使用EasyMock测试void方法依赖关系



我有一个需要测试的Mainclass,它依赖于其他类。现在我正在为该类创建一个mock如何使用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
}

如Easymock文档中所述,您不会将方法放入expect()中(因为没有返回)。你可以自己调用mocked方法,如果它处于"记录"模式,那么它就隐含了一个期望。

dependencyClassMock.returnVoidMethod();

如果你需要抛出一个Exception,或者说这个方法可以调用anyTime(),你可以使用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

@dkatzel测试完全错误。。。。。您正在手动调用一个方法,然后验证它是否被调用。。。当然是。。。这不是正确的方式(我认为)

一个更好的方法(我的观点)是扩展你想要测试的mehod类,覆盖该方法,然后在主体中放一个布尔变量作为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;
 }
}

}

不客气。

最新更新