EasyMock对void方法的期望

问题描述 投票:20回答:3

我正在使用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.
java unit-testing easymock
3个回答
25
投票

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

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

IExpectationSetters的详细API是here

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


2
投票

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

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

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

或者说你想抛出异常

EasyMock.expectLastCall().andThrow()

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


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);
© www.soinside.com 2019 - 2024. All rights reserved.