[英]How to test Controller that returns Mono<ResponseEntity<Void>>?
I'm pretty new to webflux and I am struggling to understand how to test this Controller function.我对 webflux 很陌生,我很难理解如何测试这个 Controller 功能。
public Mono<ResponseEntity<Void>> functionName(final Request request) {
RequestDto Dto = RequestMapper.
INSTANCE.toDto(request);
service.functionName(Dto);
return Mono.just(new ResponseEntity<Void>(HttpStatus.OK));
}
You could use WebTestClient
that provides fluent API for verifying responses.您可以使用
WebTestClient
提供流畅的 API 来验证响应。 Here is a short example这是一个简短的例子
@WebFluxTest
class ControllerTest {
@Autowired
private WebTestClient client;
@BeforeEach
void setUp(ApplicationContext context) {
client = WebTestClient.bindToApplicationContext(context).build();
}
@Test
void test() {
client.get()
.uri("/test")
.exchange()
.expectStatus().isOk()
.expectBody().isEmpty();
}
}
In addition, pay attention to endpoint implementation.另外,注意端点的实现。 In reactive you need to build the flow and Webflux will subscribe to it for every request.
在响应式中,您需要构建流程,Webflux 将为每个请求订阅它。 In case,
service.functionName
is blocking (non-reactive), consider running it on a separate Scheduler
using .subscribeOn(Schedulers.boundedElastic())
.如果
service.functionName
阻塞(非响应式),请考虑使用.subscribeOn(Schedulers.boundedElastic())
在单独的Scheduler
上运行它。 For details, check How Do I Wrap a Synchronous, Blocking Call?有关详细信息,请查看如何打包同步阻塞呼叫? .
.
If the Callable
resolves to null
, the resulting Mono
completes empty and we could return 404
applying switchIfEmpty
operator.如果
Callable
解析为null
,则生成的Mono
完成为空,我们可以应用switchIfEmpty
运算符返回404
。
@GetMapping(path = "/test")
public Mono<ResponseEntity<Void>> functionName(Request request) {
return Mono.fromCallable(() -> {
RequestDto Dto = RequestMapper.INSTANCE.toDto(request);
return service.functionName(Dto);
}).subscribeOn(Schedulers.boundedElastic())
.map(res -> new ResponseEntity<>(HttpStatus.OK))
.switchIfEmpty(Mono.just(new ResponseEntity<>(HttpStatus.NOT_FOUND)));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.