我们的一个类使用系统属性来加载配置文件 . 在特定的测试用例中,我们将此属性设置为无效值,以在这种情况下检查被测试类(CUT)的行为 .

在各种集成测试中也可以使用相同的类 . 由于我们正在使用JUnit Jupiter的parallel test execution capabilities,我们正在目睹那些在引擎盖下使用CUT的集成测试中的竞争条件 . 它们失败,因为系统属性有时仍然无效 .

并行性本身通过Maven Surefire插件进行全局配置:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.22.0</version>
    <configuration>
        <properties>
            <configurationParameters>
                junit.jupiter.execution.parallel.enabled=true
                junit.jupiter.execution.parallel.config.dynamic.factor=1
            </configurationParameters>
        </properties>
    </configuration>
</plugin>

因此,所有测试都默认并行运行 . CUT看起来像这样:

class AttributesProviderTest {

    @Test
    @ResourceLock( value = SYSTEM_PROPERTIES, mode = READ_WRITE )
    void invalid_attributes_file_should_yield_UncheckedIOException() throws Exception {
        final Properties backup = new Properties();
        backup.putAll( System.getProperties() );

        final String attributesFile = "foo";
        System.setProperty( AttributesProvider.ATTRIBUTES_FILE_PROPERTY, attributesFile );

        assertThatThrownBy( AttributesProvider::getTestInstance )
                .isExactlyInstanceOf( UncheckedIOException.class )
                .hasMessage( "Cannot read attributes file '" + attributesFile + "'." );

        System.setProperties( backup );
    }

    // Some other tests...

}

可以看出,我们正在尝试synchronize系统属性访问 . 但是,如果我已经正确理解,这只适用于其他 @ResourceLock 注释测试,并且通常不会神奇地同步系统属性访问?

有没有办法解决竞争条件(没有注释所有其他测试)?一些想法:

  • 确保CUT在开始时顺序执行(或其他某种同步) .

  • 重构CUT并直接使用参数调用相应的文件读取方法 .

  • 扔掉测试用例 .