【问题标题】:Testing MVC controller using reactor with WebClient使用带有 WebClient 的反应器测试 MVC 控制器
【发布时间】:2019-04-18 14:31:57
【问题描述】:
@RestController
@RequestMapping("/api/v1/platform")
public class PlatformController {

  @Autowired
  private PlatformRepository platformRepository;


  @GetMapping
  public Flux<Platform> findAll() {
    log.info("Calling findAll platforms");
    return platformRepository.findAll();
  }
}


@RunWith(SpringRunner.class)
@WebFluxTest
public class PlatformControllerTest {

  @MockBean
  private PlatformRepository platformRepository;


  @Test
  public void findAll() throws Exception {
    WebTestClient client = WebTestClient.bindToController(new PlatformController()).build();
    client.get()
        .uri("/api/v1/platform")
        .exchange()
        .expectStatus().isOk();
  }

}

上面我附上了我想要实现的简单 POC。我无法将模拟注入控制器进行测试并且测试失败。有没有其他方法可以做到这一点,还是我错过了一些基本概念?

【问题讨论】:

    标签: java spring spring-boot spring-webflux project-reactor


    【解决方案1】:

    来自docs

    @WebFluxTest 自动配置 Spring WebFlux 基础设施和 将扫描的 bean 限制为 @Controller、@ControllerAdvice、 @JsonComponent、Converter、GenericConverter 和 WebFluxConfigurer。 不扫描常规 @Component bean 当@WebFluxTest 使用了注解。

    您可以尝试在WebFluxTest 注释中添加您的控制器类吗?

    @WebFluxTest(PlatformController.class)
    

    【讨论】:

    • 不幸的是,这没有帮助。我也尝试过另一种方法。我尝试添加 @WebFluxTest(PlatformController.class) 并尝试 Autowire WebTestClient。在这种情况下,它甚至不会调用控制器。它以 404 回复。 – Nandagopal Sekar 23 秒前编辑
    【解决方案2】:

    在我将控制器类添加到上下文配置后,事情开始起作用了。

    @RunWith(SpringRunner.class)
    @ContextConfiguration(classes = {
        PlatformController.class,
        MongoTestConfig.class
    })
    @WebFluxTest(PlatformController.class)
    

    我认为这可能是一个错误,因为控制器在包含在 WebFluxTest 注释中之后应该在上下文中。

    【讨论】:

      猜你喜欢
      • 2011-01-30
      • 1970-01-01
      • 2014-12-03
      • 2021-03-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多