Mockito 可以在不考虑参数的情况下存根方法吗?

Can Mockito stub a method without regard to the argument?(Mockito 可以在不考虑参数的情况下存根方法吗?)
本文介绍了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);

或(避免nulls):

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 可以在不考虑参数的情况下存根方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

How to send data to COM PORT using JAVA?(如何使用 JAVA 向 COM PORT 发送数据?)
How to make a report page direction to change to quot;rtlquot;?(如何使报表页面方向更改为“rtl?)
Use cyrillic .properties file in eclipse project(在 Eclipse 项目中使用西里尔文 .properties 文件)
Is there any way to detect an RTL language in Java?(有没有办法在 Java 中检测 RTL 语言?)
How to load resource bundle messages from DB in Java?(如何在 Java 中从 DB 加载资源包消息?)
How do I change the default locale settings in Java to make them consistent?(如何更改 Java 中的默认语言环境设置以使其保持一致?)