spring-projects / spring-projects/spring-framework
Allow `@DynamicPropertySource` on non-static methods
Nobody has claimed this yet.
- Dominant language
- Java
- Stars
- 60.2k
- Forks
- 38.8k
- Avg merge
- 5d 2h
- Merged PRs (30d)
- 27
Description
While @DynamicPropertySource is great, it would be even better if it could be executed on each @Test method instead only one time at start of the test class.
For example: okhttp MockWebServer starts on a free random port. But each test needs its own MockWebServer as otherwise the state is preserved between test runs.
@SpringBootTest
public class MockTest implements BeforeEachCallback {
private MockWebServer mockServer;
//requires a fresh instance for each @Test method
@Override
public void beforeEach(ExtensionContext extensionContext) {
mockServer = new MockWebServer();
}
//this is not possible as mockServer is not static!
@DynamicPropertySource
static void changePort(DynamicPropertyRegistry registry) {
registry.add("my.app.base.url", () -> "http://localhost:" + mockServer.getPort());
}
}
If I'd make the MockWebServer a static field, that won't work if multiple @Test classes make use of the mock. Eg assertEquals(1, mockServer.getRequestCount()); would only be valid for the first test method, as mockwebserver preserves the state then.
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by tracing how @DynamicPropertySource is discovered and executed relative to @Test methods and BeforeEachCallback. Done means non-static property-source methods can provide per-test values for fresh instances while preserving the existing static, class-level behavior.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- java, spring
- Domain
- testing
- Issue type
- Feature
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 30/100