首页 > 解决方案 > Spock + spring boot web - 获取异常消息

问题描述

所以,我正在使用spring boot web,我想测试这个方法:

private void testException(HotelTvApp app) {
    throw new InternalServerException("Test message");
}

返回自定义异常:

@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public class InternalServerException extends RuntimeException {
    public InternalServerException(String message) {
        super(message);
    }
}

调用此方法的控制器返回以下 JSON 数据:

{
  "timestamp": 1558423837560,
  "status": 500,
  "error": "Internal Server Error",
  "message": "Test message",
  "path": "/api/v1/test"
}

我想编写一个测试来检查异常消息是否正确。我试过这个:

def "createRoom() should return 500 if trying to create room with already existing number"() {
    given:
    def uriRequest = UriComponentsBuilder.fromPath("/api/v1/test")

    when:
    def perform = mvc.perform(get(uriRequest.toUriString()))

    then:
    perform.andExpect(status().isInternalServerError())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))
            .andExpect(jsonPath('$.message', is("Test message")))
}

但我得到了这个例外: Caused by: java.lang.AssertionError: Content type not set

如何在此处检查异常消息?

标签: javaspringspring-bootspockspring-test

解决方案


您可以显式设置 contentType 如下

@ExceptionHandler(OrgNotFoundException.class)
public ResponseEntity<String> exceptionHandler(final Exception ex) {
    return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).contentType(MediaType.APPLICATION_JSON)
            .body("Error");
}

推荐阅读