如何在Mockito测试中抛出408 HTTP状态码对应的异常?
方案1:使用Spring自带的通用状态码异常(推荐,Spring 5+适用)
Spring框架从5.0版本开始提供了通用的ResponseStatusException类,可以直接指定任意HTTP状态码,不需要额外自定义异常类,写法如下:
when(...) .thenThrow(new ResponseStatusException(HttpStatus.REQUEST_TIMEOUT));
如果需要携带自定义错误提示,也可以加消息参数:
when(...) .thenThrow(new ResponseStatusException(HttpStatus.REQUEST_TIMEOUT, "请求超时,请稍后重试"));
方案2:自定义带状态码映射的异常类
如果需要频繁使用408相关的业务异常,可以自定义专门的异常类,通过@ResponseStatus注解绑定408状态码:
- 先定义异常类:
import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ResponseStatus; @ResponseStatus(value = HttpStatus.REQUEST_TIMEOUT, reason = "请求超时") public class RequestTimeoutException extends RuntimeException { // 按需添加构造方法 public RequestTimeoutException() {} public RequestTimeoutException(String message) { super(message); } }
- 之后就可以和403的
ForbiddenException一样直接抛出:
when(...) .thenThrow(RequestTimeoutException.class);
方案3:JAX-RS规范场景适用
如果你的项目用的是JAX-RS而非Spring Web,可以直接用WebApplicationException指定状态码:
import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Response; when(...) .thenThrow(new WebApplicationException(Response.Status.REQUEST_TIMEOUT));
内容的提问来源于stack exchange,提问作者caitanna98
相关产品推荐
相关产品推荐

