spring-mvc – Spring MockMvc和异步控制器的HTTP状态代码

当我的控制器具有异步servlet性质时,如何在MockMvc中验证/测试500内部服务器错误?

我正在为我的REST端点编写单元测试用例作为测试用例的一部分我需要验证服务器发送500内部错误作为http代码并带有相应的错误消息.

这是我的基于春季启动的应用程序:
(为了更好的可读性,省略了所有导入)

@RestController
@RequestMapping("/user")
@EnableAutoConfiguration
@SpringBootApplication
public class App 
{
    @RequestMapping(method = RequestMethod.GET, value = "/{name}", 
            produces = MediaType.APPLICATION_JSON_VALUE)
    private DeferredResult<String> greetByJson(@PathVariable("name") final String name){
        DeferredResult<String> dResult = new DeferredResult<String>();

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(5000);
                    dResult.setErrorResult(new RuntimeException("Boom!!! time for Internal server error"));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();

        return dResult;
    }

    public static void main( String[] args )
    {
        SpringApplication.run(App.class);
    }
}

这是我的MovkMvc JUnit测试用例:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = MockServletContext.class)
@WebAppConfiguration
public class AppTest {

    private final MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new App())
            .build();

    @Test
    public void testAsyncInternalServerError() {
        try {
            MvcResult mvcResult = mockMvc.perform(
                    get("/user/naveen").accept(MediaType.APPLICATION_JSON_VALUE))
                    .andExpect(request().asyncStarted())
                    .andReturn();

            System.out.println("Http Response Content = " + mvcResult.getAsyncResult());
            System.out.println("Http Response Status Code = " + mvcResult.getResponse().getStatus());

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

下面是控制台打印:

2015-08-08 18:11:51.494  INFO 10224 --- [           main] o.s.w.c.s.GenericWebApplicationContext   : Refreshing org.springframework.web.context.support.GenericWebApplicationContext@a82c5f1: startup date [Sat Aug 08 18:11:51 IST 2015]; root of context hierarchy
2015-08-08 18:11:51.526  INFO 10224 --- [           main] o.e.j.i.junit.runner.RemoteTestRunner    : Started RemoteTestRunner in 0.258 seconds (JVM running for 1.131)
Http Response Content = java.lang.RuntimeException: Boom!!! time for Internal server error
Http Response Status Code = 200
2015-08-08 18:11:56.584  INFO 10224 --- [       Thread-1] o.s.w.c.s.GenericWebApplicationContext   : Closing org.springframework.web.context.support.GenericWebApplicationContext@a82c5f1: startup date [Sat Aug 08 18:11:51 IST 2015]; root of context hierarchy

从上面的日志可以看出,MockMvc将http状态代码返回为200而不是500.错误消息很好.

当我使用Chrome邮递员调用终点时,我在imageenter image description here中看到附加的500内部服务器错误

最佳答案
您必须执行异步调度并在之后测试状态:

@Test
public void testMethod() throws Exception {

    MvcResult mvcResult = mockMvc.perform(get("/your/endpoint"))
            .andExpect(request().asyncStarted())
            .andExpect(request().asyncResult(notNullValue()))
            .andReturn();

    mockMvc.perform(asyncDispatch(mvcResult))
            .andExpect(status().isInternalServerError())
            .andReturn();

}

转载注明原文:spring-mvc – Spring MockMvc和异步控制器的HTTP状态代码 - 代码日志