Spring:@BootstrapWith 用于 ApplicationContext

Spring: @BootstrapWith for ApplicationContext

目前我将@BootstrapWith 注释与自定义class 结合使用,这只是设置一些在测试中使用的系统属性。但是(据我所知)每次 TestContextManager 使用它实例化测试和 TestContext 时都会设置这些属性:

@BootstrapWith is a class-level annotation that is used to configure how the Spring TestContext Framework is bootstrapped

spring.io

有什么方法可以在 ApplicationContext 启动之前设置一次属性吗?

编辑:

由于需要 @RunWith(Parameterized.class) 的参数化测试,我无法使用 @RunWith(SpringJUnit4ClassRunner.class)。我使用 SpringClassRuleSpringMethodRule 代替

此外,我运行不仅进行了参数化测试,还进行了普通测试。因此我不能简单地扩展 Parameterized 运行ner

我认为在 ApplicationContext 设置之前设置一些属性的最基本方法是编写自定义运行器,例如:

public class MyRunner extends SpringJUnit4ClassRunner {

    public MyRunner(Class<?> clazz) throws InitializationError {
        super(clazz);
        System.setProperty("sample.property", "hello world!");
    }

}

然后你就可以用它来代替你现在的跑步者了。

@RunWith(MyRunner.class)
@SpringBootTest
//....

如果您当前的运行器似乎被声明为最终的,您可以使用聚合(但我还没有测试过)而不是继承。

Here 你可以找到一个示例 Gist,其中使用了这个跑步者并且 属性 得到了成功解决。

更新

如果您不想使用自定义 Runner(尽管您可以让多个运行器为每种情况设置属性 - 带参数、不带参数等等)。您可以使用适用于静态 fields/methods 的 @ClassRule - 请看下面的示例:

@ClassRule
public static ExternalResource setProperties() {
    return new ExternalResource() {
        @Override
        public Statement apply(Statement base, Description description) {
            System.setProperty("sample.property", "hello world!");
            return super.apply(base, description);
        }
    };
}

这个 static 方法要放在你的测试中 class.

我发现这可以通过扩展 AnnotationConfigContextLoader(或任何其他 ContextLoader)和覆盖 prepareContext() 方法来实现:

@Override
protected void prepareContext(ConfigurableApplicationContext context, MergedContextConfiguration mergedConfig) {
    // set properties here
    super.prepareContext(context, mergedConfig);
}

自定义加载器应该在测试实例的 @ContextConfiguration 注释中指定

如果您只是想添加 Properties 作为 spring 应用程序上下文引导的一部分,您可以在 Junit 测试的顶部使用注释 @TestPropertySource class 像这样...

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes={SpringConfig.class,SpringConfigForTests.class})
@TestPropertySource(properties = "runDate=20180110")
public class AcceptanceTests {
...

我使用这种技术来加载我的产品 SpringConfig class(加载属性文件),然后覆盖一些专门用于在 SpringConfigForTests 中进行测试的 bean(并可能加载测试特定属性文件),然后添加另一个名为 runDate.

的 run-time 属性

我正在使用 Spring 4.2.5.RELEASE 并且似乎自 4.1

以来就包含了此注释