2 Minutes To Code (β Version)

Easymock - 2 minute tutorial

How to define mock behaviour for any argument

The previous example shows how to stub a method for a hardcoded argument. However, Easymock api also allows us to mock for generalized arguments using methods anyInt(), anyObject() etc of class org.easymock.EasyMock.

Note that the method replay(..) must be called to mark the end of recording state and let the mock object know that the stubbed methods will now be called on it.

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 DefineMockBehaviourAdvanced
{
	public static void main(String[] args)
	{
		List myList = createMock(List.class);
		
		expect(myList.get(anyInt())).andReturn("abc");
		expect(myList.add(anyObject())).andReturn(true);
		expect(myList.remove(anyObject(Date.class))).andReturn(false);
		
		replay(myList);
		
		System.out.println(myList.get(5));
		System.out.println(myList.add("something"));
		System.out.println(myList.remove(new Date(System.currentTimeMillis())));
	}
}