gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 07:53:15 29 4
gpt4 key购买 nike

我在 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/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com