When writing Spring tests using both @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK) and @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT), I am seeing the tests reuse the same application context.
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
class DemoApplicationTestsDefinedPort {
@Test
void testDefinedPort() {}
}
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK)
class DemoApplicationTestsMock {
@Test
void mockTest() {}
}
With logging.level.org.springframework.test.context.cache=DEBUG, the relevant log output:
...
Storing ApplicationContext [912966811] in cache under key [[WebMergedContextConfiguration@74287ea3 testClass = DemoApplicationTestsDefinedPort, ...]]
...
Retrieved ApplicationContext [912966811] from cache with key [[WebMergedContextConfiguration@4dad8ec0 testClass = DemoApplicationTestsMock, ...]]
...
testDefinedPort expects a real server to be started on the port specified by server.port. However, depending on the order of execution testDefinedPort may instead reuse the application context created by mockTest. The webEnvironment should form part of the cache key.