'How to run JUnit5 Spring runner tests in parallel?
I am unable to run JUnit5 tests concurrently when they involve using SpringExtension. When I run sequentially, there are no issues. When I run concurrently, only one test in the class is able to successfully access any injected or autowired fields. Any other tests will throw a NullPointerException when attempting to reference injected or autowired fields. Since JUnit5 parallelization is using ForkJoinPool under the hood, I was under the impression one Spring test context would be created and threads could safely use a cached context. Am I missing something in configuring my testing suite?
Here's a simplified example where the problem can be observed:
DummyTest:
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.api.parallel.Execution;
import org.junit.jupiter.api.parallel.ExecutionMode;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import javax.inject.Inject;
@Execution(ExecutionMode.CONCURRENT)
@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = {DummyTestConfig.class})
public class DummyTest {
@Inject
private StringBuilder stringBuilder;
@Test
public void testA() {
Assertions.assertEquals(stringBuilder.toString(), "test");
}
@Test
public void testB() {
Assertions.assertEquals(stringBuilder.toString(), "test");
}
}
DummyTestConfig:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class DummyTestConfig {
public DummyTestConfig() {}
@Bean
public StringBuilder stringBuilder() {
return new StringBuilder("test");
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
