JUnit Mockito example And Mockito framework
In this article we will learn about Mockito.
What is Mockito?
Consider a scenario, where this some of the methods are made available by other vendor/ external vendors. So, my application just need to connect with the vendor service and get the response. That response later i can use to verify my application.
Now, what if the vendor service is not yet ready but you want to test your application, or for time being you want to test your application without connecting to real time vendor service api.
So, in order to test them, we have to mock services. This is were mocking frameworks comes into picture. As this activity can be done by some of the mocking frameworks very easily. There are many mocking frameworks like JMock, EasyMock, Mockito etc. Mockito is one of the most widely used among all of them.
How to use Mockito?
Create a new Maven project, and add JUnit and Mockito dependency.
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<version>1.10.19</version>
<scope>test</scope>
</dependency>
Create a new class “Calculator.java” and add a method “perform()” in this. This perform() method adds two numbers by calling add() method that is provided by a third party vendor and once it get response for add(), it multiplies the result with 2.
//add() method is provided by external team.
public int perform(int i, int j)
{
return service.add(i,j)*2;
}
Now, add a new Interface CalculatorService.java, and let us say this Interface is having a method declared with name add().
public interface CalculatorService {
public int add(int i, int j);
}
Create another test class “”testCalculator.java” to test “Calculator.java” class. Since, we are going to mock add() method from CalculatorService interface. So, we need to add below lines.
CalculatorService calService= Mockito.mock(CalculatorService.class);
Now, just define the mock, as below.
when(calService.add(2, 3)).thenReturn(5);
Git respository for the project used in this article is here: