使用JUnit 4测试自定义异常的错误代码

Gui*_*ume 8 java junit junit4 junit-rule

我想测试异常的返回码.这是我的生产代码:

class A {
  try {
    something...
  }
  catch (Exception e)
  {
    throw new MyExceptionClass(INTERNAL_ERROR_CODE, e);
  }
}
Run Code Online (Sandbox Code Playgroud)

和相应的例外:

class MyExceptionClass extends ... {
  private errorCode;

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

  public getErrorCode(){ 
    return this.errorCode;
  }
}
Run Code Online (Sandbox Code Playgroud)

我的单元测试:

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();
  }
}
Run Code Online (Sandbox Code Playgroud)

Ser*_*hyr 8

只要thrown.expect接收过载,您就可以使用 hamcres 匹配器检查它Matcher

thrown.expect(CombinableMatcher.both(
           CoreMatchers.is(CoreMatchers.instanceOf(MyExceptionClass.class)))
           .and(Matchers.hasProperty("errorCode", CoreMatchers.is(123))));
Run Code Online (Sandbox Code Playgroud)

请注意,您需要将 hamcrest 匹配器添加到您的依赖项中。包含在 JUnit 中的核心匹配是不够的。

或者,如果您不想使用 CombinableMatcher:

thrown.expect(CoreMatchers.instanceOf(MyExceptionClass.class));
thrown.expect(Matchers.hasProperty("errorCode", CoreMatchers.is(123));
Run Code Online (Sandbox Code Playgroud)

此外,您不需要(expected = MyExceptionClass.class)声明@Test注释


Gho*_*ica 7

简单:

 @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));
  }
Run Code Online (Sandbox Code Playgroud)

这就是你需要的一切:

  • 你不想期望那个特定的异常,因为你检查它的一些属性
  • 你知道你想要输入那个特定的catch块; 因此,当呼叫没有抛出时你就会失败
  • 你不需要任何其他检查 - 当方法抛出任何其他异常时,JUnit会将其报告为错误