如何模拟多个 return 非空值的对象

How to mock multiple objects which will return non-null values

我需要帮助同时创建模拟两个对象。 如果我将第一个模拟对象(即 mockClassA)的 return 值设置为 null,它工作正常。我正在使用 EasyMock 的注释 @Mock@TestSubject。如果我没有将第一个模拟期望的 return 设置为 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。也请随时向我推荐来自这些图书馆的一些东西。

P.S:我已经尝试使用 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))。

Ref: 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();

请注意,我使用的是静态导入。它使代码更加顺眼。