2017-07-03 76 views
2

我想單元測試我的控制器和具體情況是:我的服務返回一個Mono.Empty,我拋出一個NotFoundException,我不想確定我是得到一個404例外單元測試彈簧控制器與WebTestClient和ControllerAdvice

這裏是我的控制器:

@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 

什麼想法?

回答

2

我相信你可以刪除該控制器的建議,只是有以下幾點:

@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應用程序中使用。

+0

嗨,謝謝你的回覆。實際上我發現ControllerAdvice的例子與webflux一起使用,所以我認爲我應該可以使用它 – Seb

+0

夠公平的。擁有'ResponseEntityExceptionHandler'意味着你可能在類路徑上有spring-webmvc(你不應該)。你可以嘗試從你的項目中刪除該依賴項,而不是從'ResponseEntityExceptionHandler'擴展嗎? –

+0

我試過了,沒有機會:/ – Seb