使用EasyMock模拟接受参数的接口

时间:2016-02-17 17:49:04

标签: java unit-testing junit easymock

我有一个类MyClass,它包含一个调用接口MyInterface的构造函数。 MyInterface包含接受validatorInt的方法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);
}
}

1 个答案:

答案 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);
  }
}