使用带 SpringBootTest 注释测试的 TestPropertySource 会导致创建新的 Spring 上下文吗?

Would the usage of a TestPropertySource with a SpringBootTest annotated test result in the creation of a new Spring Context?

使用在应用程序中创建新 Bean 的 @TestPropertySource 会导致创建新上下文还是会重用已创建的上下文?

Spring 测试在上下文缓存中管理上下文,并为每个上下文使用唯一可识别的键(想想一个简单的 Java Map)。

用于创建此密钥的参数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)

所以是的,如果您对多个测试使用具有不同配置的 @TestPropertySource,将会为您创建多个上下文。如果您所有的测试都有相同的 @TestPropertySource 注释,那么它们可以共享上下文,例如:

@SpringBootTest
@TestPropertySource(locations = "classpath:application.properties")
public class ContextOneIT {

  @Test
  public void testMe() {
    System.out.println("Works");
  }
}

可以与

共享相同的上下文
@SpringBootTest
@TestPropertySource(locations = "classpath:application.properties")
public class ContextTwoIT {

  @Test
  public void testMe() {
    System.out.println("Works");
  }

}

如果你很好奇并想了解Spring测试在做什么,你可以启用以下日志级别来获取上下文相关的日志:

logging.level.org.springframework.test.context.cache=DEBUG