![]() |
VOOZH | about |
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
So in this article, we are going to test some of the methods with the help of the Mockito and Junit framework.
Step 1: Creating a Maven project
Create a maven project in your favorite Java IDE (In this article we are using IntelliJ IDEA)
👁 ImageStep 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:
Dependency for Junit is as follows:
Implementation: Below is the complete code for the pom.xml file
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.
👁 ImageStep 4: Now we are going to write the test cases for Java List Interface methods.
4.1: Mockito provides us mock() method to mock the 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.
4.3: Junit provides us assertEquals() which is used to check if two objects are equally defined or not.
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.
Example:
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
Illustration A:
One can also throw an exception and test your method.
Illustration B: Throw an Exception
Implementation:
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.
👁 Image