1
public class VerifyClass {
public VerifyClass() {
System.out.println("Verify Class constructor called");
}
public int getSum(int a,int b){
System.out.println("get sum called");
return a+b;
}
}
上述類的getSum()
方法是通過spy()
測試。以下是如何使用間諜。間諜的Mockito不列入調用真實對象
@Test
public void testSpy(){
VerifyClass ob=new VerifyClass();
VerifyClass spy=Mockito.spy(ob);
Mockito.when(spy.getSum(1,2)).thenReturn(4);
System.out.println("after when :" + spy.getSum(1,2));
assertEquals(4, spy.getSum(1,2));
}
該assertEquals
通過。據我所知,間諜應該調用真正的對象的方法。在這種情況下,getSum()
應該返回3和控制檯顯示
Verify Class constructor called
get sum called
after when :4
相反,它返回它在thenReturn(4)
分配4。請澄清一下嗎?