Languages
[Edit]
EN

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

14 points
Created by:
maxsior322
227

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 UserRestControllerTest.java 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
@SpringBootTest
@AutoConfigureMockMvc
class UserRestControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @Test
    void test_mvc_1() {
        // ...
    }

    @Test
    void test_mvc_2() {
        // ...
    }

    @Test
    void test_mvc_3() {
        // ...
    }
}

 

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.

❤️💻 🙂

Join