2 Minutes To Code (β Version)

Easymock - 2 minute tutorial

How to define mock behaviour for sequential method calls

Easymock api allows us to define behaviour of mock objects for the case where same mocked methods are called multiple times. This is done by using methods andReturn(...) of class org.easymock.EasyMock multiple times.

Now, when the mocked method is called first time, the first behaviour (returning string "abc") manifests itself. On all subsequent calls, the second behaviour(returning string "pqr") manisfest itself.
package com.techfundaes.easymockBag;

import static org.easymock.EasyMock.*;

import java.util.List;

public class DefineMockBehaviourSequential
{
	public static void main(String[] args)
	{
		List myList = createMock(List.class);
		
		expect(myList.get(0)).andReturn("abc").andReturn("pqr");
		expectLastCall().anyTimes();
		
		replay(myList);
		
		System.out.println(myList.get(0));
		System.out.println(myList.get(0));
		System.out.println(myList.get(0));
		
	}
}