Spring Boot 2 + JUnit 5 REST API Unit Testing

Share this:
  • 1
  •  
  •  
  •  
  •  
  •  
    1
    Share

This article explains how to unit test REST APIs in Spring Boot 2 using JUnit 5. As we are using Spring Boot 2, we will be using Spring Framework 5. We are going to use MockMvc which will mock the Spring MVC infrastructure without starting a web container.

If you are already aware of Spring Boot REST API Unit Testing with JUnit 4, migrating to JUnit 5 will be easy, because the use of MockMvc and @WebMvcTest remains the same.

Let’s quickly jump on coding.

Technology Stack

  • Java 10
  • Spring Boot 2.0.3.RELEASE
  • Junit 5
  • Database: HSQLDB
  • IDE: Eclipse Photon / IntelliJ IDEA 2018.1.5

JUnit 5 maven configuration

For JUnit 4 adding the dependency for spring-boot-starter-test was enough. But for Junit 5 you need to add following dependencies:

  • spring-boot-starter-test
  • junit-jupiter-api
  • junit-jupiter-engine
  • maven-surefire-plugin

The pom.xml is:

 

Test Class configuration

First of all, check the configuration of the test class of your REST Controller :

Something about the annotations:

@ExtendWith(SpringExtension.class): Register the SpringExtension which integrates the Spring TestContext Framework into Junit 5’s Jupiter programming model.

@WebMvcTest: Auto configure Spring MVC infrastructure and MockMvc. It will only scan beans related to Web layer, like @Controller, @ControllerAdvice, WebMvcConfigurer etc. This is useful because we are interested only in web layer when unit testing Controller classes. In our case, we are limiting it to EmployeeController.class.

MockMvc: Provide Spring MVC infrastructure without starting the HTTP Server.

@MockBean: It adds Mockito mocks as a bean in Spring ApplicationContext.

JUnit 5 Test method

Now check how to write JUnit test method. As explained in the earlier article, steps to write unit test cases are similar. The only difference is, we should be using JUnit 5 libraries.

  1. Annotate the test method with @Test from org.junit.jupiter.api.Test
  2. Prepare the test data and define the mock behavior
  3. Call the REST API using MockMvc
  4. Verify the MvcResult is as expected. We are asserting the result using org.junit.jupiter.api.Assertions class.

And here is the code for JUnit test case for POST operation:

Source Code

The complete source code is available on Github.

 


Share this:
  • 1
  •  
  •  
  •  
  •  
  •  
    1
    Share