Spring boot test @Transactional not saving

来源

本文来自于stackoverflow

问题描述

I’am trying to do a simple Integration test using Spring Boot Test in order to test the e2e use case. My test does not work because I’am not able to make the repository saving data, I think I have a problem with spring contexts …

JPA+Springboot 为某个service或者dao做单元测试时,发现始终插入不了数据。

测试代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class BootIntegrationTestApplicationTests {

@Autowired
private PersonService personService;
@Autowired
private TestRestTemplate restTemplate;

@Test
@Transactional
public void contextLoads() {
Person person = personService.createPerson(1, "person1");
Assert.assertNotNull(person);

ResponseEntity<Person[]> persons = restTemplate.getForEntity("/persons", Person[].class);
}
}

The test does not work, because the service is not saving the Person entity ….

问题解决

For each @Test function that makes a DB transaction, if you want to permanently persist the changes, then you can use @Rollback(false)
感觉@Test方法默认忽略掉了插入或者更新数据,如果你想在@Test方法内插入数据,需要加上@Rollback(false)注解。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
@Rollback(false)
@Test
public void createPerson() throws Exception {
int databaseSizeBeforeCreate = personRepository.findAll().size();

// Create the Person
restPersonMockMvc.perform(post("/api/people")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(person)))
.andExpect(status().isCreated());

// Validate the Person in the database
List<Person> personList = personRepository.findAll();
assertThat(personList).hasSize(databaseSizeBeforeCreate + 1);
Person testPerson = personList.get(personList.size() - 1);
assertThat(testPerson.getFirstName()).isEqualTo(DEFAULT_FIRST_NAME);
assertThat(testPerson.getLastName()).isEqualTo(DEFAULT_LAST_NAME);
assertThat(testPerson.getAge()).isEqualTo(DEFAULT_AGE);
assertThat(testPerson.getCity()).isEqualTo(DEFAULT_CITY);
}

I tested it with a SpringBoot project generated by jHipster:

  • SpringBoot: 1.5.4
  • jUnit 4.12
  • Spring 4.3.9