从JpaRepository获取数据时没有从WebTestClient收到数据

问题描述 投票:0回答:1

我有一个简单的集成测试用例,我想在其中查找特定数据。 首先,我使用 .save() 插入数据。虽然它工作成功(正如我调试的那样,并且 this.dataRepository.findAll() 不返回 null),但是当我使用 WebTestClient 使用相同的方法(this.dataRepository.findAll())获取特定数据时,它返回空

@RequestMapping(value = "/api/constant")
public class ConfigurationController {

  @Autowired
  private DataRepository dataRepository;

  @GetMapping
  public Mono<Object> getConstant() {
    Mono.fromSupplier(() -> this.dataRepository.findAll()).subscribeOn(Schedulers.single());
  }
}
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK)
@AutoConfigureWebTestClient
@Transactional
public class TestITCase {

  @Autowired
  private DataRepository dataRepository;

  @Autowired
  private WebTestClient webTestClient;

  @Test
  public void getConstants_Valid_Success()  {
    this.dataRepository.saveAndFlush(data);
    this.dataRepository.findAll(); // the data exist
    FluxExchangeResult<String> result = this.webTestClient.get()
        .uri(b -> b.path("/api/constant")
            .build())
        .header(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE)
        .exchange()
        .returnResult(String.class)
        .getResponseBody()
        .blockFirst(); // this returns null for some reason
  }
}

更新

显然在使用 WebTestClient 时,

此请求在不同的线程中处理,因此使用新的事务。 存储库插入在带有 WebTestClient 的 SpringBootTest 中不起作用

但现在我想知道是否有一种方法可以使 WebTestClient 在同一线程上运行?因为我不想提交事务然后回滚它,因为它不会在我的测试中创建幂等性(例如测试在 .delete() 之前失败),然后数据被意外保存。

java spring-boot spring-webflux spring-test
1个回答
0
投票

我不确定你如何在同一个项目中混合WebFlux和JPA,如果你在同一个Spring Boot项目中混合Webmvc和WebFlux,默认情况下不应该启用Webflux,启动应用程序时,它将通过Mvc引导应用程序堆栈。

我们应该避免传统的阻塞式Mvc堆栈和反应式WebFlux。但是将 JPA 混合到 WebFlux 应用程序中是可能的。我有一个使用 JPA 和 R2dbc 的 WebFlux 示例项目。

https://github.com/hantsy/spring-puzzles/tree/master/jpa-r2dbc/

使用

WebTestClient
进行测试也是可能的,https://github.com/hantsy/spring-puzzles/blob/master/jpa-r2dbc/src/test/java/com/example/demo/ApplicationTests.java

© www.soinside.com 2019 - 2024. All rights reserved.