問題描述
我是開發新手,尤其是單元測試新手.我想我的要求很簡單,但我很想知道其他人對此的想法.
I am a newbie to development and to unit tests in particular . I guess my requirement is pretty simple, but I am keen to know others thoughts on this.
假設我有兩個這樣的課程 -
Suppose I have two classes like so -
public class First {
Second second ;
public First(){
second = new Second();
}
public String doSecond(){
return second.doSecond();
}
}
class Second {
public String doSecond(){
return "Do Something";
}
}
假設我正在編寫單元測試來測試 First.doSecond()
方法.但是,假設我想像這樣模擬 Second.doSecond()
類.我正在使用 Mockito 來做到這一點.
Let's say I am writing unit test to test First.doSecond()
method. However, suppose, i want to Mock Second.doSecond()
class like so. I am using Mockito to do this.
public void testFirst(){
Second sec = mock(Second.class);
when(sec.doSecond()).thenReturn("Stubbed Second");
First first = new First();
assertEquals("Stubbed Second", first.doSecond());
}
我看到模擬沒有生效并且斷言失敗.有沒有辦法模擬我要測試的類的成員變量.?
I am seeing that the mocking does not take effect and the assertion fails. Is there no way to mock the member variables of a class that I want to test . ?
推薦答案
你需要提供一種訪問成員變量的方法,這樣你就可以傳入一個 mock(最常見的方法是 setter 方法或構造函數一個參數).
You need to provide a way of accessing the member variables so you can pass in a mock (the most common ways would be a setter method or a constructor which takes a parameter).
如果您的代碼未提供執行此操作的方法,則它被錯誤地考慮為 TDD(測試驅動開發).
If your code doesn't provide a way of doing this, it's incorrectly factored for TDD (Test Driven Development).
這篇關于使用 Mockito 模擬類的成員變量的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!