我正在使用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);关于expectLastCall(),EasyMock的API文档是这样描述的:
Returns the expectation setter for the last expected invocation in the current thread. This method is used for expected invocations on void methods.发布于 2012-12-17 23:51:42
此方法通过IExpectationSetters返回期望的句柄;这使您能够验证(断言)是否调用了您的空方法以及相关行为,例如
EasyMock.expectLastCall().once();
EasyMock.expectLastCall().atLeastOnce();
EasyMock.expectLastCall().anyTimes();IExpectationSetters的详细接口为。
在你的例子中,你只是获得了句柄,并没有对它做任何事情,因此你看不到拥有或删除语句的任何影响。,这与你调用某个getter方法或声明某个变量而不使用它是一样的。
发布于 2014-04-29 14:13:04
只有当您需要进一步验证“该方法是否已被调用。(与设置期望相同)”之外的任何内容时,才需要EasyMock.expectLastCall();。
假设您想要验证该方法被调用了多少次,那么您将添加以下任一项:
EasyMock.expectLastCall().once();
EasyMock.expectLastCall().atLeastOnce();
EasyMock.expectLastCall().anyTimes();或者说你想抛出一个异常
EasyMock.expectLastCall().andThrow()如果你不在乎,那么EasyMock.expectLastCall();就不是必需的,也不会有任何不同,你的语句"obj.methodThatReturnsVoid(EasyMock.<String>anyObject());"就足以设置期望。
发布于 2016-08-17 04:45:41
您缺少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);https://stackoverflow.com/questions/13917312
复制相似问题