【问题标题】:Using EasyMock to mock an interface that accepts arguments使用 EasyMock 模拟接受参数的接口
【发布时间】:2016-02-17 17:49:03
【问题描述】:

我有一个类MyClass,它包含一个调用接口MyInterface 的构造函数。 MyInterface 包含一个方法 validator,它接受 IntString

我需要使用 EasyMock 在 JUnit 测试中模拟来自 MyInterface.validator 的返回 Boolean 值。

我对此进行了多次尝试,当我尝试从 MyClass 调用 MyInterface.validator 时,我只收到 Java 异常。

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

【问题讨论】:

    标签: java unit-testing junit easymock


    【解决方案1】:

    您必须在使用前配置模拟期望。您的构造函数调用模拟,因此您应该在创建 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);
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-20
      • 1970-01-01
      • 2023-03-08
      • 2014-11-18
      相关资源
      最近更新 更多