我在编写测试用例时使用Mockito来模拟某个类。
有没有办法在返回值之前打印一些语句?喜欢:
when(x.callFunction(10).thenReturn(new String("Hello"));
上述语句有效,但我无法执行以下操作:
when(x.callFunction(10).thenReturn({
System.out.println("Mock called---going to return hello");
return new String("Hello");});
使用 thenAnswer
,您可以在每次调用模拟方法时执行其他操作。
when(x.callFunction(10)).thenAnswer(new Answer<String>() {
public String answer(InvocationOnMock invocation) {
System.out.println("Mock called---going to return hello");
return "Hello";
}
});
另请参阅thenAnswer Vs thenReturn。
如果你要创建的对象不是final
,那么除了@Roland Weisleder 提供的thenAnswer
之外,你可以在 thenReturn
中使用带有 init block 的匿名子类,如以下示例代码:
class FoobarFactory {
public Foobar buildFoobar() {
return null;
}
}
class Foobar {
private String name;
public Foobar(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
模拟代码为:
@Test
public void testFoobar() throws Exception {
FoobarFactory foobarFactory = mock(FoobarFactory.class);
when(foobarFactory.buildFoobar()).thenReturn(new Foobar("somename") {
{
System.out.println("Creating mocked Foobar");
}
});
Foobar foobar = foobarFactory.buildFoobar();
assertThat(foobar.getName(), is("somename"));
}
其他答案,但鉴于您的最新评论:
我将在我的最终代码中使用 thenReturn。这更多的是测试我的测试代码并检查我的模拟函数是否被调用!
我有另一个想法给你:不要在该电话上返回/打印; 改用thenThrow()
!
关键是:控制台中的打印语句有时很有帮助;但它们很容易被忽略。如果整个目的是确保某个调用发生在某个模拟上;然后只需抛出异常而不是返回值。因为 JUnit 会给你直接的、难以忽视的反馈;通过测试用例失败。
你甚至可以更进一步,在该测试上提出@expected - 这样你就有一种自动测试这方面的方法 - 如果没有调用模拟;没有例外;测试将失败。