スパイされたオブジェクトのメソッドが呼び出された時間を確認できることは知っています。メソッド呼び出しの結果を確認できますか?
以下のようなものですか?
verify(spiedObject, didReturn(true)).doSomething();
呼び出された回数を確認するには、 を使用しますverify(spiedObject, times(x)).doSomething()
。
スパイされたオブジェクトから返された値を検証するべきではありません。これはテスト対象のオブジェクトではないため、返されるものを確認する必要があります。代わりに、スパイから返された値に応じて、テスト対象のオブジェクトの動作を確認します。
また、スパイされたオブジェクトによって返される値がわからない場合は、スパイの代わりにモックを使用することをお勧めします。
TL;DR SpyBeanメソッドが返す
ものを確認するためのテスト用のテンプレートを提供しています。テンプレートは Spring Boot を使用しています。
@SpringJUnitConfig(Application.class)
public class Test extends SpringBaseTest
{
@SpyBean
<replace_ClassToSpyOn> <replace_classToSpyOn>;
@InjectMocks
<replace_ClassUnderTest> <replace_classUnderTest>;
// You might be explicit when instantiating your class under test.
// @Before
// public void setUp()
// {
// <replace_classUnderTest> = new <replace_ClassUnderTest>(param_1, param_2, param_3);
// }
public static class ResultCaptor<T> implements Answer
{
private T result = null;
public T getResult() {
return result;
}
@Override
public T answer(InvocationOnMock invocationOnMock) throws Throwable {
result = (T) invocationOnMock.callRealMethod();
return result;
}
}
@org.junit.Test
public void test_name()
{
// Given
String expString = "String that the SpyBean should return.";
// Replace the type in the ResultCaptor bellow from String to whatever your method returns.
final Test.ResultCaptor<String> resultCaptor = new Test.ResultCaptor<>();
doAnswer(resultCaptor).when(<replace_classToSpyOn>).<replace_methodOnSpyBean>(param_1, param_2);
// When
<replace_classUnderTest>.<replace_methodUnderTest>(param_1, param_2);
// Then
Assert.assertEquals("Error message when values don't match.", expString, resultCaptor.getResult());
}
}
これで邪魔になりません。SpyBean が結果値を返すことを確認したい場合があります。たとえば、テスト対象のメソッドには、同じ値を生成する 2 つの内部メソッド呼び出しがあります。両方が呼び出されますが、必要な結果を生成するのはそのうちの 1 つだけです。