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
Java Tutorial Java is a high-level, object-oriented programming language used to build web apps, mobile applications, and enterprise software systems. It is known for its Write Once, Run Anywhere capability, which means code written in Java can run on any device that supports the Java Virtual Machine (JVM).Java s
10 min read
Java OOP(Object Oriented Programming) Concepts Java Object-Oriented Programming (OOPs) is a fundamental concept in Java that every developer must understand. It allows developers to structure code using classes and objects, making it more modular, reusable, and scalable.The core idea of OOPs is to bind data and the functions that operate on it,
13 min read
Java Interview Questions and Answers Java is one of the most popular programming languages in the world, known for its versatility, portability, and wide range of applications. Java is the most used language in top companies such as Uber, Airbnb, Google, Netflix, Instagram, Spotify, Amazon, and many more because of its features and per
15+ min read
Arrays in Java In Java, an array is an important linear data structure that allows us to store multiple values of the same type. Arrays in Java are treated like objects. For primitive types like int or char, the actual values are stored in contiguous memory locations. But if the array holds objects, then it does n
15+ min read
Collections in Java Any group of individual objects that are represented as a single unit is known as a Java Collection of Objects. In Java, a separate framework named the "Collection Framework" has been defined in JDK 1.2 which holds all the Java Collection Classes and Interface in it. In Java, the Collection interfac
15+ min read
Inheritance in Java Java Inheritance is a fundamental concept in OOP(Object-Oriented Programming). It is the mechanism in Java by which one class is allowed to inherit the features(fields and methods) of another class. In Java, Inheritance means creating new classes based on existing ones. A class that inherits from an
13 min read
Java Exception Handling Exception handling in Java allows developers to manage runtime errors effectively by using mechanisms like try-catch block, finally block, throwing Exceptions, Custom Exception handling, etc. An Exception is an unwanted or unexpected event that occurs during the execution of a program, i.e., at runt
10 min read
Java Programs - Java Programming Examples In this article, we will learn and prepare for Interviews using Java Programming Examples. From basic Java programs like the Fibonacci series, Prime numbers, Factorial numbers, and Palindrome numbers to advanced Java programs.Java is one of the most popular programming languages today because of its
8 min read
Introduction to Java Java is a high-level, object-oriented programming language developed by Sun Microsystems in 1995. It is platform-independent, which means we can write code once and run it anywhere using the Java Virtual Machine (JVM). Java is mostly used for building desktop applications, web applications, Android
4 min read
Java Interface An Interface in Java programming language is defined as an abstract type used to specify the behaviour of a class. An interface in Java is a blueprint of a behaviour. A Java interface contains static constants and abstract methods. Key Properties of Interface:The interface in Java is a mechanism to
12 min read