Skip to content
Related Articles

Related Articles

How to Test Java List Interface Methods using Mockito?

View Discussion
Improve Article
Save Article
  • Last Updated : 02 Feb, 2022
View Discussion
Improve Article
Save Article

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"?>
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    <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. 


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!