Mockito可以在不考虑参数的情况下对方法进行存根吗? [英] Can Mockito stub a method without regard to the argument?

查看:120
本文介绍了Mockito可以在不考虑参数的情况下对方法进行存根吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Mockito测试一些旧代码.

I'm trying to test some legacy code, using Mockito.

我想存根如下生产中使用的FooDao:

I want to stub a FooDao that is used in production as follows:

foo = fooDao.getBar(new Bazoo());

我可以写:

when(fooDao.getBar(new Bazoo())).thenReturn(myFoo);

但是明显的问题是,getBar()从未与我为该方法存根的同一Bazoo对象一起调用. (请问new运算符!)

But the obvious problem is that getBar() is never called with the same Bazoo object that I stubbed the method for. (Curse that new operator!)

如果可以将方法存根以使其返回myFoo而不考虑参数,我会喜欢它.失败的话,我会听取其他解决方法的建议,但我真的想避免更改生产代码,直到有合理的测试范围为止.

I would love it if I could stub the method in a way that it returns myFoo regardless of the argument. Failing that, I'll listen to other workaround suggestions, but I'd really like to avoid changing the production code until there is reasonable test coverage.

推荐答案

when(
  fooDao.getBar(
    any(Bazoo.class)
  )
).thenReturn(myFoo);

或(避免null s):

when(
  fooDao.getBar(
    (Bazoo)notNull()
  )
).thenReturn(myFoo);

别忘了导入匹配器(还有许多其他匹配器):

Don't forget to import matchers (many others are available):

对于Mockito 2.1.0及更高版本:

For Mockito 2.1.0 and newer:

import static org.mockito.ArgumentMatchers.*;

对于旧版本:

import static org.mockito.Matchers.*;

这篇关于Mockito可以在不考虑参数的情况下对方法进行存根吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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