java - 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
如何在此处检查异常消息?
解决方案
您可以显式设置 contentType 如下
@ExceptionHandler(OrgNotFoundException.class)
public ResponseEntity<String> exceptionHandler(final Exception ex) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).contentType(MediaType.APPLICATION_JSON)
.body("Error");
}
推荐阅读
- sql - 如何确保结果对是唯一的 - 不使用不同的?
- javascript - Google Apps 脚本。For 循环不工作
- odoo - 如何将值从销售传递到发票odoo?
- django - 如何合并两个查询集并在 django 中创建新的查询集
- php - 连接到 mySQL 时出错:SQLSTATE[HY093]: Invalid parameter number
- jersey - Jersey 应用程序可以拥有多少个 RootResources 和 SubResources 是否有限制?
- javascript - mongoose 上的数组字段类型的分页不起作用,但适用于 mongo shell
- spring-boot - Spring Boot中的Jetty自定义格式日志模式
- python - adb - 在 android 设备中获取应用程序名称(设置 > 应用程序)#python
- workflow - Alfresco 工作流 api 正在丢失一个变量