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

编程入门 行业动态 更新时间:2024-10-21 13:43:15
本文介绍了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 可以在不考虑参数的情况下存根方法吗?

本文发布于:2023-10-31 04:47:40,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1545050.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:存根   情况下   参数   方法   Mockito

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!