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

- Download a stable version of JMock – e.g Stable: 2.2.0 Binary JARs
- Extract jmock-2.2.0-jars.zip to a folder – e.g C:\Program Files\jmock

- JMock 2.2.0 jar files

- Open Eclipse for Java IDE
- Create a new project (name it helloJMock)

- 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 jmock JARs to the build path

- Click on add external JARs
- Select all the jar files from the jmock JAR location (e.g C:\Program Files\jmock\jmock-2.2.0)

- Click on Open
- 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 org.jmock.Expectations;
import org.jmock.Mockery;
import junit.framework.TestCase;
public class GreetingTest extends TestCase {
public void testGreetingInnyLanguage() throws Exception {
// set up
Mockery context = new Mockery();
final ITranslator mockTranslator = context.mock(ITranslator.class);
Greeting greeting = new Greeting(mockTranslator);
// expectations
context.checking(new Expectations() {{
one (mockTranslator).translate("English", "Italian", "Hello");
will(returnValue("Ciau"));
}});
// execute
assertEquals("Ciau Paulo", greeting.sayHello("Italian", "Paulo"));
// verify
context.assertIsSatisfied();
}
}
- Run GreetingTest Unit Test

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