为了更好地处理异常,我在jUnit
中发现了@Rule
注释。 有没有办法检查错误代码?在junit中检查@rule的错误代码
目前我的代码看起来像(不@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);
}
非常感谢使用。我正在寻找类似的东西。我希望这会起作用。 :) – 2012-07-10 13:20:10
有一个疑问:BaseMatcher是来自org.hamcrest吗? – 2012-07-10 13:28:53
是的,它应该包含在jUnit中。 – casablanca 2012-07-10 13:31:27