問題描述
我有一個要模擬的簡單類 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();
我在模擬對象中設置了 name
,但是當我調用 getter 獲取名稱時,它返回 null.
I set name
in mocked object, but when I call getter to get the name it returns null.
這是 Mockito 特有的問題,還是模擬對象無法設置值的約定?這是為什么?模擬對象下面發生了什么?
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
的 實際 代碼無關緊要,因為你在嘲笑它...而 Mockito 不知道 setName
和 getName
之間存在關系.它不假定它應該將參數存儲到 setName
并在調用 getName
時返回它......它 可以 這樣做,但是據我所知,它沒有.Mockito 提供的 mock 只允許您指定在其上調用方法時會發生什么,并檢查以后調用了什么 .您可以模擬對 getName()
的調用,而不是調用 setName
,并指定它應該返回的內容...
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
而不是模擬它.不要認為您必須在測試中模擬所有內容.當您使用真實課程時,只需模擬(或偽造)尷尬的事情,例如因為它使用文件系統或網絡.
... 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.
這篇關于將值設置為模擬對象但獲取 null的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!