![](/img/trans.png)
[英]spring-data-rest integration test fails with simple json request
[英]Spring boot & Spring data rest integration test fails to persist data
我正在使用Spring Boot和Spring Data Rest公开我的数据存储库。
我编写的集成测试将一个用户添加到数据库中,然后调用rest方法列出用户。 但是未列出添加的用户。
一个ApplicationRunner用于用数据填充数据库,而我正在使用Spring配置文件来存储不同的数据库。
例如,对于我的测试:
spring:
profiles: unittest
datasource:
url: 'jdbc:h2:mem:MYDB;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE'
driver-class-name: org.h2.Driver
username: myname
password: mypassword
jpa:
show-sql: true
hibernate:
ddl-auto: create-drop
jpa:
hibernate:
dialect: org.hibernate.dialect.H2Dialect
单元测试:
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
@ActiveProfiles("unittest")
@AutoConfigureTestEntityManager
@Transactional
public class MyUserRepoIntegrationTest {
private static Logger log = Logger.getLogger(MyUserRepoIntegrationTest.class);
// 3 default users + "test"
private static final int NUM_USERS = 4;
@Autowired
private TestRestTemplate restTemplate;
@Autowired
private TestEntityManager entityManager;
@Before
public void setupTests() {
entityManager.persistAndFlush(new MyUser("test", "test"));
}
@Test
public void listUsers() {
ResponseEntity<String> response = restTemplate.withBasicAuth("user", "user").getForEntity("/apiv1/data/users", String.class);
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(response.getBody()).contains("\"totalElements\" : "+NUM_USERS);
}
}
最后一个断言总是失败。 数据库中只有3个用户,这些用户是由ApplicationRunner(通过userRepository)添加的。 我尝试使用userRepository而不是TestEntityManager并在测试方法本身内部添加用户,但是没有任何变化。
我已经证实,它使用的是H2,而不是我的生产数据库。
编辑:
经过仔细检查,数据实际上到达了数据库。 当我注入UserRepository并调用.count()时,它给了我NUM_USERS(4)。
问题可能出在Spring Data REST上,因为REST响应不包括新用户。 我也尝试过修改现有用户并显式调用flush(),但响应仍然相同。 我已经从POM中删除了“ spring-boot-starter-cache”,并为我的application.yml添加了spring.cache.type = none作为“ unittest”配置文件,但是没有运气。
我正在使用UserRepository现在添加数据,并且已经完全删除了TestEntityManager。 现在可以使用...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.