我创建了一个带有自定义消息和错误代码的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。 如何在单元测试中捕获和测试错误代码? 我做过类似的事情:
public class MyListTester { private Class exceptionType = CustomException.class;
@Test
public void testAddNonNullValue() {
exception.expect(exceptionType);
exception.expectMessage("Null");
list.add(null);
}
但我没有访问错误代码
答案 0 :(得分:0)
诀窍是使用expect
规则的ExpectedException
方法,该方法以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;
}
};
}
}