在junit中使用@rule检查错误代码 [英] check errorcode with @rule in junit

查看:157
本文介绍了在junit中使用@rule检查错误代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I found @Rule annotation in jUnit for better handling of exception. Is there a way to check error code ?

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

Currently my code looks like (without @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());
    }
    }

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

But with use of @Rule, I am doing following :

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

        }

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

But, I want to do something like below:

       @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(匹配器<?>匹配器)方法在规则上使用自定义匹配器。

You can use a custom matcher on the rule with the expect(Matcher<?> matcher) method.

例如:

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

这篇关于在junit中使用@rule检查错误代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆