首页 文章

Spring引导和Spring数据休息集成测试无法持久保存数据

提问于
浏览
0

我正在使用Spring Boot和Spring Data Rest来公开我的数据存储库 .

我编写的集成测试,将用户添加到数据库,然后调用rest方法列出用户 . 但添加的用户未被列出 .

ApplicationRunner用于使用数据填充DB,我使用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而不是我的 生产环境 数据库 .

EDIT:

仔细检查后,数据实际上会进入数据库 . 当我注入我的UserRepository并调用.count()时,它给了我NUM_USERS(4) .

问题可能在于Spring Data REST,因为REST响应不包括新用户 . 我也尝试修改现有用户并显式调用flush(),但响应仍然相同 . 我从我的POM中删除了'spring-boot-starter-cache',并将spring.cache.type = none添加到我的application.yml中以获取'unittest'配置文件,但没有运气 .

1 回答

  • 0

    我正在使用UserRepository现在添加数据并完全删除了TestEntityManager . 它现在有效......

相关问题