目前,我将@BootstrapWith注释与自定义类结合使用,这只是设置测试中使用的一些系统属性。但是(据我理解),每次TestContextManager实例化测试和使用它进行TestContext时,都会设置这些属性:
@BootstrapWith是一个类级注释,用于配置Spring TestContext框架的引导方式
spring.io
在ApplicationContext启动之前,是否有任何方法设置一次属性?
编辑:
由于参数化测试需要@RunWith(SpringJUnit4ClassRunner.class),所以我不能使用@RunWith(Parameterized.class)。我用SpringClassRule和SpringMethodRule代替
此外,我不仅运行参数化测试,还运行普通测试。因此,我不能简单地扩展Parameterized运行程序。
发布于 2016-12-06 08:48:23
我认为在ApplicationContext设置之前设置某些属性的最基本方法是编写自定义运行程序,如下所示:
public class MyRunner extends SpringJUnit4ClassRunner {
public MyRunner(Class<?> clazz) throws InitializationError {
super(clazz);
System.setProperty("sample.property", "hello world!");
}
}然后你可以用它代替你现在的跑步者。
@RunWith(MyRunner.class)
@SpringBootTest
//....如果您的当前运行程序似乎被声明为最终,您可以使用聚合(但我还没有测试)来代替继承。
这里,您可以找到一个示例Gist,其中使用了该运行程序并成功地解析了属性。
更新
如果您不想使用自定义Runner (尽管您可以为每种情况设置几个运行程序的属性-有参数,没有参数,等等)。您可以使用在静态字段/方法上工作的@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);
}
};
}这个静态方法将放置在您的测试类中。
发布于 2018-03-26 16:44:01
如果您只想添加Properties作为spring应用程序上下文引导的一部分,您可以在Junit测试类的顶部使用注释@TestPropertySource,如下所示.
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes={SpringConfig.class,SpringConfigForTests.class})
@TestPropertySource(properties = "runDate=20180110")
public class AcceptanceTests {
...我使用这种技术加载我的产品SpringConfig类(它加载属性文件),然后为SpringConfigForTests中的测试专门覆盖一些bean(并可能加载特定于测试的属性文件),然后添加另一个名为runDate的运行时属性。
我使用的是Spring4.2.5。included,看起来这个注释是从4.1开始包含的。
发布于 2016-12-06 09:55:05
我发现,通过扩展AnnotationConfigContextLoader (或任何其他ContextLoader)并覆盖prepareContext()方法,这是可能的:
@Override
protected void prepareContext(ConfigurableApplicationContext context, MergedContextConfiguration mergedConfig) {
// set properties here
super.prepareContext(context, mergedConfig);
}应该在测试实例上的@ContextConfiguration注释中指定
https://stackoverflow.com/questions/40990811
复制相似问题