问题
I am trying to test exception path for my controller with @WebfluxTest
, but it is always throws a server exception and then return a 500 error.
The test codes is here:
@Test
@Ignore // ignore it temporarily
public void getPostByNonExistedId_shouldReturn404() {
given(posts.findById("1"))
.willReturn(Mono.empty());
client.get().uri("/posts/1").exchange()
.expectStatus().isNotFound();
verify(this.posts, times(1)).findById(anyString());
verifyNoMoreInteractions(this.posts);
}
The controller codes is:
@GetMapping("/{id}")
public Mono<Post> get(@PathVariable("id") String id) {
return this.posts.findById(id).switchIfEmpty(Mono.error(new PostNotFoundException(id)));
}
The PostNotFoundException
is caught in the background correctly, but it is not handled by my custom RestExceptionHandler
in my @WebfluxTest
test.
回答1:
For the future audience for this question, this question was raised as an issue against the Spring Boot issue tracker by the author of the question and has been resolved via adding support for WebExceptionHandler
in @WebFluxTest
, so the code in question should just work since the Spring Boot 2.1.0.M3 which is not released yet at the time of writing.
来源:https://stackoverflow.com/questions/48162730/how-to-test-exception-with-webfluxtest