2 Minutes To Code (β Version)

Easymock - 2 minute tutorial

How to verify mocked object after advanced use

Easymock api allows for quite sophisticated verification of mock objects.

You can verify whether stubbed methods were called at all, whether they were called al least n times ot at most n times etc using methods expectLastCall(), anyTimes(), atLeastOnce(), once(), times(int) etc of class org.easymock.EasyMock.

The example below shows how to do this.
package com.techfundaes.easymockBag;

import static org.easymock.EasyMock.*;

import java.sql.Date;
import java.util.List;

public class VerifyAdvanced
{
	public static void main(String[] args)
	{
		List myList = createMock(List.class);
		
		expect(myList.get(geq(0))).andReturn("abc");
		expectLastCall().anyTimes();
		
		expect(myList.add(anyObject())).andReturn(true);
		expectLastCall().atLeastOnce();
		
		expect(myList.remove(anyObject(Date.class))).andReturn(false);
		expectLastCall().once();
	
		myList.add(leq(100), anyObject());
		expectLastCall().times(2);
		
		expect(myList.remove(anyInt())).andReturn("something");
		expectLastCall().times(2, 10);
		
		replay(myList);
		
		myList.get(5);
		myList.get(10);
		
		myList.add("aThing");
		myList.add("anotherThing");
		
		myList.remove(new Date(System.currentTimeMillis()));
		
		myList.add(2, "aThing");
		myList.add(4, "anotherThing");
		
		myList.remove(2);
		myList.remove(4);
		myList.remove(6);
		
		verify(myList);
	}
}