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



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

目前我的代码看起来像(没有@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);
        }

您可以使用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"));

您还可以看到expect(Matcher<?> matcher)是如何在ExpectedException.java源中使用的

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

相关内容

  • 没有找到相关文章

最新更新