Writing a Unit Test

Learn how to write a unit test with JUnit 5.

Create a new Spring Boot project using the Spring Initializr. You can provide io.datajek as "Group" and unittesting as "Artifact. There is no need to add any dependency. The spring-boot-starter-test dependency is automatically included in the Spring Boot project.

The pom.xml file of the project shows the dependency as follows:

Press + to interact
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

To understand how unit testing is done with JUnit, we will create a simple class ArrayMethods in io.datajek.unittesting package. We will write some methods in this class and then test those using JUnit.

Our class has a method to find the index of a given number in the array (findIndex) and a method to print a number at a specific index in the array.

public class ArrayMethods {
int findIndex(int[] array, int number) {
int index = -1;
for (int i = 0; i < array.length; i++) {
if (array[i] == number)
index = i;
}
return index;
}
void printNumber(int[] array, int index) {
System.out.println(array[index]);
}
}
ArrayMethods class

The findIndex() method takes an integer array and a number and returns the index at which the number is found in the array.

The printNumber() method accepts an array of integers and an index number and displays the integer stored at the index.

Testing the code

JUnit framework allows us to call the findIndex() method with an array containing three integers, say 8, 4, and 5, and look for 4 in the array. The index where 4 is found, (1) is returned. To test the findIndex() method, we will ...