使用EasyMock测试void方法依赖性

时间:2013-07-23 06:56:49

标签: java unit-testing junit4 easymock

我有一个需要测试的Mainclass,它依赖于其他类。 现在我正在为该类创建一个模拟器 如何使用easymock测试void方法

MainClass{

  mainClassMethod(){
    dependencyClass.returnVoidMethod();
    //other code
  }
}

TestClass{

    @Before
    setUpMethod(){
        DependencyClass dependencyClassMock = EasyMock.createMock(DependencyClass.class);
    }

    @Test
    testMainClassMethod(){
        EasyMock.expect(dependencyClassMock.returnVoidMethod()).andRetur //this is not working
        dependencyClassMock.returnVoidMethod();
        EasyMock.expectLastCall().anyTimes(); //If I use this, it is invoking the method.

    }
}
//My dependency class code
DependencyClass implements ApplicationContextAware{
    private static ApplicationContext applicationContext;
    private static final String AUTHENTICATION_MANAGER = "authenticationManagers";

    returnVoidMethod(){
        ProviderManager pm = (ProviderManager) getApplicationContext().getBean(AUTHENTICATION_MANAGER); //this is returning null

    }
     //othercode
     //getters and setters of application context
}

2 个答案:

答案 0 :(得分:0)

Easymock Documentation中所述,您不会将方法放在expect()内(因为没有返回)。您可以单独调用模拟方法,如果它处于“记录”模式,则表示期望。

dependencyClassMock.returnVoidMethod();

如果您需要抛出异常或者说该方法可以调用anyTimes(),您可以使用expectLastCall()

@Test
public void testMainClassMethod(){

    dependencyClassMock.returnVoidMethod();
    EasyMock.expectLastCall().anyTimes();

    ...
     //later to replay the mock
    EasyMock.replay(dependencyClassMock);

    //now this method is actually called
    dependencyClassMock.returnVoidMethod();

}

编辑:注意到你没有dependencyClassMock作为字段:

public class TestClass{
    DependencyClass dependencyClassMock

    @Before
    setUpMethod(){
        dependencyClassMock = EasyMock.createMock(DependencyClass.class);
    }

...//rest of class is as described above

答案 1 :(得分:0)

@dkatzel 测试是完全错误的.....你手动调用一个方法,你验证它是否被调用...当然是! ......那不是正确的方式(我的意见)

更好的方法(我的意见)是扩展你想要测试的方法类,覆盖那个方法,并且在体内只是将一个布尔变量作为标志放入k现在,如果方法被调用或不。 ..你甚至不需要使用EasyMock

实施例

Class DependencyClass {
 public void returnVoidMethod() {
  [.... content ...]
 }
} 

Class A_test {

 @Test
 public void checkVoidMethodCalled() {
  A_mod obj = new A_mod();
  mainClassMethod();
  assertTrue(obj.called);
 }

Class A_mod extends DependencyClass {
 boolean called = false;

 @Override
 public void returnVoidMethod() {
  called = true;
 }
}


}

欢迎你。