我有一个类MyClass
,它包含一个调用接口MyInterface
的构造函数。 MyInterface
包含接受validator
和Int
的方法String
。
我需要使用EasyMock在JUnit测试中模拟来自Boolean
的返回MyInterface.validator
值。
我尝试从MyInterface.validator
调用MyClass
时,我在这个问题上做了几次尝试,我只获得了Java Exceptions。
public class MyClass {
public MyInterface myInterface;
public int test;
public MyClass (int INT, String STRING, MyInterface myInterface) {
this.myInterface = myInterface;
this.test = INT;
myInterface.validator(INT, STRING);
}
}
public interface MyInterface {
public Boolean validator(int INT, String STRING);
}
public class MyClassTest {
MyInterface mockMyInterface;
MyClass myClass;
@Before
public void setUp() throws Exception {
mockMyInterface = createMock(MyInterface.class);
}
@Test
public void test() {
myClass = new MyClass(10, "Test", mockMyInterface);
expect(mockMyInterface.validator(10, "Test")).andStubReturn(true);
replay(mockMyInterface);
assertEquals(myClass.test, 10);
verify(mockMyInterface);
}
}
答案 0 :(得分:0)
您必须在使用之前配置模拟期望。您的构造函数调用mock,因此您应该在创建MyClass实例之前对其进行配置。
试试这个:
public class MyClassTest {
MyInterface mockMyInterface;
MyClass myClass;
@Before
public void setUp() throws Exception {
mockMyInterface = createMock(MyInterface.class);
}
@Test
public void test() {
expect(mockMyInterface.validator(10, "Test")).andStubReturn(true);
replay(mockMyInterface);
myClass = new MyClass(10, "Test", mockMyInterface);
assertEquals(myClass.test, 10);
verify(mockMyInterface);
}
}