簡體   English   中英

使用WebTestClient和ControllerAdvice進行單元測試彈簧控制器

[英]unit test spring controller with WebTestClient and ControllerAdvice

我正在嘗試對我的控制器和特定情況進行單元測試:我的服務返回一個Mono.Empty,我拋出一個NotFoundException,我不想確保我得到一個404異常

這是我的控制器:

@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()));

    }

這是我的控制器建議:

@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");
    }

}

和我的測試:

@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);

    }

我得到一個NotFoundException但是500錯誤而不是404這意味着我的建議還沒有被調用

堆棧跟蹤 :

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

任何的想法 ?

我相信你可以刪除這個控制器的建議,只需要有以下內容:

    @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)));

    }

至於ResponseEntityExceptionHandler ,這個類是Spring MVC的一部分,所以我認為你不應該在WebFlux應用程序中使用它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM