如何以随机数运行Junit测试

m3eecexj  于 9个月前  发布在  其他
关注(0)|答案(2)|浏览(178)

我有一个测试套件类TestSuiteTestA

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

个字符
如何随机运行所有3个测试中的2个?搜索,看起来我需要创建一个自定义跑步机。任何例子?谢谢!
更新:我们只需要一个定制的亚军,

public class TestRunner extends BlockJUnit4ClassRunner {

    private static final int MAX_TESTS_TO_RUN = 2;
    public TestRunner(Class<?> klass) throws InitializationError {
        super(klass);
    }

    @Override
    protected List<FrameworkMethod> computeTestMethods() {
        List<FrameworkMethod> methods = super.computeTestMethods();

        List<FrameworkMethod> shuffledMethods = new ArrayList<>(methods);
        Collections.shuffle(shuffledMethods);

        return new ArrayList<>(shuffledMethods.subList(0, Math.min(methods.size(), MAX_TESTS_TO_RUN)));
    }
}


另外,如果您的测试类已经有了一个运行器,那么您需要创建一个规则并将规则添加到各个测试类

puruo6ea

puruo6ea1#

使用Junit,这是不可能开箱即用的。你必须编写一个自定义的org.junit.runner.Runner实现来实现这一点。

然而,我认为你问的是an XY problem。你应该问问自己为什么这样做是必要的。例如Junit5提供了大量的方法to run tests conditionally,这取决于Java版本,env变量,特定的操作系统等。所以你可以决定在Junit中是静态运行测试还是dynamically(取决于运行时条件)。这很可能是你想要的。

hgqdbh6s

hgqdbh6s2#

你将需要使对象静态化,然后在它说导入并运行测试号的地方替换它并调用对象。

for(int i = 0; i < 2; i++) {
        //this switch makes checks for a random number between 1 and 3
        switch((int)Math.floor(Math.random()*(3-1+1)+1)) {
            case 1:
                // import and have test 1 run here
                break;
            case 2:
                // import and have test 2 run here
                break;
            case 3:
                // import and have test 3 run here
                break;
        }
    }

字符串

相关问题