【问题标题】:How to inject EasyMock mock into tested class private field如何将 EasyMock 模拟注入测试类私有字段
【发布时间】:2012-04-04 12:50:48
【问题描述】:

我正在使用 EasyMock 创建模拟,它是测试类中的私有参数之一(没有设置器)。我尝试使用反射 - 但它无法正常工作。

public class TestedClassTest{
    @Test
    public void test(){
      TestedClass instance = new TestedClass();
      MockedClass mocked = EasyMock.createMock(MockedClass.class);
      Data data = new Data();

      //Void setter
      DataType dataType = (myDataType.DataType) EasyMock.anyObject();
      mocked.setDataType(dataType);
      EasyMock.expectLastCall();

      //expect
      EasyMock.expect(mocked.getData()).andReturn(data);
      EasyMock.replay(mocked);

      Field field = instance.getClass().getDeclaredField("mockedClass")
      field.setAccessible(true);
      field.set(instance, mocked);

      //run tested method
      instance.someAction();

      EasyMock.verify(mocked);
   }
}

我收到失败的信息:

Unexpected method call MockedClass.setDataType(myData.MyData@104306d75):
MockedClass.getData(): expected: 1, actual: 0
junit.framework.AssertionFailedError: 
Unexpected method call MockedClass.setDataType(myData.MyData@132006d75):
MockedClass.getData(): expected: 1, actual: 0

我确定在测试“instance.someAction()”期间在“MockedClass”对象上触发了此方法

如何解决这个问题?

已编辑 - 答案: 更正双倍的replay.mocked() 后,我发现(太简单了!)应该使用EasyMock.expectLastCall() 声明另外一个 void 方法

【问题讨论】:

    标签: java reflection junit easymock


    【解决方案1】:

    您的反射代码看起来不错。

    我已经很久没有使用 EasyMock 了,但是 replay 不是应该在测试中每个模拟只调用一次吗?您正在调用它两次。尝试摆脱第一个 replay 呼叫。

    在这种情况下,将包含模拟的字段公开是否有意义?一般来说,协作者应该通过构造函数或设置器来设置,完全不需要反射。

    编辑——根据您的更新——错误表明在模拟上调用了setDataType,但模拟并不期望它被调用。也许你的类调用了它两次,也许它被乱序调用,或者用你没想到的参数调用它(尽管我希望在这种情况下错误会有所不同)。

    【讨论】:

    • 已更正,但仍有类似问题
    • 同时做太多事情,抱歉。现在只有一个回放。根据您关于公共设置器的问题 - 没有这种可能性,因为无法更改测试类。
    • @Marcin,结果是什么?
    • 我想在这里做最后的回答——怎么做?编辑问题或使用“回答您的问题”。顺便说一句 - 谢谢!
    • 更新问题,或提供您自己的答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-23
    • 1970-01-01
    • 2013-05-01
    • 1970-01-01
    相关资源
    最近更新 更多