是否可以验证在Mockito中以不同线程运行的模拟方法?

kuh*_*yan 19 java mocking mockito powermock

我有一个像下面这样的方法,

public void generateCSVFile(final Date billingDate) {
    asyncTaskExecutor.execute(new Runnable() {
        public void run() {
            try {
                accessService.generateCSVFile(billingDate);
            } catch (Exception e) {
                LOG.error(e.getMessage());
            }
        }
    });
}
Run Code Online (Sandbox Code Playgroud)

我嘲笑:

PowerMockito.doNothing().when(accessService).generateCSVFile(billingDate);
Run Code Online (Sandbox Code Playgroud)

但是当我验证时:

verify(rbmPublicViewAccessService, timeout(100).times(1)).generateCSVFile(billingDate);
Run Code Online (Sandbox Code Playgroud)

它给了我没有被调用.这是因为它是通过单独的线程调用的,是否可以验证在不同线程中调用的方法?

Tom*_*lst 36

当您验证调用时,很可能Runnable尚未执行asyncTaskExecutor,导致单元测试中出现验证错误.

解决此问题的最佳方法是在验证调用之前加入生成的线程并等待执行.

如果你无法获得线程的实例,可能的解决方法是模拟asyncTaskExecutor并实现它,以便它直接执行runnable.

private ExecutorService executor;

@Before
public void setup() {
    executor = mock(ExecutorService.class);
    implementAsDirectExecutor(executor);
}

protected void implementAsDirectExecutor(ExecutorService executor) {
    doAnswer(new Answer<Object>() {
        public Object answer(InvocationOnMock invocation) throws Exception {
            ((Runnable) invocation.getArguments()[0]).run();
            return null;
        }
    }).when(executor).submit(any(Runnable.class));
}
Run Code Online (Sandbox Code Playgroud)


Fra*_*ens 12

我遇到了同样的问题并玩了超时参数 http://javadoc.io/page/org.mockito/mockito-core/latest/org/mockito/Mockito.html#22 但是参数0就像在

verify(someClass, timeout(0)).someMethod(any(someParameter.class));
Run Code Online (Sandbox Code Playgroud)

它有效.我假设测试线程产生,因此另一个线程有机会完成其工作,适当地调用模拟.它仍然闻起来像一个黑客.