Would using a @TestPropertySource, that creates a new Bean in the application, result in the creation of a new Context or would it reuse an already created context?
Spring Test manages the context within a context cache and uses a uniquely identifiable key for each context (think of a simple Java Map
).
The parameters that are used to create this key are the following:
- locations (from @ContextConfiguration)
- classes (from @ContextConfiguration)
- contextInitializerClasses (from @ContextConfiguration)
- contextCustomizers (from ContextCustomizerFactory) – this includes @DynamicPropertySource methods as well as various features from Spring Boot’s testing support such as @MockBean and @SpyBean.
- contextLoader (from @ContextConfiguration)
- parent (from @ContextHierarchy)
- activeProfiles (from @ActiveProfiles)
- propertySourceLocations (from @TestPropertySource)
- propertySourceProperties (from @TestPropertySource)
- resourceBasePath (from @WebAppConfiguration)
So yes, if you use @TestPropertySource
with different configurations for multiple tests, there will be multiple contexts created for you. If all your test have the same @TestPropertySource
annotation, then they can share the context, e.g.:
@SpringBootTest
@TestPropertySource(locations = "classpath:application.properties")
public class ContextOneIT {
@Test
public void testMe() {
System.out.println("Works");
}
}
can share the same context with
@SpringBootTest
@TestPropertySource(locations = "classpath:application.properties")
public class ContextTwoIT {
@Test
public void testMe() {
System.out.println("Works");
}
}
If you are curious and want to understand what Spring Test is doing, you can enable the following log level to get context related logs:
logging.level.org.springframework.test.context.cache=DEBUG