Mock objects with EasyMock

1. Introduction

The mock objects allows to make unit tests on objects depending on other objects. We will replace this dependencies with mock objects. With that, we can by example verify than the method xyzzy() has been called 5 times and returned 33. That can be practical in a several cases. By exampe, if the object to mock is slow or undeterministic (depending on time, or why not on the weather). This objects are really difficult to test because we can make a lot of tests but we could never find the special cases. Test cases with mock objects enable us to test this cases.

There is several tools to make mock objects. In this article, we will use EasyMock 2.5.2 with JUnit 4.7.

Here is the interface to test :

public interface ISimpleDao {
	void save(String title);
	void remove(String title) throws NotExistingException;
	int count();
	void debug();
	boolean isValid(String title);
	void insert(String title);
}

And here is our class to test :

public class SimpleService {
	private ISimpleDao dao;
 
	public void setDao(ISimpleDao dao){
		this.dao = dao;
	}
 
	public void insert(String title){
		if(dao.isValid(title)){
			dao.insert(title);
		}
	}
 
	public void save(String... titles){
		for(String title : titles){
			dao.save(title);
		}
	}
 
	public boolean remove(String title){
		try {
			dao.remove(title);
		} catch (NotExistingException e){
			return false;
		}
 
		return true;
	}
 
	public int size(){
		return dao.count();
	}
 
	public void debug(){
		System.out.println("Debug informations of SimpleService");
		dao.debug();
	}
}

Our mock will implement the ISimpleDao interface and we will give it to SimpleService who’s the class to test. This example is really simplistic, but it will be enough to cover the main features of EasyMock.

Related posts:

  1. Develop a modular application – Implementation
  2. Java 7 : The new java.util.Objects class
  3. JR Operations and Capabilities
  4. Tip : Add resources dynamically to a ClassLoader
  5. Swing tip : A better SwingWorker without exception swallowing
Pages: 1 2 3 4 5
  • http://www.monitorlcd17.org Monitor LCD 17

    a very good article with examples.

  • Shan6051

    I am facing a problem while testing a method.
    this method calls A class which calls B class and B calls D interface. I am mocking the Interface but since this is not directly going in the Method (to be tested) ….is it possible to do this type of testing because in all examples i saw only one class and one Interface only …
    Please HELP me !!

  • http://www.aryol.com.tr prefabrik

    another great post. I’m big fan of this site. Thanks for the codes.

  • Pingback: JUnit: Automatically Managing Mocks « Ted Young