Running Tests With Mockito

A simple guide on how to run tests using Mockito

In the previous blog, we discussed about Mockito, what it is, what it does and what the advantages of it are.

Today, we will look into a simple example of how to run test with the use of Mockito.

For this example, we will use the IntelliJ Idea IDE.

Testing With Mockito

1. Start by creating a simple Maven project.
With the help of Maven, we will be able to easily make use of the Mockito and JUnit dependencies that are required in order to run the tests.

2. In the pom.xml file, add the dependencies as follows;

<?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>MockitoTesting</artifactId>
<version>1.0-SNAPSHOT</version>

<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>

<dependencies>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>3.0.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>RELEASE</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
</dependency>
</dependencies>
</project>


3. Create a new class called "Numbers".



4. Create a test for the Numbers class.
For this, click on the class name -> Alt + Enter -> Create Test

5. The test case can be written as follows;


As shown above, an object of the Numbers class has been mocked with the help of Mockito and it allows the user to run the tests without having to create an object.

This can be repeated for any number of test cases that are required.

This will give the following output;


Happy Mocking!

Comments

Popular Posts