Junit 带有错误代码的自定义异常

Junit 带有错误代码的自定义异常,junit,Junit,我创建了一个带有自定义消息和错误代码的CustomException public class CustomException extends RuntimeException{ private int errorCode; public CustomException(String message,int errorCode){ super(message); this.errorCode=errorCode; } public int getErrorCode(){

我创建了一个带有自定义消息和错误代码的CustomException

public class CustomException extends RuntimeException{
private int errorCode;

public CustomException(String message,int errorCode){
    super(message);
    this.errorCode=errorCode;
}

public int getErrorCode(){
    return this.errorCode;
}

public String getMessage(){
    return "Message: "+super.getMessage()+" ErrorCode: "+this.errorCode;
}
}
当我在列表中添加空值时,抛出CustomException,消息为“null”,错误代码为1。当我添加一个空值时,异常消息为“empty”,错误代码为2。 如何在单元测试中捕获和测试错误代码? 我做过类似的事情:

公共类MyListTester{ 私有类异常类型=CustomException.Class

 @Test
 public void testAddNonNullValue() {
      exception.expect(exceptionType);
      exception.expectMessage("Null");
      list.add(null);
}

但是我没有访问错误代码的权限。诀窍是使用
ExpectedException
规则的
ExpectedException
方法,该规则将
Matcher
作为参数,并编写自定义Matcher来验证错误代码。下面是一个完整的示例:

public class MyListTester {

    @Rule
    public ExpectedException exception = ExpectedException.none();

    @Test
    public void testAddNullValue() {
        MyList list = new MyList();
        exception.expect(CustomException.class);
        exception.expectMessage("Null");
        exception.expect(errorCode(1));
        list.add(null);
    }

    @Test
    public void testAddEmptyValue() {
        MyList list = new MyList();
        exception.expect(CustomException.class);
        exception.expectMessage("Empty");
        exception.expect(errorCode(2));
        list.add(emptyValue);
    }

    private Matcher<? extends CustomException> errorCode(final int errorCode) {
        return new CustomTypeSafeMatcher<CustomException>("errorCode " + errorCode) {
            @Override
            protected boolean matchesSafely(CustomException e) {
                return e.getErrorCode() == errorCode;
            }
        };
    }
}
公共类MyListTester{
@统治
public ExpectedException exception=ExpectedException.none();
@试验
公共无效testAddNullValue(){
MyList=新建MyList();
expect(CustomException.class);
例外情况。expectMessage(“空”);
异常。expect(错误代码(1));
list.add(空);
}
@试验
public void testAddEmptyValue(){
MyList=新建MyList();
expect(CustomException.class);
例外情况。expectMessage(“空”);
异常。expect(错误代码(2));
list.add(emptyValue);
}
私人匹配可能的副本