5

コントローラーと特定のケースを単体テストしようとしています:私のサービスは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 が発生していますが、404 ではなく 500 エラーです。これは、アドバイスが呼び出されていないことを意味します

スタックトレース :

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

何か案が ?

4

1 に答える 1

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 アプリケーションで使用する必要はないと思います。

于 2017-07-03T12:38:04.620 に答える