gpt4 book ai didi

Java:在 JUnit assert* 中使用记录器

转载 作者:搜寻专家 更新时间:2023-11-01 01:00:19 24 4
gpt4 key购买 nike

我想在 JUnit 中做类似下面的事情:

assertTrue(logger.error("the condition is not true"), <a boolean condition>);

所以错误消息被记录器记录下来,记录器可以是例如commons 或 log4j。

但是 Junit 断言不采用记录器参数,那么有什么方法可以实现这一点,还是我需要 try catch 断言并将错误消息记录在 catch block 中?

最佳答案

您可以使用 JUnit TestRule TestWatcher . TestRule 在测试方法之前和之后执行代码(类似于 @Before@After),但您可以访问更多信息,并且更重要的是,测试的结果。 TestWatcher定义了诸如 succeeded()failed()starting()finished() 等方法,您可以实现以获得事件通知。

以下示例简单地打印出失败的测试和失败的断言。

public class TestWatcherTest {
@Rule
public TestWatcher testWatcher = new TestWatcher() {
protected void failed(Throwable e, Description description) {
System.out.println("" + description.getDisplayName() + " failed " + e.getMessage());
super.failed(e, description);
}

};

@Test
public void test1() {
Assert.assertEquals("hello world", 3, 4);
}
}

您显然可以做您喜欢的事而不是 System.out.println()。这产生作为输出:

test1(uk.co.farwell.junit.TestWatcherTest) failed hello world expected:<3> but was:<4>

请注意,失败的断言是一个异常,因此您可以访问堆栈跟踪等。

关于Java:在 JUnit assert* 中使用记录器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10734456/

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