本文介绍了MockMVC 如何在同一个测试用例中测试异常和响应代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想断言引发异常并且服务器返回 500 内部服务器错误.

I want to assert that an exception is raised and that the server returns an 500 internal server error.

为了突出意图,提供了一个代码片段:

To highlight the intent a code snippet is provided:

thrown.expect(NestedServletException.class);
this.mockMvc.perform(post("/account")
            .contentType(MediaType.APPLICATION_JSON)
            .content(requestString))
            .andExpect(status().isInternalServerError());

当然,我写isInternalServerErrorisOk 都没有关系.无论 throw.except 语句下方是否抛出异常,测试都会通过.

Of course it dosen't matter if I write isInternalServerError or isOk.The test will pass regardless if an exception is thrown below the throw.except statement.

你打算如何解决这个问题?

How would you go about to solve this?

推荐答案

您可以参考 MvcResult 和可能解决的异常并检查一般 JUnit 断言...

You can get a reference to the MvcResult and the possibly resolved exception and check with general JUnit assertions...

MvcResult result = this.mvc.perform(
        post("/api/some/endpoint")
                .contentType(TestUtil.APPLICATION_JSON_UTF8)
                .content(TestUtil.convertObjectToJsonBytes(someObject)))
        .andDo(print())
        .andExpect(status().is4xxClientError())
        .andReturn();

Optional<SomeException> someException = Optional.ofNullable((SomeException) result.getResolvedException());

someException.ifPresent( (se) -> assertThat(se, is(notNullValue())));
someException.ifPresent( (se) -> assertThat(se, is(instanceOf(SomeException.class))));

这篇关于MockMVC 如何在同一个测试用例中测试异常和响应代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-20 17:53