Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/339.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 使用JUnit4测试自定义异常的错误代码_Java_Junit_Junit4_Junit Rule - Fatal编程技术网

Java 使用JUnit4测试自定义异常的错误代码

Java 使用JUnit4测试自定义异常的错误代码,java,junit,junit4,junit-rule,Java,Junit,Junit4,Junit Rule,我想测试异常的返回代码。这是我的生产代码: class A { try { something... } catch (Exception e) { throw new MyExceptionClass(INTERNAL_ERROR_CODE, e); } } 以及相应的例外情况: class MyExceptionClass extends ... { private errorCode; public MyExceptionClass(int

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

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));
  }
这就是您在这里所需要的:

  • 您不希望期望该特定异常,因为您希望检查它的某些属性
  • 您知道您希望进入特定的捕捉块;因此,当调用没有抛出时,您就失败了
  • 您不需要任何其他检查-当该方法引发任何其他异常时,JUnit无论如何都会将其报告为错误

只要抛出
,您就可以使用hamcres匹配器检查它。expect
是重载以接收
匹配器

thrown.expect(CombinableMatcher.both(
           CoreMatchers.is(CoreMatchers.instanceOf(MyExceptionClass.class)))
           .and(Matchers.hasProperty("errorCode", CoreMatchers.is(123))));
请注意,您需要将hamcrest matcher添加到依赖项中。JUnit中包含的核心匹配是不够的

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

thrown.expect(CoreMatchers.instanceOf(MyExceptionClass.class));
thrown.expect(Matchers.hasProperty("errorCode", CoreMatchers.is(123));

另外,您不需要
(expected=MyExceptionClass.class)
声明
@Test
注释扩展Sergii的答案,您可以通过编写自定义匹配器来进一步清理这个问题

import org.hamcrest.Description;
import org.hamcrest.TypeSafeMatcher;

public class CustomMatcher extends TypeSafeMatcher<CustomException> {

    public static CustomMatcher hasCode(String item) {
        return new CustomMatcher(item);
    }

    private String foundErrorCode;
    private final String expectedErrorCode;

    private CustomMatcher(String expectedErrorCode) {
        this.expectedErrorCode = expectedErrorCode;
    }

    @Override
    protected boolean matchesSafely(final CustomException exception) {
        foundErrorCode = exception.getErrorCode();
        return foundErrorCode.equalsIgnoreCase(expectedErrorCode);
    }

    @Override
    public void describeTo(Description description) {
        description.appendValue(foundErrorCode)
                .appendText(" was not found instead of ")
                .appendValue(expectedErrorCode);
    }
}

参考资料:

我正在寻找一种很好的方法来实现它。Try/catch可以,但它意味着更多的代码行。在我看来,这是丑陋的阅读…请检查我的答案,希望这种方法将帮助你尼斯!非常感谢。
import org.junit.rules.ExpectedException;

public class MyObjTest {

    @Rule
    public ExpectedException thrown = ExpectedException.none();

    @Test
    public void someMethodThatThrowsCustomException() {
        thrown.expect(CustomException.class);
        thrown.expect(CustomMatcher.hasCode("110501"));

        MyObj obj = new MyObj();
        obj.methodThatThrowsCustomException();
    }
}