我需要在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
构造函数。如何正确进行模拟?MyClass
中没有任何方法,但构造函数,myMethod
和setSize
除外 最佳答案
您可以使用部分模拟来做到这一点。这是靠近您的代码的示例。
首先是经过测试的 class 。您将需要创建它的部分模拟。应该模拟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 method pattern时经常使用它。