|
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 by Step ImplementationStep 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 for Junit is as follows: XML
Implementation: Below is the complete code for the pom.xml file XML
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() Method4.1: Mockito provides us mock() method to mock the List Class. Java
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
4.3: Junit provides us assertEquals() which is used to check if two objects are equally defined or not. Java
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
Example: Java
Test list.size() Method With Multiple Values We can also test the list.size() method with multiple value. Example Java
Test list.get() MethodIllustration A: Java
One can also throw an exception and test your method. Illustration B: Throw an Exception Java
Implementation: Java
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. |
Reffered: https://www.geeksforgeeks.org
Java |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 9 |