我一直无法找到一种方法来使用“Deep Stubs”对 Mockito 中的间谍进行存根方法。我想做的是这样的:
@Spy private Person person = //retrieve person
@Test
public void testStubbed() {
doReturn("Neil").when(person).getName().getFirstName();
assertEquals("Neil", person.getName().getFirstName());
}
Run Code Online (Sandbox Code Playgroud)
上面的代码编译没有问题,但在运行测试时,它失败,说明 getName() 无法返回返回类型(在本例中为 Name 类)。
通常,在模拟时,您必须使用
@Mock(answer = Answers.RETURNS_DEEP_STUBS)每个模拟对象。不过spy好像没有这样的东西。
有没有人曾经使用间谍成功地进行过深度模拟?
下面列出了我收到的错误:
String cannot be returned by getName()
getName() should return Name
Due to the nature of the syntax above problem might occur because of:
1. Multithreaded testing
//I'm not doing multithreaded testing
2. A spy is stubbed using when(spy.foo()).then() syntax. It is safer to stub spies with doReturn|Throw() family …Run Code Online (Sandbox Code Playgroud)