2017-07-03 173 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