問題描述
我有一個(gè)要模擬的簡單類 Foo
:
I have a simple class Foo
to be mocked:
public class Foo {
private String name;
public Foo() {
}
public Foo(String name) {
this.name = name;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
在我的單元測試代碼中,我使用 Mockito 來模擬它.
In my unit test code, I mock it by using Mockito.
Foo mockedFoo = Mockito.mock(Foo.class);
mockedFoo.setName("test");
// name is null
String name = mockedFoo.getName();
我在模擬對象中設(shè)置了 name
,但是當(dāng)我調(diào)用 getter 獲取名稱時(shí),它返回 null.
I set name
in mocked object, but when I call getter to get the name it returns null.
這是 Mockito 特有的問題,還是模擬對象無法設(shè)置值的約定?這是為什么?模擬對象下面發(fā)生了什么?
Is it a Mockito specific issue or is it an convention that mocked object can't set value? Why is that? What is happening underneath with mocked object?
推薦答案
嗯,是的 - Foo
的 實(shí)際 代碼無關(guān)緊要,因?yàn)槟阍诔靶λ?..而 Mockito 不知道 setName
和 getName
之間存在關(guān)系.它不假定它應(yīng)該將參數(shù)存儲(chǔ)到 setName
并在調(diào)用 getName
時(shí)返回它......它 可以 這樣做,但是據(jù)我所知,它沒有.Mockito 提供的 mock 只允許您指定在其上調(diào)用方法時(shí)會(huì)發(fā)生什么,并檢查以后調(diào)用了什么 .您可以模擬對 getName()
的調(diào)用,而不是調(diào)用 setName
,并指定它應(yīng)該返回的內(nèi)容...
Well yes - the actual code of Foo
doesn't matter, because you're mocking it... and Mockito doesn't know there's meant to be a relationship between setName
and getName
. It doesn't assume that it should store the argument to setName
and return it when getName
is called... it could do that, but it doesn't as far as I'm aware. The mock provided by Mockito just allows you to specify what happens when methods are called on it, and check what was called later on. Instead of calling setName
, you could mock a call to getName()
and specify what it should return...
... 或者您可以直接使用 Foo
而不是模擬它.不要認(rèn)為您必須在測試中模擬所有內(nèi)容.當(dāng)您使用真實(shí)課程時(shí),只需模擬(或偽造)尷尬的事情,例如因?yàn)樗褂梦募到y(tǒng)或網(wǎng)絡(luò).
... or you could just use Foo
directly instead of mocking it. Don't think you have to mock everything in your tests. Just mock (or fake) things that are awkward when you're using the real class, e.g. because it uses the file system or network.
這篇關(guān)于將值設(shè)置為模擬對象但獲取 null的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!