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

标签 java exception testing junit 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"));

关于java - 在 junit 中使用@rule 检查错误代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11413922/

相关文章:

java - 是否可以从方法返回

java - 发生异常时显示完整的堆栈跟踪

testing - 自动化服务器运行的 Testcafe 测试随机失败

java - JSP 在开普勒 (Eclipse Standard 4.3) 中以黑白方式打开

java - java 中的格式化输出,如 ls

c# - 如何使用 C# 处理 401 错误响应?

javascript - 从作为 promise 返回的 Angular 查询参数创建测试

java - JSTL中是否需要 "c"前缀 <c :forEach>?

java - 有没有轻量级的java web服务框架或库?

Django 测试 : mock user login