問題描述
我正在嘗試使用 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 可以在不考慮參數的情況下存根方法嗎?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!