Mockito - doReturn() 和 when() 之间的区别 [英] Mockito - difference between doReturn() and when()

查看:73
本文介绍了Mockito - doReturn() 和 when() 之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用 Mockito 在 Spring MVC 应用程序中模拟我的服务层对象,我想在其中测试我的控制器方法.然而,当我一直在阅读 Mockito 的细节时,我发现方法 doReturn(...).when(...) 等价于 when(...).thenReturn(...).所以,我的问题是让两种方法做同样的事情有什么意义,或者 doReturn(...).when(...)when 之间的细微区别是什么(...).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(...)?

任何帮助将不胜感激.

推荐答案

存根的两种语法大致相同.但是,您可以总是使用 doReturn/when 进行存根;但在某些情况下,您不能使用 when/thenReturn.存根 void 方法就是这样一种方法.其他包括与 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.

when/thenReturn 给你而 doReturn/when 没有的一件事是在编译时对你返回的值进行类型检查.但是,我相信这几乎没有任何价值 - 如果类型错误,您会在运行测试后立即发现.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆