gpt4 book ai didi

java - 并行化 + 参数化线程,每个线程的执行顺序随机

转载 作者:行者123 更新时间:2023-12-01 22:26:09 27 4
gpt4 key购买 nike

我有一个类可以与参数并行运行我的测试。但为了检查并发问题,我想以随机顺序执行测试。例如。第一个线程上的 test1 - test2 - test3 和第二个线程上的 test2 - test1 - test3 。 (我想你已经明白了)

这是我当前正在使用的代码,我已经找到了一些使用 BlockJUnit4ClassRunnerWithParameters 的示例,但将 Parameterized 更改为 BlockJUnit4ClassRunnerWithParameters 显然对我不起作用。

因此我的问题是:如何让每个线程以随机顺序执行测试?

希望大家多多指教...

public class Parallelized extends Parameterized
{

private static class ThreadPoolScheduler implements RunnerScheduler
{
private ExecutorService executor;

public ThreadPoolScheduler()
{
String threads = System.getProperty("junit.parallel.threads", "16");
int numThreads = Integer.parseInt(threads);
executor = Executors.newFixedThreadPool(numThreads);
}

@Override
public void finished()
{
executor.shutdown();
try
{
executor.awaitTermination(10, TimeUnit.MINUTES);
}
catch (InterruptedException exc)
{
throw new RuntimeException(exc);
}
}

@Override
public void schedule(Runnable childStatement)
{
executor.submit(childStatement);
}
}

public Parallelized(Class klass) throws Throwable
{
super(klass);
setScheduler(new ThreadPoolScheduler());
}
}

最佳答案

好吧,我找到了一个相当简单的解决方案:

您所需要的只是一个ParametersRunnerFactory,它创建BlockJUnit4ClassRunnerWithParameters类型的Runner。要随机化每个运行者的测试顺序,您只需覆盖 computeTestMethods() 并随机排列方法列表。

要使用您创建的 RunnerFactory,您必须在每个中的 @RunWith(Parallelized.class) 正下方添加 @Parameterized.UseParametersRunnerFactory(Parallelized.RunnerFactory.class)您想要使用随机执行顺序的类。

注意:如果不添加此注释,junit 将使用默认运行程序而不是您的自定义运行程序 -> 不会发生任何更改。

public static class RunnerFactory implements ParametersRunnerFactory {
@Override
public org.junit.runner.Runner createRunnerForTestWithParameters(TestWithParameters test) throws InitializationError {
return new CustomRunnerWithParameters(test);
}

}

public static class CustomRunnerWithParameters extends BlockJUnit4ClassRunnerWithParameters {
private final Object[] parameters;

@Override
protected List<FrameworkMethod> computeTestMethods() {
List<FrameworkMethod> tests = new ArrayList<FrameworkMethod>(super.computeTestMethods());
Collections.shuffle(tests);
return tests;
}

public CustomRunnerWithParameters(TestWithParameters test) throws InitializationError {
super(test);
parameters = test.getParameters().toArray(new Object[test.getParameters().size()]);
}

@Override
public Object createTest() throws Exception {
return getTestClass().getOnlyConstructor().newInstance(parameters);
}
}

在 Aroidans 评论后编辑:

我忘记补充一点,我在扩展参数化的自定义运行程序中使用覆盖的 getChildren 方法来打乱测试的执行顺序。但他的回答也是有效的。

    @Override
protected List<Runner> getChildren() {
ArrayList<Runner> runner = new ArrayList<>(super.getChildren());
if (NUM_THREADS > 1) {
Collections.shuffle(runner);
}
return runner;
}

关于java - 并行化 + 参数化线程,每个线程的执行顺序随机,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28746959/

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