【问题标题】:Junit Test for Exception in a @InjectMocks class@InjectMocks 类中的异常的 Junit 测试
【发布时间】:2020-08-07 12:15:06
【问题描述】:

我的应用程序中有以下代码。

有人可以帮我写一个测试用例吗?

Service.java

```public class Service{
public void createMessage(){
try{
LOG.info("message sent");
}catch(JAXBException){
LOG.info("exception occured");
}
}```

ServiceTest.java

```public class ServiceTest{
@InjectMocks
Service service;

@Test
public void testCreateMessageException(){
doThrow(JAXBException.class).when(service.createMessage));
}```

我尝试了上述测试用例,但它给了我以下错误。 org.mockito.exceptions.misusing.MissingMethodInvocationException: when() 需要一个参数,该参数必须是“模拟方法调用”。 例如: when(mock.getArticles()).thenReturn(articles);

【问题讨论】:

  • 首先,测试不正确。 1) Service.createMessage() 不会抛出 JAXBException,因为它已经在方法调用中处理。 2)when() 不适用于返回类型为void 的方法 3)共享代码中的service.createMessage 不是方法调用 4)when() 的使用不正确 5)使用@Mock 而不是@InjectMocks , 后来是为了不同的目的。请分享实际代码,以便我们为您提供帮助。

标签: java spring exception junit mockito


【解决方案1】:

错误的原因是使用doThrow().when()时很常见的错误。 所以你写道:

doThrow(JAXBException.class).when(service.createMessage());

应该是:

doThrow(JAXBException.class).when(service).createMessage();

【讨论】:

    【解决方案2】:

    您的理解是正确的,您不能在使用 @InjectMocks(被测系统)注释的服务上使用 when().then()。它必须在被测系统中自动连接的服务上使用。

    https://www.vogella.com/tutorials/Mockito/article.html

    【讨论】:

      猜你喜欢
      • 2012-04-25
      • 2011-01-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多