Unit test for Runnable with Mockito

♀尐吖头ヾ 提交于 2019-12-05 21:41:59

Pass a mock Handler to the constructor of TestClass.

Then use Mockito.verify() to assert that callHandler() method was called.

Involving concurrency

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

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();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!