使用 Reactor 和 WebClient 测试 MVC 控制器
Testing MVC controller using reactor with WebClient
@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。我无法将模拟注入控制器以进行测试,并且测试失败。有没有其他方法可以做到这一点,或者我是否遗漏了一些基本概念?
来自docs:
@WebFluxTest auto-configures the Spring WebFlux infrastructure and
limits scanned beans to @Controller, @ControllerAdvice,
@JsonComponent, Converter, GenericConverter, and WebFluxConfigurer.
Regular @Component beans are not scanned when the @WebFluxTest
annotation is used.
您可以尝试在 WebFluxTest
注释中添加您的控制器 class 吗?
@WebFluxTest(PlatformController.class)
在我将控制器 class 添加到上下文配置后一切开始正常工作。
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = {
PlatformController.class,
MongoTestConfig.class
})
@WebFluxTest(PlatformController.class)
我认为这可能是一个错误,因为控制器在包含在 WebFluxTest 注释中后应该在上下文中。
@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。我无法将模拟注入控制器以进行测试,并且测试失败。有没有其他方法可以做到这一点,或者我是否遗漏了一些基本概念?
来自docs:
@WebFluxTest auto-configures the Spring WebFlux infrastructure and limits scanned beans to @Controller, @ControllerAdvice, @JsonComponent, Converter, GenericConverter, and WebFluxConfigurer. Regular @Component beans are not scanned when the @WebFluxTest annotation is used.
您可以尝试在 WebFluxTest
注释中添加您的控制器 class 吗?
@WebFluxTest(PlatformController.class)
在我将控制器 class 添加到上下文配置后一切开始正常工作。
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = {
PlatformController.class,
MongoTestConfig.class
})
@WebFluxTest(PlatformController.class)
我认为这可能是一个错误,因为控制器在包含在 WebFluxTest 注释中后应该在上下文中。