我被要求模擬一個Java類,以便測試團隊可以測試他們,但當我試圖搜索不同類型的嘲笑和所有我得到與junit一起嘲笑什麼是最好的方式來嘲笑一個java類與出JUNIT
例如與junit的mockit。有人可以幫助我走出這個困惑
我被要求模擬一個Java類,以便測試團隊可以測試他們,但當我試圖搜索不同類型的嘲笑和所有我得到與junit一起嘲笑什麼是最好的方式來嘲笑一個java類與出JUNIT
例如與junit的mockit。有人可以幫助我走出這個困惑
免責聲明:我會建議你使用像JUnit的框架
然而,這是一個使用的Mockito工作的例子可以運行一個Java應用程序,並且不依賴在JUnit上。
您需要在類路徑上使用mockito-all.jar才能運行此代碼。
該課程正在測試Bar
的實施,該實施依賴於名爲Foo
的另一個類。
import static org.mockito.Mockito.verify;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
public class BarTestCase {
private Bar bar; // the class under test
@Mock
private Foo foo;
public BarTestCase() {
MockitoAnnotations.initMocks(this); // initialise Mockito
bar = new BarImpl(foo);
}
public void testSomethingWithBar() {
// given
String name = "fred";
// when
bar.getUserByFirstName(name);
// then
verify(foo).doSomething(name);
// verify(foo).doSomething(""); // un-comment this line to see the test fail
}
public static void main(String[] args) {
BarTestCase myTestCase = new BarTestCase();
myTestCase.testSomethingWithBar();
System.out.println("SUCCESS!");
}
}
這些都是其他類/您將需要運行上述測試類
public interface Bar {
void getUserByFirstName(String name);
}
public class BarImpl implements Bar {
private Foo foo;
public BarImpl(Foo foo) {
this.foo = foo;
}
@Override
public void getUserByFirstName(String name) {
foo.doSomething(name);
}
}
public interface Foo {
void doSomething(String name);
}
依賴注入救援接口。你可以把你的實現放在一個接口後面,並有兩個類實現它。一個用於實際生產代碼,一個用於測試目的。要決定使用哪一個你可以使用某種依賴注入框架,比如spring或者其他。或者你可以使用舊的學校方式來使用系統屬性來決定選擇哪個實現。檢查您的部署環境以獲取特定於環境的設置並將其用於此目的。
(也提醒大家,他們還需要檢驗真正的東西在一個點或另一個測試....)
您需要發佈於你正在嘗試做的更多的信息。從技術上講,你不需要在JUnit中使用Mockito,你也可以毫無困難地在生產代碼中使用它,但是我必須承認我從來沒有見過它 – geoand