Over a million developers have joined DZone.

Spring Boot REST API Unit Testing With JUnit

DZone's Guide to

Spring Boot REST API Unit Testing With JUnit

In this tutorial, we go through the process of setting up tests to make sure your API performs as it should, using an open source technology.

· Performance Zone ·
Free Resource

xMatters delivers integration-driven collaboration that relays data between systems, while engaging the right people to proactively resolve issues. Read the Monitoring in a Connected Enterprise whitepaper and learn about 3 tools for resolving incidents quickly.

Unit Testing APIs is an important part of API testing because Unit Testing ensures that API components will function properly. In this article, we will learn how to cover Spring Boot REST APIs with JUnit. Spring Boot is an open-source framework for application creation, and where we create our APIs.

There are many different variations and techniques to Unit Test APIs. I prefer the following combination: Spring Boot, JUnit, MockMvc, and Mockito, because they are all open-source and support Java, which is my preferred language.

To start, we have to have IntelliJ IDEA, as an IDE for development, and JDK8, for using Java for development. These are my personal preferences but Eclipse, NetBeans, or even a simple text editor could also be used.

Now, let’s setup a project. You can also participate - the source code is located here. We will be testing controllers and repository classes. In short, we have 4 controllers (ArrivalController, DepartureController, UsersController, FlightsController) and 4 repositories (ArrivalRepository, DepartureRepository, UsersRepository, FlightsRepository). We will write tests per controller (testing the size of the JSON Object, the status of the call to the endpoint and an assertion on one item from the JSON object) and tests per repository (inserting two new items in a table and making sure the return object is equal).

Step 1 - Create an API Testing Project

1. Install IntelliJ IDEA.

2. Make sure you have JDK installed (at least version 1.8.XXX).

Now we will create a new project.

3. Open IntelliJ and click “Create New Project.”

api testing with junit

4. Select Gradle, Java, and the JDK version.

rest api testing unit testing

5. Name your project.

unit testing apis

6. Choose the project destination.

junit, api testing, spring boot, unit testing

If you did everything correctly, you should now see this window with an empty Java project:

rest api spring boot unit testing

Step 2 - Add Dependencies

Now that we have a project, we need to setup the dependencies. You can use these dependencies since they are public.

To do that, double click on your build.gradle file and add the following gradle configuration file:

group 'blazemeter'
version '1.0-SNAPSHOT'

buildscript {
   repositories {
       maven { url "http://repo.spring.io/libs-snapshot" }
   dependencies {

apply plugin: 'java'
apply plugin: 'idea'
apply plugin: 'io.spring.dependency-management'
apply plugin: 'org.springframework.boot'

sourceSets {
   main.java.srcDir "src/main/java"
   main.resources.srcDir "src/main/resources"
   test.java.srcDir "src/test/java"
   test.resources.srcDir "src/test/resources"

jar {
   baseName = 'blaze-demo-api'
   version =  '1.0'

bootRepackage {
   mainClass = 'com.demo.BlazeMeterApi'

dependencyManagement {
   imports {
       mavenBom 'io.spring.platform:platform-bom:Brussels-SR2'

repositories {
   maven { url "http://repo.spring.io/libs-snapshot" }

sourceCompatibility = 1.8
targetCompatibility = 1.8

dependencies {

   compile group: 'org.springframework', name: 'spring-core'
   compile group: 'org.springframework.boot', name: 'spring-boot-starter-jdbc'
   compile group: 'org.springframework.boot', name: 'spring-boot-starter-web'
   compile group: 'org.springframework.boot', name: 'spring-boot-starter-actuator'
   compile group: 'org.springframework.boot', name: 'spring-boot-starter-security'
   compile group: 'org.springframework.boot', name: 'spring-boot-starter-data-jpa'
   compile group: 'org.springframework.security.oauth', name: 'spring-security-oauth2'
   compile group: 'com.fasterxml.jackson.datatype', name: 'jackson-datatype-hibernate4'
   compile group: 'mysql', name: 'mysql-connector-java'
   compile group: 'io.rest-assured', name: 'rest-assured', version: '3.0.3'
   compile group: 'io.rest-assured', name: 'json-schema-validator', version: '3.0.3'

   testCompile group: 'org.springframework.boot', name: 'spring-boot-starter-test'
   testCompile group: 'org.springframework.security', name: 'spring-security-test'
   testCompile group: 'junit', name: 'junit'
   testCompile group: 'org.hsqldb', name: 'hsqldb'

Step 3 - Write Your Unit Test via JUnit

In IntelliJ IDEA, go to the class that you want to test. Hit Cmd + Shift + T and a popup will appear. In the popup, select  “Create New Test...”. Then, IntelliJ IDEA will create a file for writing the test in. The file will be created in the default place. In our case, if we are going to cover the class ArrivalController, it will create a test class with the path test/java/com/demo/controller. You can see this in the following screenshot:

how do i run unit tests on my apis?

I personally prefer to group tests (as you can see in the same picture - there are 3 folders: bdd, rest, unit) according to the test types: REST, UNIT, BDD, etc. For that reason, I create the test classes by myself. For this example, ArrivalControllerTest is located at the test/java/com/demo/unit/controller path.

Here is the test class itself:

package com.demo.unit.controller;

import com.demo.controller.ArrivalController;
import com.demo.domain.Arrival;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import java.util.List;
import static com.demo.constant.Paths.ARRIVAL;
import static com.demo.constant.Paths.VERSION;
import static java.util.Collections.singletonList;
import static org.hamcrest.collection.IsCollectionWithSize.hasSize;
import static org.hamcrest.core.Is.is;
import static org.mockito.BDDMockito.given;
import static org.springframework.http.MediaType.APPLICATION_JSON;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.user;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

public class ArrivalControllerTest {

   private MockMvc mvc;

   private ArrivalController arrivalController;

   public void getArrivals() throws Exception {
       Arrival arrival = new Arrival();

       List<Arrival> allArrivals = singletonList(arrival);


       mvc.perform(get(VERSION + ARRIVAL + "all")
               .andExpect(jsonPath("$", hasSize(1)))
               .andExpect(jsonPath("$[0].city", is(arrival.getCity())));

   public void getArrivalsById() throws Exception {
       Arrival arrival = new Arrival();


       mvc.perform(get(VERSION + ARRIVAL + arrival.getId())
               .andExpect(jsonPath("city", is(arrival.getCity())));

In this test class, we have two test methods, getArrivals() and getArrivalsById(). The reason we have two is that we have two methods in the controller itself, so we want to test them both. 

The getArrivals() method does the following (code snippet above):

  • Creates an Arrival entity and sets the test value for the city.
  • Creates a list of Arrivals (because we will have just one member, it can be a singeltonList).
  • Using given from mockito, makes sure the mocked ArrivalController will return a list of Arrivals.
  • Performs a GET request to the mocked controller with the credentials and performs simple assertions:
    • Status - 200 (which isOk).
    • The JSON object has one member.
    • The JSON body has a city key with the value we set.

The second test method does the same for the getArrivalsById(). The difference is that it assumes one JSON object result instead of a list of Arrivals of JSON objects.

That’s all. Now we can execute this single test by clicking the play button at the beginning of the line of the method name (see the following picture). The purpose of this execution is to make sure the test is working properly:

how can i use junit for apis

After execution, you will see the results of test execution, including the status, count, and stacktrace. We can see that our test passed (on the left side), the number of tests (the progress bar is in the middle up top) and the stacktrace for execution.

how can i test my spring boot rest apis with junit

That’s it for that one controller. The next step will be to add tests for all controllers.

Step 4 - Setting Up the Unit Tests for the APIs

Now, let’s test one API repository class with this unit test. This is a unit test that is covering the database testing part. For example, writing test data to the DB and afterward verifying it is properly stored.

Like in the previous part, go to the ArrivalRepository class, hit Cmd + Shift + T and create a new test class via IntelliJ IDEA or by yourself.

 This is the code for that test class:

package com.demo.unit.repository;

import com.demo.domain.Arrival;
import com.demo.repository.ArrivalRepository;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase.Replace.NONE;

@AutoConfigureTestDatabase(replace = NONE)
public class ArrivalRepositoryTest {

   private TestEntityManager entityManager;

   private ArrivalRepository arrivalRepository;

   public void whenFindAll() {
       Arrival firstArrival = new Arrival();

       Arrival secondArrival = new Arrival();

       List<Arrival> arrivals = arrivalRepository.findAll();


   public void whenFindAllById() {
       Arrival arrival = new Arrival();

       Arrival testArrival = arrivalRepository.findAllById(arrival.getId());


In this test, we are using the H2 database for testing. This is common practice. Otherwise, you need to have the same type of database set up in all test/dev environments, maintain them and make sure you clean them up after test execution. This is not necessary when you use the H2 DB because it is in the memory. After the test(s) is finished, the database will be fully dropped. 

The test covers the following:

  • Use entityManager to create two new rows of data in the Arrival table of test H2 database.
  • Search for all records from database via a findAll query.
  • Perform assertions on the size of the data and equality of gathered objects.

The second method does the same, but because it is for findAllById, it is checking just one object equality. 

That’s all! Now you can do this for all other repository classes with their methods. 

Step 5 - Running the Unit Tests on Your APIs 

After all the controller and repository class tests are set up, we need to execute them. Do that by highlighting the folder unit -> right click -> select “Run ‘Tests’ in ‘com.demo.unit’ with Coverage” (see next picture), so we will also have the code coverage report.

rest api unit testing with junit, java, spring boot

These are the coverage results, showing how many classes and methods are covered by unit tests:

repository and classes junit testing for your apis

That’s it! You now know how to run Unit Tests with JUnit for REST APIs. 

3 Steps to Monitoring in a Connected Enterprise. Check out xMatters.

performance ,junit ,api testing ,api performance

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}