在junit中使用@rule检查错误代码

时间:2012-07-10 13:04:05

标签: java exception testing junit junit-rule

我在@Rule中找到了jUnit注释,以便更好地处理异常。 有没有办法检查错误代码?

目前我的代码看起来像(没有@Rule):

 @Test
    public void checkNullObject() {
    MyClass myClass= null;
    try {
        MyCustomClass.get(null); // it throws custom exception when null is passed
    } catch (CustomException e) { // error code is error.reason.null
        Assert.assertSame("error.reason.null", e.getInformationCode());
    }
    }

但是使用@Rule,我正在做以下事情:

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

        @Test
        public void checkNullObject() throws CustomException {
        exception.expect(CustomException .class);
        exception.expectMessage("Input object is null.");
        MyClass myClass= null;
        MyCustomClass.get(null);

        }

但是,我想做类似下面的事情:

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

        @Test
        public void checkNullObject() throws CustomException {
        exception.expect(CustomException .class);
       //currently below line is not legal. But I need to check errorcode.
        exception.errorCode("error.reason.null");
        MyClass myClass= null;
        MyCustomClass.get(null);

        }

2 个答案:

答案 0 :(得分:4)

您可以使用expect(Matcher<?> matcher)方法在规则上使用自定义匹配器。

例如:

public class ErrorCodeMatcher extends BaseMatcher<CustomException> {
  private final String expectedCode;

  public ErrorCodeMatcher(String expectedCode) {
    this.expectedCode = expectedCode;
  }

  @Override
  public boolean matches(Object item) {
    CustomException e = (CustomException)item;
    return expectedCode.equals(e.getInformationCode());
  }
}

并且在测试中:

exception.expect(new ErrorCodeMatcher("error.reason.null"));

答案 1 :(得分:1)

您还可以在ExpectedException.java source

中查看expect(Matcher<?> matcher)的用法
private Matcher<Throwable> hasMessage(final Matcher<String> matcher) {
     return new TypeSafeMatcher<Throwable>() {
      @Override
        public boolean matchesSafely(Throwable item) {
        return matcher.matches(item.getMessage());
        }
   };
}

    public void expectMessage(Matcher<String> matcher) {
         expect(hasMessage(matcher));
 }