EasyMock
// create
IUnderTest mock = createMock(IUnderTest.class);
//alternatively, to also check method-call-order:
//IUnderTest mock = createStrictMock(IUnderTest.class);
// train
mock.addValue("key", "value");
expect(mock.getValue("key")).andReturn("value"); // expect a call and define what’s returned then
expectLastCall().times(3); // last method call is expected to be called 3 times
expect(mock.deleteValue("nonExistant")).andThrow(new Exception());
//alternatively to last line:
//mock.deleteValue("nonExistant");
//expectLastCall().andThrow(new Exception());
// set mock into “productive” mode
replay(mock);
/* TESTCODE HERE */
// verify trained calls were called like trained
verify(mock);
Assigning return-values at runtime (example from doc)
List<String> l = createMock(List.class);
// andAnswer style
expect(l.remove(10)).andAnswer(new IAnswer<String>() {
public String answer() throws Throwable {
return getCurrentArguments()[0].toString();
}
});
// andDelegateTo style
expect(l.remove(10)).andDelegateTo(new ArrayList<String() {
@Override
public String remove(int index) {
return Integer.toString(index);
}
});
Changing return-values between calls
expect(mock.get("key2"))
.andReturn("value x1").times(3)
.andThrow(new Exception(), 4)
.andReturn("value x2");
times()
-Alternatives
times(int min, int max)
, atLeastOnce()
, anyTimes()