Hello EasyMock
This Tutorial will show you how to write a simple EasyMock based Unit Test
Main Learning's
After following this tutorial you will learn how to:
- Download and install EasyMock
- Use EasyMock in Eclipse
- Create a EasyMock based Unit Test
- Compile and run the EasyMock based Unit Test
Versions used:
- Eclipse SDK 3.2.2
- JDKversion 1.5.0_12
- EasyMock 2.3
Assumptions:
The JDK is properly installed
You are familiar with Eclipse IDE fro Java
Tutorial Steps:
- Go to http://www.easymock.org/Downloads.html

- Download a stable version of EasyMock – e.g easymock2.3
- Extract easymock2.3.zip to a folder – e.g C:\Program Files\easymock
- Open Eclipse for Java IDE
- Create a new project (name it helloEasyMock)

- Click on Finish
- Create a ITranslator interface

- Make sure ITranslator interface has the following code
-
package org.helloopensource.greetings;
public interface ITranslator {
public abstract String translate(String fromLanguage, String toLanguage, String word);
}
- Create a Greeting class

- Make sure Greeting class has the following code
- package org.helloopensource.greetings;
public class Greeting {
private ITranslator translator;
public Greeting(ITranslator translator) {
this.translator = translator;
}
public String sayHello(String language, String name) {
return translator.translate("English", language, "Hello") + " " + name;
}
}
- Add the easymock.jar to the build path

- Click on add external JARs
- Select the easymock.jar files (e.g C:\Program Files\easymock\easymock2.3\easymock.jar)
- Create a new Unit Test (new / Unit Test)

- Click on finish
- Make sure JUnit library is added to the build path
- Add the following code for the GreetingTest code:
- package org.helloopensource.greetings;
import static org.easymock.EasyMock.createMock;
import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.replay;
import static org.easymock.EasyMock.verify;
import junit.framework.TestCase;
public class GreetingTest extends TestCase {
public void testGreetingInAnotherLanguage() throws Exception {
ITranslator mockTranslator = createMock(ITranslator.class);
Greeting greeting = new Greeting(mockTranslator);
expect(mockTranslator.translate("English", "Hindi", "Hello")).andReturn("Namaste");
replay(mockTranslator);
assertEquals("Namaste Paulo", greeting.sayHello("Hindi", "Paulo"));
verify(mockTranslator);
}
}
- Run GreetingTest Unit Test

Comments (0)
You don't have permission to comment on this page.