Spring Boot - rollback transaction after each @Test method (JUnit 5)

14 points
Created by:

In this short article, we would like to show how to test Spring Boot 2 Application with JUnit 5 making rollback after each @Test method is called.

That approach is useful when we want to use the same application instance across many tests.

Quick solution: 

Add @Transactional annotation for the class that contains your tests.

Example file:

package com.example;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.transaction.annotation.Transactional;

@Transactional  // <-------------- @Transactional annotation rollbacks @Test methods calls
class UserRestControllerTest {

    private MockMvc mockMvc;

    void test_mvc_1() {
        // ...

    void test_mvc_2() {
        // ...

    void test_mvc_3() {
        // ...


Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂