Spring Boot微服务Cucumber集成测试中插入数据后无法查询到记录的问题求助
Spring Boot微服务Cucumber集成测试中插入数据后无法查询到记录的问题求助
我现在碰到一个头疼的问题:我们有个基于Java/SpringBoot的RESTful微服务,配套了用Cucumber写的集成测试模块。测试执行时,调用插入数据接口的步骤明明已经成功把数据写入数据库了——接口不仅返回了带新ID的完整Book对象,响应校验也通过了,但到了后续checkData()步骤查询数据库时,却死活查不到这条记录,返回的结果永远是0条!
我翻了日志,排除了多数据源的问题,大概率是注解或者配置哪里写错了,但折腾了两天各种调整都没搞定。下面是相关代码和配置,求各位大佬帮忙看看!
测试类代码
@CucumberContextConfiguration @ContextConfiguration(classes = {MainApp.class}) @RunWith(Cucumber.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = {MainApp.class}) @Import(MainApp.class) @EnableAutoConfiguration @AutoConfigureWireMock(port = 0) public class ApplicationTestSteps { @Autowired private JdbcTemplate jdbcTemplate; private List<Book> retrieveAllBooks() { return jdbcTemplate.query("select * from t_books", new BookMapper()); } @When("I call the insert data endpoint in the app") { // 调用应用的插入接口,向数据库插入Book数据 } @And("I check the database has the data") public void checkData() { assertThat(retrieveAllBooks().size()).isGreaterThan(0); } }
测试环境配置(application.yml)
spring: datasource: url: jdbc:h2:mem:LTESTDB;MODE=DB2 username: sa password: driver-class-name: org.h2.Driver jpa: defer-datasource-initialisation: true generate-ddl: false hibernate: hbm2ddl: auto: none hibernate: hbm2ddl.auto: update
补充说明:我们用/resources/schema.sql和/resources/data.sql来初始化数据库,因为生产环境是老的DB2数据库,API里的Book实体类只映射了表中部分字段。
已尝试的无效方案
- 在Cucumber测试类上加
@DirtiesContext注解 - 把事务隔离级别设置为
ReadUncommitted - 反复调整Spring相关注解的组合(比如增减
@ContextConfiguration、@Import等)
有没有朋友遇到过类似的情况?到底是哪里的问题导致插入的记录在后续Cucumber步骤里查不到啊?
内容来源于stack exchange
相关产品推荐
相关产品推荐

