How to Run JUnit 5 Tests with Spring Boot

If you’re building a Spring Boot application, you’ll likely want to test your code to ensure it’s working as expected. JUnit 5 is a powerful testing framework that makes it easy to write and run tests in Java. In this tutorial, we’ll show you how to run JUnit 5 tests with Spring Boot, including how to inject a sample service class and perform sample assertions.

Prerequisites

To follow along with this tutorial, you’ll need:

  • A Java IDE, such as Eclipse or IntelliJ IDEA.
  • A Spring Boot project that you want to test.
  • Basic knowledge of Spring Boot and JUnit 5.

Firstly, initialize the application with any tool, such as Spring Boot Initializr:

spring boot test example

To run this Test you don’t need any extra dependency. As a matter of fact. Spring Boot already bundles JUnit 5 Test classes in the Spring Boot Starter Test:

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

Step 1: Create a Sample Service Class

First, let’s create a simple service class that we can test. Create a new Java class called MyService in your project:

@Service
public class MyService {
    public String getMessage() {
        return "Hello, world!";
    }
}

This class has a single method, getMessage(), that returns a simple greeting message.

Step 2: Create a Sample Test Class

Next, let’s create a test class for our MyService class. Create a new Java class called MyServiceTest in the src/test/java directory of your project:

package com.example.demo;

import static org.junit.jupiter.api.Assertions.assertEquals;

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 testGetMessage() {
        String message = myService.getMessage();
        assertEquals("Hello, world!", message);
    }
}

This test class contains the @SpringBootTest annotation, which tells Spring Boot to load the entire application context for the test. The MyService instance is injected into the test class using the @Autowired annotation, which makes it available for testing.

The testGetMessage() method performs a simple assertion to ensure that the getMessage() returns the correct message.

Finally, this is the Project tree for a Spring Boot application which runs a JUnit 5 Test:

spring boot test junit

Step 3: Run the Test

To run the test, open the MyServiceTest class in your Java IDE and click the “Run” button. You should see the output “Tests run: 1, Failures: 0, Errors: 0, Skipped: 0” in the console, indicating that the test passed.

Congratulations, you’ve successfully run a JUnit 5 test with Spring Boot! You can now use this as a starting point to write more comprehensive tests for your Spring Boot application.

Troubleshooting common issues

A common issue, if you want to run Integration Tests in Spring Boot application in the same phase when you build your application is that you won’t be able to connect the Test to the application:

$ mvn install spring-boot:run  [ERROR] Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 3.434 s <<< FAILURE! - in com.example.testrest.DemoApplicationTests [ERROR] testCustomerList(com.example.testrest.DemoApplicationTests)  Time elapsed: 1.004 s  <<< ERROR! java.net.ConnectException: Connection refused (Connection refused)

This is due to the fact, that the port chosen during the Test Phase is random, therefore most of the time you will get a Connection refused Exception.

How to fix it

In older versions of Spring Boot, you could add the annotation @IntegrationTest to your application to solve the issue, however that has been deprecated and removed in Spring Boot 2. The simplest way to get around the problem is to specify the SpringBootTest.WebEnvironment.DEFINED_PORT in your @SpringBootTest Class as follows:

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)

Conclusion

In this tutorial, we showed you how to run JUnit 5 tests with Spring Boot, including how to inject a sample service class and perform sample assertions. By following these steps, you can easily write and run tests for your Spring Boot application to ensure that it’s working as expected.

To keep learning about Spring Boot and Tests, check also this article: Testing Spring Boot with RESTAssured

Source code for this article: https://github.com/fmarchioni/masterspringboot/tree/master/test/basic