问题描述
我升级了org.jmockit:jmockit:1.31 -> org.jmockit:jmockit:1.34
,尝试模拟异常时遇到以下错误:Class java.lang.Throwable is not mockable
在Jmockit中进行了哪些更改以不再使模拟可抛出异常成为可能?
Java 11
JMockit 1.34
Testng 6.9.10
测试
@Test
public void HttpStatusWhenFailure(@Injectable CustomresponseException e) throws CustomException {
new Expectations() {{
ProxyManager.rrun((String) any); result = e;
e.getHttpStatus(); result = 500;
}};
Response response = resource.run(YearMonth.Now().toString());
assertEquals(response.getStatus(),500);
}
CustomException
@ApplicationException
public class CustomException extends Exception {
private static final long serialVersionUID = 100L;
protected int httpStatus;
public CustomException(int httpStatus) {
super();
this.httpStatus = httpStatus;
}
public CustomException(int httpStatus,String message) {
super(message);
this.httpStatus = httpStatus;
}
public CustomException(int httpStatus,String message,Throwable cause) {
super(message,cause);
this.httpStatus = httpStatus;
}
public CustomException(int httpStatus,Throwable cause) {
super(cause);
this.httpStatus = httpStatus;
}
public int getHttpStatus() {
return httpStatus;
}
}
解决方法
在此处使用模拟异常有点夸张。该测试应该可以工作(使用真正的异常)
@Test
public void HttpStatusWhenFailure() throws CustomException {
new Expectations() {{
ProxyManager.rrun((String) any); result = new CustomResponseException(500,"msg");
}};
Response response = resource.run(YearMonth.now().toString());
assertEquals(response.getStatus(),500);
}
该测试将被视为好像rrun(..)导致抛出CustomResponseException(我相信您的意图)一样。相反,如果您希望它像返回异常(异常)一样起作用,那么您可以在其他SO帖子中找到实现此目的的方法。