简体   繁体   English

Mockito-参数捕获器未捕获且没有交互

[英]Mockito - Argument Captor not capturing and no interactions

I'm working on some old code that does not handle exceptions very well. 我正在处理一些不能很好地处理异常的旧代码。 One test I'm writing, stubs a method that throws an exception, which I need to confirm is the correct exception. 我正在编写的一个测试将一个引发异常的方法存根,我需要确认的是正确的异常。 The only way to test this exception that I can see, is to capture the argument when it is being logged and compare the strings. 我可以看到,测试此异常的唯一方法是在记录参数时捕获参数并比较字符串。

When I run this I get: 当我运行它时,我得到:

Wanted but not invoked: logger.error(Capturing argument) 想要但不被调用:logger.error(捕获参数)

Actually there were zero interactions with this mock 实际上,此模拟游戏的互动为零

@Test
public void testRunCipherThrowsException() throws Exception
{
    final Logger logger = mock(Logger.class);
    ArgumentCaptor<Logger> argument = ArgumentCaptor.forClass(Logger.class);

    when(cipher.doSomething(any(byte[].class))).thenThrow(new IllegalBlockSizeException("Bad block size"));
    Mockito.verify(logger).error(argument.capture());

    _task.run();

    assertEquals("The execution failed.  Details: Bad block size", argument.getValue().getName());
}

Here is a snippet from the class I am testing - in debug I am hitting that line of code every time. 这是我正在测试的类的摘录-在调试中,我每次都碰到那行代码。

try
{

final byte[] result = cipher.doSomething(testData);

catch (final Exception ex)
    {
        _consequtiveFailures++;
        _logger.error("The execution failed.  Details: " + ex.getMessage(), ex);
    }

I've tried to arrange the test a few different ways thinking the verify might not be getting setup correctly. 我试图以几种不同的方式来安排测试,认为验证可能无法正确设置。 I have also tried a few different ways of setting of the mock Logger object. 我还尝试了几种不同的设置模拟Logger对象的方法。 It is my first time using argument captor, so hopefully I'm just missing something obvious. 这是我第一次使用参数捕获器,所以希望我只是缺少一些明显的东西。

final Logger logger = mock(Logger.class); 最终的Logger logger =模拟(Logger.class);

This is a logger instance you have created locally for your test method; 这是您在本地为测试方法创建的记录器实例; it will therefore not be used by the class you are testing. 因此,您正在测试的类将不会使用它。 You need to at least spy() the actual logger instance. 您至少需要spy()实际的记录器实例。

What is more, you verify() after you execute (I guess here that _task.run() executes the code which will trigger the exception); 更重要的是,您执行 verify() (我猜这里_task.run()执行将触发异常的代码); which means that even if you spied on the correct Logger instance, at the time you verify() it, there will be nothing. 这意味着即使您监视了正确的Logger实例,在您verify()时,也不会有任何结果。

So: 所以:

  • actually mock, or spy, the actual logger used by _task ; 实际模拟或监视_task使用的实际记录器;
  • verify mock/spy interactions ( Mockito.verify() works for both) after you have executed the method. 执行方法后,验证模拟/间谍交互( Mockito.verify()都适用)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM