JMockit - Throwable is not mockable

Viewed 511

I upgraded org.jmockit:jmockit:1.31 -> org.jmockit:jmockit:1.34 and I'm getting the following error when trying to mock an exception: Class java.lang.Throwable is not mockable

What changes were made in Jmockit to no longer make mocking throwable exceptions possible?

Java 11
JMockit 1.34
Testng 6.9.10

Test

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

Using a mock Exception is a bit of overkill here. This test should work (using a real exception)

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

This test would be treated as if rrun(..) caused the CustomResponseException to be thrown (I believe your intent). If instead, you want it to act as if it returned an exception (peculiar), there are ways to do that which you can find in other SO posts.

Related