java - 无法运行 Junit 案例。抛出错误 "Actually there were zero interactions with this mock"

标签 java junit mockito spring-junit

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

@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但没有被调用, 实际上,与这个模拟的互动为零。 但传递给 ConvertAndSend 方法的参数匹配 谁能提出一些解决方案。

最佳答案

您注入(inject)测试的bean似乎不受Spring管理。那这个呢?

@MockBean
private JmsTemplate jmsTemplate;

@Autowired
private ProductService productService;

关于java - 无法运行 Junit 案例。抛出错误 "Actually there were zero interactions with this mock",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53242505/

相关文章:

java - Java中如何在打开新线程之前关闭线程?

java - 机器人框架 - 来自谷歌文档的示例不起作用

java - Mockito - 验证目标类方法内另一个对象的方法调用

Java Junit4 支持扩展基类

java - 如何正确匹配 Mockito 中的可变参数

java - 如何在 tomcat 服务器上运行两个具有不同 spring 配置文件的 WAR 文件?

java - 使用自定义编码器的 REST+Spring+POST

java - 在远程 teamcity 构建代理上运行 selenium 自动化测试

java - 使用 JUnit 和 Mockito 测试方法以增强分支覆盖率

android - 模块中未列出的模拟依赖项