簡體   English   中英

Spock + Spring Boot Web-獲取異常消息

[英]Spock + spring boot web - get exception message

因此,我正在使用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

如何在此處查看異常消息?

您可以如下顯式設置contentType

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM