【问题标题】:Spock + spring boot web - get exception messageSpock + spring boot web - 获取异常消息
【发布时间】:2019-10-07 13:28:36
【问题描述】:

所以,我用的是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

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

【问题讨论】:

  • 您可以使用 Postman 调用您的端点并手动检查返回的内容和标头吗?

标签: java spring spring-boot spock spring-test


【解决方案1】:

您可以如下显式设置 contentType

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

【讨论】:

    猜你喜欢
    • 2020-05-26
    • 2014-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-31
    相关资源
    最近更新 更多