JUnit5用户手册~并行执行

时间:2021-03-01 01:22:51

两种运行模式

SAME_THREAD: 默认的,测试方法在同一个线程
CONCURRENT: 并行执行,除非有资源锁

junit-platform.properties 配置参数

配置所有测试方法都并行

junit.jupiter.execution.parallel.enabled = true
junit.jupiter.execution.parallel.mode.default = concurrent
@Execution(CONCURRENT) 指定类或方法并行

配置top-level类并行,测试方法同一线程执行

junit.jupiter.execution.parallel.enabled = true
junit.jupiter.execution.parallel.mode.default = same_thread
junit.jupiter.execution.parallel.mode.classes.default = concurrent

配置top-level类串行,测试方法并行

junit.jupiter.execution.parallel.enabled = true
junit.jupiter.execution.parallel.mode.default = concurrent
junit.jupiter.execution.parallel.mode.classes.default = same_thread

JUnit5用户手册~并行执行

 相关参数

属性

描述

支持的值 默认值
junit.jupiter.execution.parallel.enabled
是否允许并行

true

false

false
junit.jupiter.execution.parallel.mode.default
test tree的默认执行模式
concurrent
same_thread
same_thread
junit.jupiter.execution.parallel.mode.classes.default
top-level类的默认执行模式
concurrent
same_thread
same_thread
junit.jupiter.execution.parallel.config.strategy
默认线程和最大线程数的策略
dynamic
fixed
custom
dynamic
junit.jupiter.execution.parallel.config.dyna mic.factor

 dynamic配置的系数

数值 1
junit.jupiter.execution.parallel.config.fixed.parallelism
fixed配置的线程数 数值 无默认
junit.jupiter.execution.parallel.config.custom.class
custom配置的策略类 无默认

2、同步

@Execution(CONCURRENT)
class SharedResourcesDemo {
	private Properties backup;
	
	@BeforeEach
	void backup() {
		backup = new Properties();
		backup.putAll(System.getProperties());
	}
	
	@AfterEach
	void restore() {
		System.setProperties(backup);
	}
	
	@Test
	@ResourceLock(value = SYSTEM_PROPERTIES, mode = READ)
	void customPropertyIsNotSetByDefault() {
		assertNull(System.getProperty("my.prop"));
	}
	
	@Test
	@ResourceLock(value = SYSTEM_PROPERTIES, mode = READ_WRITE)
	void canSetCustomPropertyToApple() {
		System.setProperty("my.prop", "apple");
		assertEquals("apple", System.getProperty("my.prop"));
	}
	
	@Test
	@ResourceLock(value = SYSTEM_PROPERTIES, mode = READ_WRITE)
	void canSetCustomPropertyToBanana() {
		System.setProperty("my.prop", "banana");
		assertEquals("banana", System.getProperty("my.prop"));
	}
}