[英]How to mock a method which is called by another method using EasyMock?
我需要在void方法中模擬一個方法。
這是我的示例代碼:
class MyClass {
public MyClass(Session s, Boolean b1, Boolean b2)
void myMethod(some paramaters...) {
// some code
int count= setSize();
}
int setSize() {
// some calculation....
return size;
}
現在在我的測試類中,我想模擬setSize()
來返回我自己的值300
。
我喜歡:
MyClass mockclass = createNiceMock(MyClass.class);
EasyMock.expect(mockimplyZero.setBatchSize()).andReturn(Integer.valueOf(300));
mockclass.myMethod(parameters....)
當調用myMethod
,它無法正確進入方法。 我認為可能是EasyMock正在為MyClass
構造函數設置默認值。 如何正確地進行模擬?
除了constructor, myMethod
和setSize
之外, MyClass
中沒有方法
你可以使用部分模擬來做到這一點。 這是一個接近您的代碼的示例。
首先是測試類。 您需要創建一個部分模擬它。 應該myMethod
getSize
,但是myMethod
應該是測試方法。
此外,通常,您需要調用構造函數來正確初始化類(經典模擬不會調用任何構造函數)。
class MyClass {
private boolean b1;
private boolean b2;
public MyClass(boolean b1, boolean b2) {
this.b1 = b1;
this.b2 = b2;
}
int myMethod() {
return getSize();
}
int getSize() {
return 42;
}
public boolean getB1() {
return b1;
}
public boolean getB2() {
return b2;
}
}
然后測試將如下
import org.junit.Test;
import static org.easymock.EasyMock.*;
import static org.junit.Assert.*;
public class MyClassTest {
@Test
public void test() {
// Create a partial mock by calling its constructor
// and only mocking getSize
MyClass mock = createMockBuilder(MyClass.class)
.withConstructor(true, true)
.addMockedMethod("getSize")
.createMock();
// Record that getSize should return 8 (instead of 42)
expect(mock.getSize()).andReturn(8);
// All recording done. So put the mock in replay mode
replay(mock);
// Then, these assertions are to prove that the partial mock is
// actually doing what we expect. This is just to prove my point. Your
// actual code will verify that myMethod is doing was is expected
// 1. Verify that the constructor was correctly called
assertEquals(true, mock.getB1());
assertEquals(true, mock.getB2());
// 2. Verify that getSize was indeed mocked
assertEquals(8, mock.myMethod());
// Check everything expected was indeed called
verify(mock);
}
}
任務完成。 請注意,這不一定是糟糕設計的標志。 我經常在測試Template方法模式時使用它。
在同一個類上測試另一個方法時,不應該模擬一個方法。 理論上你可以這樣做(例如使用Mokito 間諜 )。
從這個意義上說,你在錯誤的層面上接近這個:你實際上不應該關心你的測試方法在你測試的類中調用哪些其他方法。 但是如果你必須適應測試的東西,那么前進的方法將是(例如)一種方法,允許你的測試代碼在調用mymethod()
之前設置該大小字段。
或者:你分開關注點,並將“大小”部分移動到它自己的類X.然后你的測試類可以保存一個X的實例; 然后可以嘲笑那個實例。
簡而言之:您想退一步閱讀一些有關如何使用EasyMock的教程。 這不是你可以通過反復試驗來學習的東西。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.