2017-07-03 12 views
2

私のコントローラと、特定のケースをユニットテストしようとしています。私のサービスはMono.Emptyを返します。私はNotFoundExceptionをスローします。WebTestClientとControllerAdviceを使用したユニットテストスプリングコントローラ

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

} 

と私のテスト:

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

    } 

はここに私のコントローラのアドバイスです:

例外ここ

を取得することは、私のコントローラです

@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

私はあなたがこのコントローラのアドバイスを削除することができ、ちょうど次ていると信じて:私はあなたがWebFluxアプリケーションでそれを使用すべきとは思わないResponseEntityExceptionHandlerについては

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

    } 

を、このクラスはSpring MVCのの一部です。 。

+0

こんにちは、お返事ありがとうございます。実際に私はwebfluxで使用されているControllerAdviceの例を見つけたので、私はそれを使うことができると思います – Seb

+0

十分に公正です。 'ResponseEntityExceptionHandler'を指定すると、classpathにspring-webmvcがある可能性があります。プロジェクトからその依存関係を削除し、 'ResponseEntityExceptionHandler'から拡張しないことができますか? –

+0

私は試してもチャンスはありません:/ – Seb

関連する問題