0

I have created a CustomException with a custom message and an error code.

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

When I add a null value in a list throw CustomException with the message "Null" and error Code 1. When I add an empty value the message for exception is "Empty" and error Code 2. How I can capture and test error code in unit test? I have done something like that:

public class MyListTester{ private Class exceptionType = CustomException.class;

 @Test
 public void testAddNonNullValue() {
      exception.expect(exceptionType);
      exception.expectMessage("Null");
      list.add(null);
}

but I don't have acces to the error code

Matthew Farwell
  • 60,889
  • 18
  • 128
  • 171
  • possible duplicate of [How can I use JUnit's ExpectedException to check the state that's only on a child Exception?](http://stackoverflow.com/questions/22491137/how-can-i-use-junits-expectedexception-to-check-the-state-thats-only-on-a-chil) – Joe May 14 '14 at 12:54

1 Answers1

0

The trick is to use the expect method of the ExpectedException rule which takes a Matcher as parameter and to write a custom matcher for verifying the error code. Here is a complete example:

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;
            }
        };
    }
}
Michael Tamm
  • 883
  • 8
  • 13