[英]unit test spring controller with WebTestClient and ControllerAdvice
I'm trying to unit test my controller and the specific case which is : my service return a Mono.Empty, I throw a NotFoundException and I wan't to make sure I'm getting a 404 exception 我正在尝试对我的控制器和特定情况进行单元测试:我的服务返回一个Mono.Empty,我抛出一个NotFoundException,我不想确保我得到一个404异常
here's my controller : 这是我的控制器:
@GetMapping(path = "/{id}")
public Mono<MyObject<JsonNode>> getFragmentById(@PathVariable(value = "id") String id) throws NotFoundException {
return this.myService.getObject(id, JsonNode.class).switchIfEmpty(Mono.error(new NotFoundException()));
}
Here's my controller advice : 这是我的控制器建议:
@ControllerAdvice
public class RestResponseEntityExceptionHandler {
@ExceptionHandler(value = { NotFoundException.class })
protected ResponseEntity<String> handleNotFound(SaveActionException ex, WebRequest request) {
String bodyOfResponse = "This should be application specific";
return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Resource not found");
}
}
and my test : 和我的测试:
@Before
public void setup() {
client = WebTestClient.bindToController(new MyController()).controllerAdvice(new RestResponseEntityExceptionHandler()).build();
}
@Test
public void assert_404() throws Exception {
when(myService.getobject("id", JsonNode.class)).thenReturn(Mono.empty());
WebTestClient.ResponseSpec response = client.get().uri("/api/object/id").exchange();
response.expectStatus().isEqualTo(404);
}
I'm getting a NotFoundException But a 500 error not a 404 which mean my advice hasn't been called 我得到一个NotFoundException但是500错误而不是404这意味着我的建议还没有被调用
stack trace : 堆栈跟踪 :
java.lang.AssertionError: Status expected:<404> but was:<500>
> GET /api/fragments/idFragment
> WebTestClient-Request-Id: [1]
No content
< 500 Internal Server Error
< Content-Type: [application/json;charset=UTF-8]
Content not available yet
any idea ? 任何的想法 ?
I believe you can delete this controller advice and just have the following: 我相信你可以删除这个控制器的建议,只需要有以下内容:
@GetMapping(path = "/{id}")
public Mono<MyObject<JsonNode>> getFragmentById(@PathVariable(value = "id") String id) {
return this.myService.getObject(id, JsonNode.class)
.switchIfEmpty(Mono.error(new ResponseStatusException(HttpStatus.NOT_FOUND)));
}
As for ResponseEntityExceptionHandler
, this class is part of Spring MVC so I don't think you should use it in a WebFlux application. 至于ResponseEntityExceptionHandler
,这个类是Spring MVC的一部分,所以我认为你不应该在WebFlux应用程序中使用它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.