【问题标题】:How to set expectation to params passed to void methods using EasyMock如何使用 EasyMock 为传递给 void 方法的参数设置期望
【发布时间】:2012-04-07 13:20:06
【问题描述】:

我正在使用 EasyMock 和 EasyMock CE 3.0 来模拟依赖层并测试我的类。以下是我无法找到任何解决方案的场景

我有要测试的类,它调用一个依赖类void 方法,该方法接受输入参数并更改相同的参数。我正在测试的方法是根据更改的参数进行一些操作,我现在必须针对各种场景进行测试

考虑下面的示例,我尝试在其中放置相同的场景

public boolean voidCalling(){
    boolean status = false;
    SampleMainBean mainBean = new SampleMainBean();
    dependentMain.voidCalled(mainBean);
    if(mainBean.getName() != null){
        status = true; 
    }else{
        status = false;
    }
    return status;
}

以及dependentMain类下面的方法

public void voidCalled(SampleMainBean mainBean){
    mainBean.setName("Sathiesh");
}

为了全面覆盖,我需要 2 个测试用例来测试返回 true 和 false 的场景,但我总是得到 false,因为我无法设置 void 方法的行为来更改此输入 bean .在这种情况下,如何使用 EasyMock 获得真实的结果

提前感谢您的帮助。

【问题讨论】:

    标签: easymock


    【解决方案1】:

    从这个答案中的答案开始:EasyMock: Void Methods,可以使用IAnswer

    // create the mock object
    DependentMain dependentMain = EasyMock.createMock(DependentMain.class);
    
    // register the expected method
    dependentMain.voidCalled(mainBean);
    
    // register the expectation settings: this will set the name 
    // on the SampleMainBean instance passed to voidCalled
    EasyMock.expectLastCall().andAnswer(new IAnswer<Object>() {
        @Override
        public Object answer() throws Throwable {
            ((SampleMainBean) EasyMock.getCurrentArguments()[0])
                    .setName("Sathiesh");
            return null; // required to be null for a void method
        }
    });
    
    // rest of test here
    

    【讨论】:

      【解决方案2】:

      感谢您的回复.. 我的问题已解决... :) 也感谢您提供示例代码。

      使用上面的代码 sn-p,我必须做的一个改变是,

      // register the expected method
      dependentMain.voidCalled((SampleMainBean) EasyMock.anyObject());
      

      这样就可以在要测试的方法中获取更新的bean了。

      再次感谢您的帮助。

      【讨论】:

        猜你喜欢
        • 2013-06-12
        • 1970-01-01
        • 1970-01-01
        • 2012-12-04
        • 1970-01-01
        • 2018-02-12
        • 1970-01-01
        • 2010-09-28
        • 1970-01-01
        相关资源
        最近更新 更多