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

2022-09-01 15:10:24

我有一个如下方法,

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

我嘲笑过:

PowerMockito.doNothing().when(accessService).generateCSVFile(billingDate);

但是当我验证时:

verify(rbmPublicViewAccessService, timeout(100).times(1)).generateCSVFile(billingDate);

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


答案 1

验证调用时很可能尚未执行 ,从而导致单元测试中出现验证错误。RunnableasyncTaskExecutor

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

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

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));
}

答案 2

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

verify(someClass, timeout(0)).someMethod(any(someParameter.class));

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


推荐