28
24

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Mockitoによる非同期処理のテスト

Last updated at Posted at 2014-06-07

Javaのユニットテストで非同期処理をテストしたい場合、
MockitoVerificationWithTimeoutを使うと簡潔にテストを記述できます。

例として、非同期処理Foo#requestとそのテストコードを示します。
このテストはFoo#requestの中でCallback#onSuccessが10秒以内に呼ばれることを確認します。

timeoutメソッドが肝です。timeoutの引数にはタイムアウト値をミリ秒単位で指定します。

Foo.java
public class Foo {
	public static void request(Callback callback) {
		new Thread() {
			...
			callback.onSuccess();
		}.start();
	}
}
FooTest.java
import static org.mockito.Mockito.*;

public class FooTest {
	@Test
	public void test() {
		Callback callbackMock = mock(Callback.class);
		Foo.request(callbackMock);

		verify(callbackMock, timeout(10000)).onSuccess();
	}
}

更に、timesを指定することもできます。

FooTest.java
import static org.mockito.Mockito.*;

public class FooTest {
	@Test
	public void test() {
		Callback callbackMock = mock(Callback.class);
		Foo.request(callbackMock);

		verify(callbackMock, timeout(10000).times(2)).onSuccess();
	}
}
28
24
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
28
24

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?