javajunitjunit4junit-rule

Test the error code of a custom exception with JUnit 4


I would like to test the return code of an exception. Here is my production code:

class A {
  try {
    something...
  }
  catch (Exception e)
  {
    throw new MyExceptionClass(INTERNAL_ERROR_CODE, e);
  }
}

And the corresponding exception:

class MyExceptionClass extends ... {
  private errorCode;

  public MyExceptionClass(int errorCode){
    this.errorCode = errorCode;
  }

  public getErrorCode(){ 
    return this.errorCode;
  }
}

My unit test:

public class AUnitTests{
  @Rule
  public ExpectedException thrown= ExpectedException.none();

  @Test (expected = MyExceptionClass.class, 
  public void whenRunningSomething_shouldThrowMyExceptionWithInternalErrorCode() throws Exception {
      thrown.expect(MyExceptionClass.class);
      ??? expected return code INTERNAL_ERROR_CODE ???

      something();
  }
}

Solution

  • Simple:

     @Test 
     public void whenSerialNumberIsEmpty_shouldThrowSerialNumberInvalid() throws Exception {
      try{
         whenRunningSomething_shouldThrowMyExceptionWithInternalErrorCode();     
         fail("should have thrown");
      }
      catch (MyExceptionClass e){
         assertThat(e.getCode(), is(MyExceptionClass.INTERNAL_ERROR_CODE));
      }
    

    That is all you need here: