我知道您可以验证被监视对象的方法被调用的次数。您能验证方法调用的结果吗?
类似下面的内容?
verify(spiedObject, didReturn(true)).doSomething();
要验证它被调用的次数,请使用verify(spiedObject, times(x)).doSomething()
。
你不应该验证从监视对象返回的值。它不是要测试的对象,所以为什么要验证它返回的内容。相反,验证被测对象响应从监视返回的值的行为。
另外,如果您不知道被监视对象将返回什么值,那么最好使用mock而不是监视。
我提供了一个测试模板,您想要验证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是否返回结果值。例如,在测试的方法中有两个内部方法调用将产生相同的值。两者都被调用,但只有其中一个产生所需的结果。