所以,我正在使用 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);
}
}
调用此方法的 Controller 返回以下 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")))
}
但是我得到了这个异常:
原因:java.lang.AssertionError:未设置内容类型
如何查看这里的异常消息?
最佳答案
您可以显式设置 contentType,如下所示
@ExceptionHandler(OrgNotFoundException.class)
public ResponseEntity<String> exceptionHandler(final Exception ex) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).contentType(MediaType.APPLICATION_JSON)
.body("Error");
}
关于java - Spock + Spring Boot Web - 获取异常消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56233433/