gpt4 book ai didi

java - 在 JUnit 中打印测试结果

转载 作者:行者123 更新时间:2023-12-01 16:47:52 24 4
gpt4 key购买 nike

目前我正在使测试用例重复 2 次,那么如何将结果打印为 2 个单独的结果。

我尝试使用内置函数来创建文本,但是,它现在显示“成功”或“失败”。

目前我有这个代码:

public class UnitTestRunner {
static JUnitCore junitCore;
static Class<?> testClasses;

public static void main(String[] args) {
System.out.println("Running Junit Test Suite.");
Result result = JUnitCore.runClasses(TestSuite.class);
for (Failure failure : result.getFailures()) {
System.out.println(failure.toString());
}
System.out.println("Successful: " + result.wasSuccessful() +
" ran " + result.getRunCount() + " tests");
}
}

这段代码工作正常,但我不知道如何将其实现到 JUnit 中。

有人可以帮忙展示如何将此代码实现到 JUnit 测试用例中吗?

最佳答案

这个答案会有点长。对于自定义输出,您必须添加 RunListener您可以使用以下示例实现来实现相同目的。

public class UnitTestRunner {
static JUnitCore junitCore;
static Class<?> testClasses;

public static void main(String[] args) {
System.out.println("Running Junit Test Suite.");
junitCore = new JUnitCore();
junitCore.addListener(new CustomExecutionListener());

Result result = junitCore.run(TestSuite.class);
for (Failure failure : result.getFailures()) {
System.out.println(failure.toString());
}
System.out.println("Successful: " + result.wasSuccessful() + " ran " + result.getRunCount() + " tests");
}
}

RunListener 的实现如下

import org.junit.runner.Description;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
import org.junit.runner.notification.RunListener;

public class CustomExecutionListener extends RunListener {

public void testRunStarted(Description description) throws Exception {
System.out.println("Number of tests to execute: " + description.testCount());
}

public void testRunFinished(Result result) throws Exception {
System.out.println("Number of tests executed: " + result.getRunCount());
}

public void testStarted(Description description) throws Exception {
System.out.println("Starting: " + description.getMethodName());
}

public void testFinished(Description description) throws Exception {
System.out.println("Finished: " + description.getMethodName());
}

public void testFailure(Failure failure) throws Exception {
System.out.println("Failed: " + failure.getDescription().getMethodName());
}

public void testAssumptionFailure(Failure failure) {
System.out.println("Failed: " + failure.getDescription().getMethodName());
}

public void testIgnored(Description description) throws Exception {
System.out.println("Ignored: " + description.getMethodName());
}
}

通过覆盖 RunListener 中的方法,您可以格式化输出。

关于java - 在 JUnit 中打印测试结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46536753/

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