gpt4 book ai didi

java - 使用 gradle 并行运行 JUnit4 测试

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:21:38 25 4
gpt4 key购买 nike

我想使用 Gradle 并行运行测试。我的实验表明 Gradle 在类级别并行运行测试。我需要它们在方法级别执行。

给定两个这样的测试类:

public class OneTest {
@Test
public void should_sleep_4_seconds() throws Exception {
System.out.println("Start 4 seconds");
Thread.sleep(4000);
System.out.println("Done 4 seconds");
}
}
public class ManyTest {

@Test
public void should_sleep_1_seconds() throws Exception {
System.out.println("Start 1 seconds");
Thread.sleep(1000);
System.out.println("Done 1 seconds");
}

@Test
public void should_sleep_2_seconds() throws Exception {
System.out.println("Start 2 seconds");
Thread.sleep(2000);
System.out.println("Done 2 seconds");
}
}

像这样的构建脚本:

plugins {
id 'java'
}

sourceCompatibility = '1.8'
targetCompatibility = '1.8'

dependencies {
testCompile 'junit:junit:4.12'
}

test {
testLogging.showStandardStreams = true
maxParallelForks = 3
}

repositories {
mavenCentral()
}

我可以得到这个结果:

./gradlew clean test

> Task :test

se.thinkcode.ManyTest > should_sleep_2_seconds STANDARD_OUT
Start 2 seconds

se.thinkcode.OneTest > should_sleep_4_seconds STANDARD_OUT
Start 4 seconds

se.thinkcode.ManyTest > should_sleep_2_seconds STANDARD_OUT
Done 2 seconds

se.thinkcode.ManyTest > should_sleep_1_seconds STANDARD_OUT
Start 1 seconds
Done 1 seconds

se.thinkcode.OneTest > should_sleep_4_seconds STANDARD_OUT
Done 4 seconds

BUILD SUCCESSFUL in 5s
3 actionable tasks: 3 executed

这告诉我存在并行性,但它只是在类级别,而不是方法级别。

有没有什么 native 方法可以让 Gradle 在一个线程中执行每个测试方法?

最佳答案

无法使用 Gradles JUnit 4 runner 并行运行除类以外的任何测试。

我无法确认这是否有效,但您可能想尝试 JUnit 5 中的 JUnit Platform + JUnit Vintage。查看 JUnit 5 starters查看如何设置。

dependencies {
def junit4Version = '4.12'
def junit5Version = '5.3.2'
implementation(enforcedPlatform("org.junit:junit-bom:${junit5Version}")) {
because 'enforce matching Platform, Jupiter, and Vintage versions'
}

// JUnit Jupiter
testImplementation('org.junit.jupiter:junit-jupiter-api')
testImplementation('org.junit.jupiter:junit-jupiter-params')
testRuntimeOnly('org.junit.jupiter:junit-jupiter-engine') {
because 'allows JUnit 5 (read Jupiter) tests to run'
}

// JUnit Vintage
testImplementation("junit:junit:${junit4Version}")
testRuntimeOnly('org.junit.vintage:junit-vintage-engine') {
because 'allows JUnit 3 and JUnit 4 tests to run'
}
}

然后您可以将 junit.jupiter.execution.parallel.enabled=true 添加到 junit-platform.properties 以启用并行执行。查看JUnit 5 User Guide - Parallel Execution .

关于java - 使用 gradle 并行运行 JUnit4 测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54436801/

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