[英]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.