How to Test Java List Interface Methods using Mockito?
Last Updated :
02 Feb, 2022
Mockito is an open-source testing framework used for unit testing of Java applications. It plays a vital role in developing testable applications. Mockito is used to mock interfaces so that a dummy functionality can be added to a mock interface that can be used in Unit Testing. The List interface in Java provides a way to store the ordered collection. It is a child interface of Collection. It is an ordered collection of objects in which duplicate values can be stored. There are many methods available in Java List Interface likeÂ
- add()
- set()
- remove()
- size()
- get() and many more.
So in this article, we are going to test some of the methods with the help of the Mockito and Junit framework.Â
Step by Step Implementation
Step 1: Creating a Maven projectÂ
Create a maven project in your favorite Java IDE (In this article we are using IntelliJ IDEA)
Step 2: When you have successfully created a maven project you have to add some dependencies in your pom.xml file. You have to add the following dependency in your pom.xml file.
Dependency for Mockito is as follows:
XML
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<version>2.0.2-beta</version>
</dependency>
Dependency for Junit is as follows:Â
XML
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.8.2</version>
</dependency>
Implementation: Below is the complete code for the pom.xml file
XML
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>mockito-demo</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.8.2</version>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<version>2.0.2-beta</version>
</dependency>
</dependencies>
<properties>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
</properties>
</project>
Step 3: Testing the Java List Interface Methods
In order to test the Java List Interface Methods we have to create a test class inside the src > test > java > right-click > New > Java Class folder as shown in the below image. Here we have named the class as JavaListMock.
Step 4: Â Now we are going to write the test cases for Java List Interface methods.
Test list.size() Method
4.1: Mockito provides us mock() method to mock the List Class.
Java
List mockList = mock(List.class);
4.2: Mockito provides us two other methods when() and thenReturn(). when() is used when we want to mock to return specific values when particular methods are called and thenReturn() methods lets you define the return value when a particular method of the mocked object is been called.Â
Java
when(mockList.size()).thenReturn(2);
4.3: Junit provides us assertEquals() which is used to check if two objects are equally defined or not.
Java
assertEquals(2, mockList.size());
4.4: One has to write the upper 3 lines inside a public void method and you have to annotate the method with @Test. @Test annotation tells the JUnit that the public void method in which it is used can run as a test case.
Java
@Test
public void mockListSizeMethod(){
// Your test code
}
Example:Â
Java
// Java Program to Test code for the list.size() Method
// @Test tells the JUnit that the public void method
// in which it is used can run as a test case
@Test public void mockListSizeMethod()
{
// Mock the List Class
List mockList = mock(List.class);
// when is used when we want to mock to return specific
// values when particular methods are called and
// thenReturn() methods lets you define the return value
// when a particular method of the mocked object is been
// called
when(mockList.size()).thenReturn(2);
// assertEquals is used to check if
// two objects is equally defined or not
assertEquals(2, mockList.size());
}
By now, we have successfully tested the list.size() method, so moving onto nextÂ
Test list.size() Method With Multiple Values
We can also test the list.size() method with multiple value.
Example
Java
@Test
public void mockListSizeMethod_multipleValues(){
List mockList = mock(List.class);
when(mockList.size()).thenReturn(2).thenReturn(3);
assertEquals(2, mockList.size());
assertEquals(3, mockList.size());
}
Test list.get() Method
Illustration A:
Java
@Test
public void mockListGetMethod(){
List mockList = mock(List.class);
// Argument Matcher
when(mockList.get(anyInt())).thenReturn(2);
assertEquals(2, mockList.get(anyInt()));
}
One can also throw an exception and test your method.
Illustration B:Â Throw an Exception
Java
@Test(expected = RuntimeException.class)
public void mockListGetMethod_throwAnException(){
List mockList = mock(List.class);
when(mockList.get(anyInt())).thenThrow(new RuntimeException("Something Wrong"));
mockList.get(anyInt());
}
Implementation:Â
Java
// Java Program to Illustrate JavaListMock File
// Importing required classes
import static org.junit.Assert.assertEquals;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.List;
import org.junit.Test;
// Class
public class JavaListMock {
// @Test annotation tells the JUnit that
// the public void method
// in which it is used can run as a test case
@Test public void mockListSizeMethod()
{
// Mock the List Class
List mockList = mock(List.class);
// when is used when we want to mock to return
// specific values when particular methods are
// called and thenReturn() methods lets you define
// the return value when a particular method of the
// mocked object is been called
when(mockList.size()).thenReturn(2);
// assertEquals is used to check if
// two objects is equally defined or not
assertEquals(2, mockList.size());
}
// Method
@Test public void mockListSizeMethod_multipleValues()
{
List mockList = mock(List.class);
when(mockList.size()).thenReturn(2).thenReturn(3);
assertEquals(2, mockList.size());
assertEquals(3, mockList.size());
}
// Method
@Test public void mockListGetMethod()
{
List mockList = mock(List.class);
// Argument Matcher
when(mockList.get(anyInt())).thenReturn(2);
assertEquals(2, mockList.get(anyInt()));
}
// Method
@Test(expected = RuntimeException.class)
public void mockListGetMethod_throwAnException()
{
List mockList = mock(List.class);
when(mockList.get(anyInt()))
.thenThrow(
new RuntimeException("Something Wrong"));
mockList.get(anyInt());
}
}
Step 5: Run test cases
Now we are going to run our test cases. To run your test cases you may click on the testing al methods button o test all the methods in one click. And if you want to test each method separately then you may click on the testing a single method button. In the Run tab, you can see all of your test cases have been passed.Â
Similar Reads
How to Write Test Cases in Java Application using Mockito and Junit?
Mockito is an open-source testing framework used for unit testing of Java applications. It plays a vital role in developing testable applications. Mockito is used to mock interfaces so that a dummy functionality can be added to a mock interface that can be used in Unit Testing. Unit Testing is a typ
4 min read
JUnit Testing For MySQL Project in Java
For testing a software project, automated testing is always good and that will produce error-prone results. In the case of manual testing, there are possibilities of human errors. In this article let us take a sample project and let us see how to write JUnit test cases for it. Example Project Projec
6 min read
Match Lambdas to Interfaces in Java
One of the most popular and important topics is lambda expression in java but before going straight into our discussion, let us have insight into some important things. Starting off with the interfaces in java as interfaces are the reference types that are similar to classes but containing only abst
5 min read
How to Test Java Application using TestNG?
TestNG is an automation testing framework widely getting used across many projects. NG means âNext Generationâ and it is influenced by JUnit and it follows the annotations (@). Â End-to-end testing is easily handled by TestNG. As a sample, let us see the testing as well as the necessity to do it via
4 min read
Generate Junit Test Cases Using Randoop API in Java
Here we will be discussing how to generate Junit test cases using Randoop along with sample illustration and snapshots of the current instances. So basically in Development If we talk about test cases, then every developer has to write test cases manually. Which is counted in the development effort
4 min read
Mutation Testing in Java (Using Jumble)
Mutation testing is a white-box testing technique that changes certain portions of the code to reveal possible faults. On a very high level, it is the process of rewriting the source code with some known or possible bugs or differences to the actual code in small ways in order to remove the redundan
3 min read
How to Test a Maven Project using EasyMock?
Always a software project is prepared and tested as an individual unit. We pass different scenarios and expect the original values should match. One such approach is "Easymock" and in this article via a sample project, handled when and how to mock void methods. We are going to see this approach via
3 min read
Unit Testing, Integration Testing, Priority Testing using TestNG in Java
TestNG is an automated testing framework. In this tutorial, let us explore more about how it can be used in a software lifecycle. Unit Testing Instead of testing the whole program, testing the code at the class level, method level, etc., is called Unit Testing The code has to be split into separate
6 min read
Modifier isInterface(mod) method in Java with Examples
The isInterface(mod) method of java.lang.reflect.Modifier is used to check if the integer argument includes the interface modifier or not. If this integer parameter represents interface type Modifier then method returns true else false. Syntax: public static boolean isInterface(int mod) Parameters:
2 min read
JUnit - Test HTTPClient using Maven Project
HTTP Client can provide synchronous and asynchronous request mechanisms via the following three core classes: HttpRequest: Request that needs to be sent via the HttpClient.HttpClient: It is a container for multiple requests.HttpResponse: All requests need to complete the cycle and provide the result
6 min read