SpringBootTest-请求无效时测试异常

时间:2018-11-21 02:42:29

标签: unit-testing spring-boot kotlin reactive-programming spring-webflux

我使用web-flux开发了一个API,当我使用POSTMAN发出请求时,该API工作正常。我的代码是:

控制器:

@PostMapping("/post", produces = ["application/xml"])
fun post(@Valid request: RequestData): Mono<Response> {
    return Mono.just(request)
    ...
    ...
    ...
}

dto:

data class RequestData(

    @get:NotBlank
    @get:Email
    val email: String = "",
)

因此,每当我通过POSTMAN传递无效的电子邮件时,我都会捕获到如下所示的异常及其正常工作:

@ExceptionHandler
fun bindingExceptionHandler(e: WebExchangeBindException) = "Custom Error Message"

但是现在当我针对这种情况(无效的emaid)编写UT(@WebFluxTest)时,它失败了。

@Test
fun testWhenInvalidEmail() {

    // Request body
    val email = "invalidemail"
    val request = LinkedMultiValueMap<String, String>()
    request.add("email", email)

    webTestClient.post().uri("/post")
        .body(BodyInserters.fromFormData(request))
        .exchange()
        .expectStatus().isOk
}

当我调试它时,我发现当通过单元测试的请求时,我的exceptionHandler没有出现。我在POST请求中使用了application/x-www-form-urlencoded内容类型。

请让我知道我做错了什么。 I followed this question as well but didn't work.

1 个答案:

答案 0 :(得分:0)

如另一个相关问题所述,此问题已在Spring Boot 2.1.0中修复。

此外,您不必自己构建WebTestClient,而应将其注入测试类(see reference documentation about that):

@RunWith(SpringRunner.class)
@WebFluxTest(MyValidationController.class)
public class MyValidationControllerTests {

    @Autowired
    private WebTestClient webClient;

    @Test
    public void testWhenInvalidEmail() {
        //...
    }

}