EN
Spring Boot - rollback transaction after each @Test method (JUnit 5)
14 points
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:
xxxxxxxxxx
1
package com.example;
2
3
import org.junit.jupiter.api.Test;
4
import org.springframework.beans.factory.annotation.Autowired;
5
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
6
import org.springframework.boot.test.context.SpringBootTest;
7
import org.springframework.test.web.servlet.MockMvc;
8
import org.springframework.transaction.annotation.Transactional;
9
10
// <-------------- @Transactional annotation rollbacks @Test methods calls
11
12
13
class UserRestControllerTest {
14
15
16
private MockMvc mockMvc;
17
18
19
void test_mvc_1() {
20
// ...
21
}
22
23
24
void test_mvc_2() {
25
// ...
26
}
27
28
29
void test_mvc_3() {
30
// ...
31
}
32
}