代码之家  ›  专栏  ›  技术社区  ›  Javasick Kumar Vivek Mitra

Spring启动:@TestPropertySource未从导入的配置加载

  •  2
  • Javasick Kumar Vivek Mitra  · 技术社区  · 6 年前

    WebMvcTest 我正在试着加载 test.properties 应用 @TestPropertySource 注释以重写测试类中的某些属性。 如果我把它放在测试类上,它就可以正常工作了:

    @RunWith(SpringRunner.class)
    @WebMvcTest
    @TestPropertySource("classpath:test.properties")
    public class ControllerTest {
        ...
    }
    

    @RunWith(SpringRunner.class)
    @WebMvcTest
    @Import(ControllersConfiguration.class)
    public class ControllerTest {
        ...
    }
    

    ControllersConfiguration 课程为:

    @TestConfiguration
    @TestPropertySource("classpath:test.properties")
    public class ControllersConfiguration {
        ...
    }
    

    附笔。 @PropertySource application.properties

    UPD:请澄清-尝试在此处通过所有测试: https://github.com/Javasick/WeirdTestPropertySource

    2 回复  |  直到 5 年前
        1
  •  3
  •   codeformars    6 年前

    我昨天调查了一下,发现Spring正在寻找这个 @TestPropertySource

    • 源测试类
    • 接口,如果测试类实现了它们
    • 该测试类的超激光
    • 继承的注释

    AbstractTestContextBootstrapper.class 对此负责的机构:

    MergedTestPropertySources mergedTestPropertySources =
            TestPropertySourceUtils.buildMergedTestPropertySources(testClass);
    MergedContextConfiguration mergedConfig = new MergedContextConfiguration(testClass,
            StringUtils.toStringArray(locations),
            ClassUtils.toClassArray(classes),
            ApplicationContextInitializerUtils.resolveInitializerClasses(configAttributesList),
            ActiveProfilesUtils.resolveActiveProfiles(testClass),
            mergedTestPropertySources.getLocations(),
            mergedTestPropertySources.getProperties(),
            contextCustomizers, contextLoader, cacheAwareContextLoaderDelegate, parentConfig);
    

    方法 TestPropertySourceUtils.buildMergedTestPropertySources(testClass)

    所以,如果您想将这个注释外部化,您需要创建一个超类,并将这个注释和 @Import 或者创建带有此注释的接口,或者创建将两个注释组合在一起的自己的注释 @进口 把它放在你的测试课上。

        2
  •  -1
  •   mrkernelpanic    6 年前

    来自JavaDocs:

    如果

    每个SmartContextLoader都是 提供对@TestPropertySource的自动支持,包括 Spring TestContext提供的每个SmartContextLoader 框架

    通常,@TestPropertySource将与 @上下文配置。

    @ContextConfiguration