【发布时间】:2017-04-27 06:16:31
【问题描述】:
我正在使用 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' 并将 spring.cache.type=none 添加到我的 application.yml 以用于 'unittest' 配置文件,但没有运气。
【问题讨论】:
-
您是否尝试过移动用户添加测试方法而不是设置方法?
-
是的,正如我在倒数第二句话中所写的那样。
标签: java spring spring-boot integration-testing spring-data-rest