Spring Boot 3 with JUnit 5

JUnit framework is an excellent choice for writing and executing unit tests and integration tests for any Java application. With Spring Boot 3, it comes inbuilt as part of spring-boot-starter-test module.

In this Spring boot tutorial, we will learn to configure JUnit 5 and to write unit tests.

1. Maven

By default, the latest spring-boot-starter-test dependency imports the JUnit 5 dependencies into the Spring boot application.

The JUnit versions have changed with the following Spring Boot releases:

  • Prior to Spring Boot v2.2.0, by default, JUnit 4 was imported.
  • From Spring Boot v2.2.0 to Spring Boot 2.4.0, JUnit 5 was included by default, and the JUnit-vintage module was included for backward compatibility. [Release Notes v2.2]
  • Since Spring Boot 2.4.x, the JUnit 5 is included without the vintage engine. [Release Notes v2.4]

You are highly encouraged to migrate JUnit 4 tests to JUnit 5. But if you still need time, then you can import the vintage dependency exclusively.

We are using the latest Spring boot version (at the time of updating this article) i.e. v3.1.2. It includes JUnit 5 framework, by default.

<parent>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-parent</artifactId>
  <version>3.1.2</version>
</parent>

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

2. Writing JUnit 5 Tests

Now we can start writing the test classes and methods using the JUnit 5 annotations. For example, we can use @SpringBootTest to load the Spring Boot application context for integration testing.

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
public class MyServiceTest {

    @Autowired
    private MyService myService;

    @Test
    public void testSomeMethod() {
        // Your JUnit 5 test logic here
        // You can use assertions and other JUnit 5 features
    }
}

The tests are written in the /src/test/java/ directory in a suitable package hierarchy. Spring boot maven plugin does an excellent job of simplifying the process of running tests and provides various testing-related features. For example, it captures and displays the test output, including test results and any exceptions thrown during testing.

3. Running The Tests

We can run the JUnit 5 tests as we would with any IDE or build tool such as Maven.

mvn test

4. Demo

Let us see an example of JUnit 5 tests written in a Spring Boot 3 application. Here is the Spring boot REST controller for which we will be writing unit tests.

@RestController
@RequestMapping(path = "/employees")
public class EmployeeController {

    @Autowired
    private EmployeeDAO employeeDao;

    @GetMapping(path="/", produces = "application/json")
    public Employees getEmployees() {
        return employeeDao.getAllEmployees();
    }

    @PostMapping(path= "/", consumes = "application/json", produces = "application/json")
    public ResponseEntity<Object> addEmployee(@RequestBody Employee employee) {
        employeeDao.addEmployee(employee);
        URI location = ServletUriComponentsBuilder.fromCurrentRequest()
                                    .path("/{id}")
                                    .buildAndExpand(employee.getId())
                                    .toUri();
        return ResponseEntity.created(location).build();
    }
}

We will use the @WebMvcTest annotation, which is used for a Spring MVC test that focuses only on Spring MVC components. It disables full auto-configuration and instead applies only configuration relevant to MVC tests. It also configures the Spring Security and MockMvc.

@WebMvcTest(EmployeeController.class)
public class TestEmployeeRESTController {
 
  @Autowired
  private MockMvc mvc;
 
}

Finally, use MockMvc bean instance to invoke the APIs and verify the results.

@Test
public void getAllEmployeesAPI() throws Exception {

  mvc.perform(MockMvcRequestBuilders
  			.get("/employees")
  			.accept(MediaType.APPLICATION_JSON))
      .andDo(print())
      .andExpect(status().isOk())
      .andExpect(MockMvcResultMatchers.jsonPath("$.employees").exists())
      .andExpect(MockMvcResultMatchers.jsonPath("$.employees[*].employeeId").isNotEmpty());
}

Similarly, we can write the other tests.

5. Conclusion

This tutorial discusses how to include JUnit 4 or JUnit 5 dependencies in a Spring Boot application. It discusses how and where to create these tests. And finally, we saw a demo of JUnit 5 tests in action.

Happy Learning !!

Source Code on Github

Comments

Subscribe
Notify of
guest
2 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode