Spring boot & Spring data rest 集成测试持久化数据失败

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 数据 REST,因为 REST 响应不包括新用户。我也试过修改现有用户并显式调用 flush(),但响应仍然相同。 我已经从我的 POM 中删除了 'spring-boot-starter-cache',并将 spring.cache.type=none 添加到我的 application.yml 的 'unittest' 配置文件中,但没有成功。

我现在使用 UserRepository 添加数据并完全删除了 TestEntityManager。现在可以使用了...