【问题标题】:Mockito: how to verify method was called inside another method, which always throws Exception?Mockito:如何验证方法在另一个方法中被调用,总是抛出异常?
【发布时间】:2016-11-10 10:02:28
【问题描述】:

我正在测试一个带有预期异常的方法。 我还需要验证在抛出异常后(在模拟对象上)调用了一些代码,但验证被忽略了。 代码如下:

public class ExceptionHandler {

    @Autowired
    private Sender sender;

    public void handle(Exception exception) throws Exception {
      if (!SomeException.class.isAssignableFrom(exception.getClass())) {
        sender.sendMessage(ExceptionUtils.getStackTrace(exception));
      }
      throw exception;
    }
}

这里是测试代码:

@Mock
private Sender sender;

@InjectMocks
private ExceptionHandler handler;

@Test
public void testHandler() throws Exception {
    SomeException someException = new SomeException();

    try {
        handler.handle(someException);
    } catch (SomeException thrownResult) {
        assertEquals(someException, thrownResult);
    }

    verify(sender, times(1)).sendMessage(Mockito.anyString());
}

【问题讨论】:

    标签: junit exception-handling mockito


    【解决方案1】:

    我还需要验证是否调用了某些代码(在模拟对象上) 抛出异常后,但验证被忽略。

    这不是真的,这一行是实际执行的:

    verify(sender, times(1)).sendMessage(Mockito.anyString());
    

    但验证失败并出现此错误:

    需要但未调用:sender.sendMessage();

    <...>

    实际上,与此模拟的交互为零。

    正如预期的那样,该方法从未被调用,因为条件 !SomeException.class.isAssignableFrom(exception.getClass()) 未被满足 - 您使用 SomeException 的实例调用 handler.handle。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-05-05
      • 1970-01-01
      • 2011-04-23
      • 2019-04-26
      • 1970-01-01
      • 1970-01-01
      • 2023-03-09
      相关资源
      最近更新 更多