0

我正在尝试对一个类进行单元测试。班级如下

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes=MyConfig.class)
Class MyTest{

 @Mock
 pirvate JmsTemplate jmsTemplate;


  @InjectMocks
  private final ProductService productService= new ProductService();

  @Test
      public void sendItem(){
             Item i = new Item();
             i.name("xyz");
            productService.send(i)
            verfity(jmsTemplate).convertAndSend("product.test",i)
      }
}

@Configuration
@PropertySource(classpath:application-test.properties)
class MyConfig{

  @Bean
  ProductService productService(){
    return new ProductService();
  }

  @Bean
  JmsTemplate jmsTemplate(){
     return new JmsTemplate();
  }
}

resources folder under test package has

application.properties, contents of it are

spring.profiles.active=test

And application-test.properties has
queue.name=product.test

我的 productService 类如下

class ProductService{
  @Autowired
    JmsTemplate jmsTemplate;

   @Value("${queue.name}")
    private String queue;

    public void send(Item i){
         jmsTemplate.convertAndSend(queue,i)
    }
}

当我运行上面的测试用例时,我得到,

我得到了 mockito 想要但没有被调用,实际上与这个 mock 的交互为零。但是传递给 convertAndSend 方法的参数匹配任何人都可以提出一些解决方案。

4

1 回答 1

1

您注入测试的 bean 似乎不是 Spring 管理的。那这个呢?

@MockBean
private JmsTemplate jmsTemplate;

@Autowired
private ProductService productService;
于 2018-11-10T20:07:46.760 回答