-1

我有一个需要测试的 Mainclass,它依赖于其他类。现在我正在为该类创建一个模拟 How to test void methods using easymock

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
}
4

2 回答 2

0

Easymock 文档中所述,您不要将方法放在 a 中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
于 2013-08-24T01:01:49.263 回答
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;
 }
}


}

不客气。

于 2015-08-06T15:52:35.603 回答