Mockito - doReturn()和when()之间的区别 [英] Mockito - difference between doReturn() and when()
问题描述
我目前正在使用Mockito来模拟Spring MVC应用程序中的服务层对象,我想在其中测试我的Controller方法。但是,正如我一直在阅读Mockito的细节,我发现方法 doReturn(...)。when(...)
相当于时(...)。thenReturn(...)
。所以,我的问题是,有两种方法可以做同样的事情或者什么是 doReturn(...)之间的细微差别。当(...)
和当(...)。thenReturn(...)
?
I am currently in the process of using Mockito to mock my service layer objects in a Spring MVC application in which I want to test my Controller methods. However, as I have been reading on the specifics of Mockito, I have found that the methods doReturn(...).when(...)
is equivalent to when(...).thenReturn(...)
. So, my question is what is the point of having two methods that do the same thing or what is the subtle difference between doReturn(...).when(...)
and when(...).thenReturn(...)
?
任何帮助将不胜感激。
Any help would be appreciated.
推荐答案
存根的两种语法大致相同。但是,您可以始终使用 doReturn / when
进行存根;但有些情况下无法使用时/ thenReturn
。挖空虚方法就是其中之一。其他包括与Mockito间谍一起使用,并且不止一次地使用相同的方法。
The two syntaxes for stubbing are roughly equivalent. However, you can always use doReturn/when
for stubbing; but there are cases where you can't use when/thenReturn
. Stubbing void methods is one such. Others include use with Mockito spies, and stubbing the same method more than once.
当/ thenReturn 时有一件事给你, doReturn /当
没有时,是在编译时对你返回的值进行类型检查。但是,我相信这几乎没有任何价值 - 如果你的类型错了,你会在你进行测试后立即发现。
One thing that when/thenReturn
gives you, that doReturn/when
doesn't, is type-checking of the value that you're returning, at compile time. However, I believe this is of almost no value - if you've got the type wrong, you'll find out as soon as you run your test.
我强烈建议仅使用 doReturn / when
。如果有的话,学习两种语法是没有意义的。
I strongly recommend only using doReturn/when
. There is no point in learning two syntaxes when one will do.
您可以在形成Mockito语法 - 对一个非常密切相关的问题的更详细的答案。
You may wish to refer to my answer at Forming Mockito "grammars" - a more detailed answer to a very closely related question.
这篇关于Mockito - doReturn()和when()之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!