我发现@Rule
注释jUnit
可以更好地处理异常。有没有办法检查错误代码?
目前我的代码看起来像(没有@Rule):
@Test
public void checkNullObject() {
MyClass myClass= null;
try {
MyCustomClass.get(null); // it throws custom exception when null is passed
} catch (CustomException e) { // error code is error.reason.null
Assert.assertSame("error.reason.null", e.getInformationCode());
}
}
但是随着使用@Rule
,我正在做以下事情:
@Rule
public ExpectedException exception = ExpectedException.none();
@Test
public void checkNullObject() throws CustomException {
exception.expect(CustomException .class);
exception.expectMessage("Input object is null.");
MyClass myClass= null;
MyCustomClass.get(null);
}
但是,我想做如下的事情:
@Rule
public ExpectedException exception = ExpectedException.none();
@Test
public void checkNullObject() throws CustomException {
exception.expect(CustomException .class);
//currently below line is not legal. But I need to check errorcode.
exception.errorCode("error.reason.null");
MyClass myClass= null;
MyCustomClass.get(null);
}