I recently blogged about getting started with EasyMock - a simple framework for taking the pain out of creating and using mock objects when unit testing your java code.
In the example I showed that we were expecting the next() method to be called and we wanted the mock ResultSet to return false:
So here is the same example with the additional expected
In the example I showed that we were expecting the next() method to be called and we wanted the mock ResultSet to return false:
expect(mockResultSet.next()).andReturn(false);What I didn't explain was that you use the
expect()
method when you are expecting the mock to return a value. If the method doesn't return a value (such as ResultSet.close()
) then there is no need to wrap it in an expect()
method call:mockResultSet.close();Remember: any methods that you call on your mock prior to the
replay()
method call are setting up it's expectations not actually calling the methods. After the replay()
method is called the mock is in 'live' mode, recording activity and returning any predefined values when it's methods are called.So here is the same example with the additional expected
close()
method call:public class ResultReporterTest {Technorati Tags: Java, Unit Testing, Mock Objects, EasyMock, Andrew Beacock
@Test
public void parseReturnsFalseIfPassedAnEmptyResultSet() throws SQLException {
ResultSet mockResultSet = createMock(ResultSet.class); // 1
expect(mockResultSet.next()).andReturn(false); // 2
mockResultSet.close();
replay(mockResultSet); // 3
ResultReporter reporter = new ResultReporter();
assertFalse(reporter.parse(mockResultSet));
verify(mockResultSet); // 4
}
}
Comments
my test needed to expect a non-void return call from one method
and a void return call from a second method
of the same createMock Object
thus requiring a replay on the createMock Object
so using expectLastCall would not work in this circumstance
however and expect on the non-void method call followed
by just the void method call
before the reply
worked as required