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

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

本文介绍了使用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);
  }
}

以及相应的例外情况:

class MyExceptionClass extends ... {
  private errorCode;

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

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

我的单元测试:

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


推荐答案

简单:

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

这就是你需要的全部:


  • 你不想期待那个特定的例外,因为你想要来检查它的一些属性

  • 您知道想要输入那个特定的catch块;因此你只是在调用没有抛出时失败

  • 你不需要任何其他检查 - 当方法抛出任何其他异常时,JUnit将报告为错误

  • you don't want to expect that specific exception, as you want to check some properties of it
  • you know that you want to enter that specific catch block; thus you simply fail when the call doesn't throw
  • you don't need any other checking - when the method throws any other exception, JUnit will report that as error anyway

这篇关于使用JUnit 4测试自定义异常的错误代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 01:32