Hello Mockito
This Tutorial will show you how to write a simple Mockito based Unit Test
Main Learning's
After following this tutorial you will learn how to:
- Download and install Mockito
- Use Mockito in Eclipse
- Create a Mockito based Unit Test
- Compile and run the ~Mockito based Unit Test
Versions used:
- Eclipse SDK 3.3.1
- JDKversion 1.5.0_12
- Mockito
Assumptions:
The JDK is properly installed
You are familiar with Eclipse IDE from Java
Tutorial Steps:
- Go to http://code.google.com/p/mockito/
- Download a stable version of Mockito – e.g mockito1.2
- Extract mockito-1.1.2.zip to a folder – e.g C:Program Files/mockito-1.2.0
- Open Eclipse for Java IDE
- Create a new project (name it helloMockito)
- 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 mockito-all-1.2.jar to the build path
- Click on add external JARs
- Select the mockito-all-1.2.jar files (e.g C:Program Files/mockito-1.2.0/mockito-all-1.2.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.junit.Assert.*;
import static org.mockito.Mockito.stub;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.mock;
import org.junit.Test;
public class GreetingTest {
@Test
public void shouldTestGreetingInItalian(){
//setup
ITranslator mockTranslator = mock(ITranslator.class);
Greeting greeting = new Greeting(mockTranslator);
stub(mockTranslator.translate("English", "Italian", "Hello")).toReturn("Ciau");
//execute
assertEquals("Ciau Paulo", greeting.sayHello("Italian", "Paulo"));
//verify
verify(mockTranslator).translate("English", "Italian", "Hello");
}
}
- Run GreetingTest Unit Test
Comments (0)
You don't have permission to comment on this page.