3

我发现@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);

        }
4

2 回答 2

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"));
于 2012-07-10T13:15:01.150 回答
1

您还可以查看如何 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));
 }
于 2012-07-10T13:24:31.687 回答