如何模拟将返回非空值的多个对象



我需要帮助同时创建模拟两个对象。 如果我将第一个模拟 obj 的返回值(即模拟类 A 设置为null(,它工作正常。我正在使用注释@Mock@TestSubjectEasyMock。如果我没有将第一个模拟期望的返回设置为null,我会看到以下错误。

java.lang.IllegalStateException: last method called on mock is not a void method

这是代码,我正在尝试:

EasyMock.expect(mockClassA.getValfromDB()).andReturn(ValA);
EasyMock.replay();
EasyMock.expect(mockoClassB.makeRestCall(EasyMock.anyString())).times(2).andReturn(httpResponse);
EasyMock.replay();

如果 EasyMock 不支持在单个方法中模拟多个对象,我可以使用 Mockito、PowerMockito、EasyMockSupport。请随时从这些图书馆向我推荐一些东西。

PS:我已经尝试使用EasyMockSupport的replayall()。但这没有任何区别。

我可以调试我的代码,发现我以错误的方式给出了"不"的时间。

更改行

EasyMock.expect(mockClassB.makeRestCall(EasyMock.anyString())).times(2).andReturn(httpResponse);
EasyMock.replay();

EasyMock.expect(mockClassB.makeRestCall(EasyMock.anyString())).andReturn(httpResponse);
EasyMock.expectLastCall().times(2);
EasyMock.replay();

解决了我的问题(观察expectLastCall.times(2)(。

参考: TutorialsPoint.com

必须将模拟传递给replay()方法。所以你的原始代码和答案都有效。但是,确实times()必须在andReturn()之后。

所以正确的代码是

expect(mockClassA.getValfromDB()).andReturn(ValA);
expect(mockClassB.makeRestCall(anyString())).andReturn(httpResponse).times(2);
replay(mockClassA, mockClassB);

或者这个与EasyMockSupport

expect(mockClassA.getValfromDB()).andReturn(ValA);
expect(mockClassB.makeRestCall(anyString())).andReturn(httpResponse).times(2);
replayAll();

请注意,我使用的是静态导入。它使代码更易于眼睛使用。

最新更新