当前位置: 首页 > 知识库问答 >
问题:

Spring boot&Spring data rest集成测试无法持久化数据

靳睿
2023-03-14

我正在使用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);
  }
}

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

问题可能出在Spring Data REST上,因为REST响应不包括新用户。我还尝试修改一个现有用户并显式调用flush(),但响应仍然是相同的。我已经从POM中删除了'spring-boot-starter-cache'并为'unitTest'配置文件添加了spring.cache.type=none到application.yml中,但没有成功。

共有1个答案

贾烨
2023-03-14

我现在正在使用UserRepository添加数据,并且已经完全删除了TestEntityManager。现在起作用了...

 类似资料:
  • 我尝试使用MockMVC和TestRestTemboard。在这两种情况下,返回的响应都是404,但是APIendpoint在集成测试之外工作(当我自己运行Spring应用时)。 有没有人有一个可以工作的示例应用程序,它使用SpringDataREST对生成的控制器进行了工作集成测试? 我还可以编写针对自己控制器的常规集成测试(非SDR类型) 测试代码: 回购: 好的,我发现了问题,但我不知道答案

  • 在上一章最后,我们写的测试可以算得上是单元测试,接着我们可以写一些自动化测试。 编写自动化测试 接着我们就可以用Selenium来做自动化测试。这是ThoughtWorks出品的一个强大的基于浏览器的开源自动化测试工具,它通常用来编写Web 应用的自动化测试。 Selenium与第一个UI测试 先让我们来看一个自动化测试的例子: from django.test import LiveServer

  • translated_page: https://github.com/PX4/Devguide/blob/master/en/test_and_ci/continous_integration.md translated_sha: 95b39d747851dd01c1fe5d36b24e59ec865e323e PX4 Continuous Integration PX4 builds and

  • 我在SpringBoot 2上有一个应用程序。x个 pom。xml 这是应该自动连接的类。。。 pom。xml 更新 这个类来自类似的项目,它可以工作(但Intellij的想法将字段标记为错误) 在src/test/java/weblogic/war/Spring/boot/service/read/CompanyReadServiceTest.java 我复制了一个项目。 更新\u 2 我清除了

  • 我正在尝试使用来持久化一个实体。当我自己处理事务时,我的测试用例工作(数据保存在db中)。 (实体管理器来自我的DAO类扩展的模板类) 当我配置spring来处理事务时,它会停止分发数据。 测试上下文。xml: UsersRepositoryTest: 堆栈跟踪: 从stacktrace中可以看到,事务似乎已经启动和完成,但没有生成sql插入,也没有数据插入到数据库中(数据回滚设置为false)