Spring Boot 测试自定义 Errors Controller

SpringBoot test custom Errors Controller

按照这里的建议 Spring Boot Remove Whitelabel Error Page 我创建了一个自定义错误控制器来 return 自定义错误响应 json 格式看起来像

@RestController
public class CustomErrorController implements ErrorController {

private static final String PATH = "/error";

@Value("${spring.debug:false}")
private boolean debug;

@Autowired
private ErrorAttributes errorAttributes;

  @RequestMapping(value = PATH)
  ErrorJson error(HttpServletRequest request, HttpServletResponse response) {
    return new ErrorJson(response.getStatus(), getErrorAttributes(request, debug));
  }

  private Map<String, Object> getErrorAttributes(HttpServletRequest request, boolean includeStackTrace) {
    RequestAttributes requestAttributes = new ServletRequestAttributes(request);
    return errorAttributes.getErrorAttributes(requestAttributes, includeStackTrace);
  }

  @Override
  public String getErrorPath() {
    return PATH;
  }

}

其中 CustomErrorController 实现 ErrorControllerErrorJson 只是一个简单的 class 来格式化 json 错误响应。

现在我正在尝试编写一个测试,以测试 CustomErrorController 是否处理了一个不存在的 enpoint,并且 returns 一个 404 和 json 响应如下:

{
  "status": 404,
  "error": "Not Found",
  "message": "No message available",
  "timeStamp": "Thu Jun 29 14:55:44 PDT 2017",
  "trace": null
}

我的测试目前看起来像

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class CustomErrorControllerTest {

    @Autowired
    private MockMvc mockMvc;


    @Test
    public void invalidURLGet() throws Exception {
        mockMvc.perform(MockMvcRequestBuilders.get("/foo"))
                .andExpect(status().is(404))
                .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))
                .andReturn();

    }


}

我收到状态为 404 的错误响应,但内容正文为空,MockHttpServletResponse 为:

MockHttpServletResponse:
           Status = 404
    Error message = null
          Headers = {X-Application-Context=[application:development:-1]}
     Content type = null
             Body = 
    Forwarded URL = null
   Redirected URL = null
          Cookies = []

那么,我有两个问题:

  1. 为什么内容主体为空。 MockMvc 是否找不到 CustomErrorController.
  2. 我是否错误地测试了错误行为。如果可以,我该如何测试自定义错误响应?

您可以使用 TestRestTemplate 来更进一步。这将使您不仅可以进行适当的 URI 调用,还可以让您有机会将您的响应序列化为实际的 object 它返回以验证您的 body 和其他元素是否实际存在.

简要示例:

// Elsewhere...
@Autowired
private TestRestTemplate template;

// In your tests...
ErrorJson result = template.getForObject("/error", ErrorJson.class);

// Inspect the result!