我正在使用 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()
我发现(如此简单!)应该使用以下方式声明另一个 void 方法EasyMock.expectLastCall()
您的反射代码看起来不错。
我已经很久没有使用EasyMock了,但还没有replay
在测试中每个模拟只应该调用一次?你调用它两次。尝试摆脱第一个replay
call.
在这种情况下,将包含模拟的字段公开是否有意义?一般来说,协作者应该通过构造函数或设置器来设置,从而根本不需要反射。
编辑 - 根据您的更新 - 错误表明setDataType
在模拟中被调用,但模拟并不期望它被调用。也许你的类调用它两次,也许它被乱序调用,或者使用你不期望的参数调用它(尽管我希望在这种情况下错误会有所不同)。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)