EasyMock对void方法的期望

时间:2012-12-17 15:44:46

标签: 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);

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.

3 个答案:

答案 0 :(得分:25)

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

EasyMock.expectLastCall().once();
EasyMock.expectLastCall().atLeastOnce();
EasyMock.expectLastCall().anyTimes();

IExpectationSetters的详细API是here

在你的例子中,你只是得到了句柄而没有用它做任何事情因此你看不到有或没有任何影响。这与你调用一些getter方法或声明一些变量,不要使用它。

答案 1 :(得分:2)

当您需要进一步验证除“调用该方法之外的任何内容时,您只需要EasyMock.expectLastCall();。(与设置期望相同)”

假设您要验证方法被调用的次数,因此您将添加以下任何一个:

EasyMock.expectLastCall().once();
EasyMock.expectLastCall().atLeastOnce();
EasyMock.expectLastCall().anyTimes();

或者说你想抛出异常

EasyMock.expectLastCall().andThrow()

如果您不在乎,则EasyMock.expectLastCall();不是必需的,并且没有任何区别,您的陈述"obj.methodThatReturnsVoid(EasyMock.<String>anyObject());"足以设定期望。

答案 2 :(得分:0)

您缺少EasyMock.verify(..)

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);

// verify that your method was called
EasyMock.verify(obj);
相关问题