【问题标题】:JMockit - Throwable is not mockableJMockit - Throwable 不可模拟
【发布时间】:2021-01-07 20:22:29
【问题描述】:

我升级了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);
}

自定义异常

@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;
    }
}

【问题讨论】:

    标签: java testng java-11 jmockit


    【解决方案1】:

    在这里使用模拟异常有点矫枉过正。这个测试应该可以工作(使用真正的异常)

    @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 帖子中找到执行此操作的方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-12-24
      • 2011-05-09
      • 1970-01-01
      • 2015-11-13
      • 2014-12-17
      • 1970-01-01
      • 1970-01-01
      • 2013-09-03
      相关资源
      最近更新 更多