I found @Rule
annotation in jUnit
for better handling of exception.
Is there a way to check error code ?
Currently my code looks like (without @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());
}
}
But with use of @Rule
, I am doing following :
@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);
}
But, I want to do something like below:
@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);
}
You can use a custom matcher on the rule with the
expect(Matcher<?> matcher)
method.For example:
and in the test:
You can also see how the
expect(Matcher<?> matcher)
has been used within ExpectedException.java source