Mockito-doReturn()和when()之间的区别

我目前正在使用Mockito在Spring MVC应用程序中模拟我的服务层对象,在该应用程序中我想测试我的Controller方法。但是,当我阅读Mockito的细节时,我发现这些方法doReturn(...).when(...)等效于when(...).thenReturn(...)。所以,我的问题是什么是有两个方法,做同样的事情或之间有什么细微的区别点doReturn(...).when(...)when(...).thenReturn(...)

任何帮助,将不胜感激。


守着星空守着你
浏览 6670回答 3
3回答

www说

如果您使用间谍对象(标有@Spy)而不是模拟对象(标有),则两种方法的行为会有所不同@Mock:when(...) thenReturn(...) 在返回指定值之前进行真正的方法调用。因此,如果被调用的方法引发Exception,则必须对其进行处理/模拟。等等。当然,您仍然可以获得结果(在中定义thenReturn(...))doReturn(...) when(...) 根本不调用该方法。例:public class MyClass {     protected String methodToBeTested() {           return anotherMethodInClass();     }     protected String anotherMethodInClass() {          throw new NullPointerException();     }}测试:@Spyprivate MyClass myClass;// ...// would work finedoReturn("test").when(myClass).anotherMethodInClass();// would throw a NullPointerExceptionwhen(myClass.anotherMethodInClass()).thenReturn("test");
打开App,查看更多内容
随时随地看视频慕课网APP