check errorcode with @rule in junit
Asked Answered
V

2

3

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);

        }
Vivienviviene answered 10/7, 2012 at 13:4 Comment(0)
W
4

You can use a custom matcher on the rule with the expect(Matcher<?> matcher) method.

For example:

public class ErrorCodeMatcher extends BaseMatcher<CustomException> {
  private final String expectedCode;

  public ErrorCodeMatcher(String expectedCode) {
    this.expectedCode = expectedCode;
  }

  @Override
  public boolean matches(Object item) {
    CustomException e = (CustomException)item;
    return expectedCode.equals(e.getInformationCode());
  }
}

and in the test:

exception.expect(new ErrorCodeMatcher("error.reason.null"));
Watchtower answered 10/7, 2012 at 13:15 Comment(4)
Thanks a lot. I was looking something similar to this. I hope this will work. :)Vivienviviene
One doubt : is BaseMatcher is from org.hamcrest ?Vivienviviene
Yes, and it should be included in jUnit.Watchtower
Yeah , it is. But I had never hear about that class. So was in doubt.Vivienviviene
B
1

You can also see how the expect(Matcher<?> matcher) has been used within ExpectedException.java source

private Matcher<Throwable> hasMessage(final Matcher<String> matcher) {
     return new TypeSafeMatcher<Throwable>() {
      @Override
        public boolean matchesSafely(Throwable item) {
        return matcher.matches(item.getMessage());
        }
   };
}

    public void expectMessage(Matcher<String> matcher) {
         expect(hasMessage(matcher));
 }
Buxtehude answered 10/7, 2012 at 13:24 Comment(1)
+1 TypeSafeMatcher is a better alternative than the BaseMatcher in my example.Watchtower

© 2022 - 2024 — McMap. All rights reserved.