EasyMock对void方法的期望

Sot*_*lis 20 java unit-testing easymock

我正在使用EasyMock进行一些单元测试,我不明白它的用法EasyMock.expectLastCall().正如您在下面的代码中看到的,我有一个带有方法的对象,该方法返回在其他对象的方法中调用的void.我认为我必须让EasyMock期望该方法调用,但我尝试注释掉expectLastCall()调用它仍然有效.是因为我通过EasyMock.anyObject())它将它注册为预期的电话或是否还有其他事情发生?

MyObject obj = EasyMock.createMock(MyObject.class);
MySomething something = EasyMock.createMock(MySomething.class);
EasyMock.expect(obj.methodThatReturnsSomething()).andReturn(something);

obj.methodThatReturnsVoid(EasyMock.<String>anyObject());

// whether I comment this out or not, it works
EasyMock.expectLastCall();

EasyMock.replay(obj);

// This method calls the obj.methodThatReturnsVoid()
someOtherObject.method(obj);
Run Code Online (Sandbox Code Playgroud)

EasyMock的API文档说expectLastCall():

Returns the expectation setter for the last expected invocation in the current thread. This method is used for expected invocations on void methods.
Run Code Online (Sandbox Code Playgroud)

Yog*_*ngh 25

此方法通过返回期望句柄IExpectationSetters; 这使您能够验证(断言)您的void方法是否被调用以及相关行为,例如

EasyMock.expectLastCall().once();
EasyMock.expectLastCall().atLeastOnce();
EasyMock.expectLastCall().anyTimes();
Run Code Online (Sandbox Code Playgroud)

IExpectationSetters的详细API在这里.

在您的示例中,您只是获取句柄而不对其执行任何操作,因此您不会看到使用或删除语句的任何影响.它与调用某些getter方法或声明某个变量并且不使用它非常相同.

  • 呃... EasyMock是个不错的开始,但是Mockito或JMockit跳过这些篮球. (5认同)