Sotirios Delimanolis Sotirios Delimanolis - 3 months ago 28
Java Question

EasyMock expectations with void methods

I'm using EasyMock to do some unit tests and I don't understand the usage of

EasyMock.expectLastCall()
. As you can see in my code below, I have an object with a method that returns void getting called in some other object's method. I would think that I have to make EasyMock expect that method call, but I tried commenting out the
expectLastCall()
invocation and it still works. Is it because I passed
EasyMock.anyObject())
that it registered it as an expected call or is there something else going on?

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


The API doc for EasyMock says this about
expectLastCall()
:

Returns the expectation setter for the last expected invocation in the current thread. This method is used for expected invocations on void methods.

Answer

This method returns you the handle of expectation through IExpectationSetters; which gives you ability to validate(assert) that your void method was called or not and related behaviors e.g.

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

Detailed API of the IExpectationSetters is here.

In your example you are just getting the handle and not doing anything with it hence you don't see any impact of having or removing the statement. It's very same as you call some getter method or declare some variable and don't use it.

Comments