使用Mockito进行Runnable的单元测试 [英] Unit test for Runnable with Mockito
问题描述
我有一个这样的代码,我想为其编写单元测试.
I have a code like this for which I would like to write unit test.
public class TestClass {
private final Executor executor;
private final Handler handler;
TestClass(Executor executor, Handler handler) {
this.executor = executor;
this.handler = handler;
}
void doSomething(String param1) {
executor.execute(new Runnable() {
@Override
public void run() {
//do something
handler.callHandler();
}
});
}
}
如何使用Mockito/Powermockito验证callHandler()方法是否被调用.
How can I use Mockito / Powermockito to verify if the callHandler() method is invoked.
推荐答案
将模拟Handler
传递给TestClass
的构造函数.
Pass a mock Handler
to the constructor of TestClass
.
然后使用Mockito.verify()
声明已调用callHandler()
方法.
Then use Mockito.verify()
to assert that callHandler()
method was called.
您可以在CountDownLatch
上加一个倒数的答案,以使测试等待命中该处理程序.等待将涉及设置合理的超时时间,这可能很棘手,您不希望它过高,否则失败会使测试运行更长的时间,而又不会太低,以至于不会出现误报.
You can stub an answer that counts down on a CountDownLatch
to make the test wait for the handler to be hit. Waiting will involve setting a reasonable timeout, which can be tricky, you don't want it too high, or failure will make the test run much longer, and not too low so that you don't get false positives.
Handler handler = mock(Handler.class);
CountDownLatch finished = new CountDownLatch(1);
doAnswer(invocation -> {
finished.countDown();
return null;
}).when(handler).callHandler();
TestClass testClass = new TestClass(executor, handler);
testClass.doSomething("thisThing");
boolean ended = finished.await(10, TimeUnit.SECONDS);
assertThat(ended).isTrue();
verify(handler).callHandler();
绕过并发
如果仅尝试确定是否调用了处理程序,则可以使用在同一线程上执行的Executor
.这将使测试更加稳定.
Bypassing concurrency
If you're only trying to determine whether the handler is invoked you can use an Executor
that executes on the same thread. This will make for a more stable test.
Handler handler = mock(Handler.class);
Executor executor = new Executor() {
@Override
public void execute(Runnable command) {
command.run();
}
};
TestClass testClass = new TestClass(executor, handler);
testClass.doSomething("thisThing");
verify(handler).callHandler();
这篇关于使用Mockito进行Runnable的单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!