gpt4 book ai didi

java - 将自定义消息添加到 JUnit4 样式异常测试

转载 作者:行者123 更新时间:2023-11-29 08:16:41 28 4
gpt4 key购买 nike

我有以下测试:

@Test(expected=ArithmeticException.class) 
public void divideByZero() {
int n = 2 / 1;
}

如图所示here .

我想添加一条消息,如果此测试失败,将打印该消息。

例如,如果我正在进行断言测试,我会执行以下操作来添加一条消息:

@Test public void assertFail(){
Assert.fail("This is the error message I want printed.");
Assert.assertEquals(true, false);
}

第二个例子应该打印出“This is the error message I want printed.”。如何设置第一个示例消息文本?

最佳答案

也许 @Rule 注释应该有所帮助。在你的单元测试类中添加这样的东西:

import org.junit.Rule;
import org.junit.rules.MethodRule;
import org.junit.runners.model.Statement;
import org.junit.runners.model.FrameworkMethod;
import org.junit.internal.runners.model.MultipleFailureException;
...
@Rule
public MethodRule failureHandler = new MethodRule()
{
@Override
public Statement apply(final Statement base, FrameworkMethod method, Object target)
{
return new Statement()
{
@Override
public void evaluate() throws Throwable
{
List<Throwable> listErrors = new ArrayList<Throwable>();
try
{
// Let's execute whatever test runner likes to do
base.evaluate();
}
catch (Throwable testException)
{
// Your test has failed. Store the test case exception
listErrors.add(testException);
// Now do whatever you need, like adding your message,
// capture a screenshot, etc.,
// but make sure no exception gets out of there -
// catch it and add to listErrors
}
if (listErrors.isEmpty())
{
return;
}
if (listErrors.size() == 1)
{
throw listErrors.get(0);
}
throw new MultipleFailureException(listErrors);
}
};
}
};

与其在 listErrors 中收集所有异常,不如考虑将 testException 与您的异常和附加消息一起包装起来,然后将其抛出。

关于java - 将自定义消息添加到 JUnit4 样式异常测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4326896/

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