gpt4 book ai didi

java - 扩展 Junit ParentRunner 类以过滤测试方法

转载 作者:搜寻专家 更新时间:2023-11-01 02:29:59 25 4
gpt4 key购买 nike

我需要读取一个文本文件,其中包含所有测试方法列表的是/否值,并仅为测试用例类选择"is"标记的测试方法,并在 Junit 中执行。

所以我编写了一个脚本来读取文件并将其分组到 ma​​p< TestCaseName,ArrayList_ofEnabledTestMethods > 中。要运行它,我发现一个选项是使用 Assume.assumeTrue()

但我想尝试一些其他方式...而不是在每个测试方法之前编写额外的行,所以我尝试编写一个自定义运行程序(ABCSuite 扩展 ParentRunner ) 并计划在我的 TestSuite 文件中使用它,如下所示:

import org.junit.runner.RunWith;
import org.junit.runners.Suite;

@RunWith(ABCSuite.class)
@Suite.SuiteClasses({TestCalc.class})
public class BatTest{

}

此处 TestCalc.class 包含所有测试方法,其中一些在前面提到的文本文件中标记为"is"。

请告诉我如何使用扩展 ParentRunner 类/Junit 库 来实现这一点。如果有任何好的教程或之前解决此问题的任何链接,请..分享

最佳答案

您可以通过扩展 BlockJUnit4ClassRunner 来做到这一点:

public class FilterRunner extends BlockJUnit4ClassRunner {
private List<String> testsToRun = Arrays.asList(new String[] { "test1" });

public FilterRunner(Class<?> klass) throws InitializationError {
super(klass);
}

@Override
protected void runChild(final FrameworkMethod method, RunNotifier notifier) {
Description description= describeChild(method);
if (method.getAnnotation(Ignore.class) != null || !testsToRun.contains(method.getName())) {
notifier.fireTestIgnored(description);
} else {
runLeaf(methodBlock(method), description, notifier);
}
}
}

你可以随意填写testsToRun。以上将把其他测试标记为已忽略。你这样使用:

@RunWith(Suite.class)
@SuiteClasses({Class1Test.class})
public class TestSuite {
}

@RunWith(FilterRunner.class)
public class Class1Test {
@Test
public void test1() {
System.out.println("test1");
}

@Test
public void test2() {
System.out.println("test2");
}
}

这会产生以下输出:

test1

如果您不想将@FilterRunner 添加到每个测试类,请查看我对如何定义 JUnit method rule in a suite? 的回答.

关于java - 扩展 Junit ParentRunner 类以过滤测试方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11885862/

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