2016-12-06 286 views
1

目前我使用@BootstrapWith注释与自定义类一起使用,它只是简单地设置了一些在测试中使用的系统属性。但是(据我所知)这些属性被每个实例TestContextManager来测试和TestContext都会用它时设置:Spring:@BootstrapWith用于ApplicationContext

@BootstrapWith是用于配置 了Spring TestContext框架是怎样的一类级别注解自举

spring.io

有没有什么办法的ApplicationContext开始前一次设置属性?

编辑:

我不能用@RunWith(SpringJUnit4ClassRunner.class)由于参数的测试,这需要@RunWith(Parameterized.class)。我使用SpringClassRuleSpringMethodRule而不是

此外,我运行不仅参数化测试,但也运行普通测试。因此,我不能简单地延长Parameterized亚军

+0

你的意思' System.getProperties()'? –

+0

@MaciejDobrowolski启动ApplicationContext之前的System.setProperty() – Anton

+0

您是否必须全局设置属性,还是每个测试套件的属性都不相同? –

回答

1

我认为之前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(尽管你可以有几个选手的每一种情况下设置属性 - 使用参数,无参数,等等)。您可以使用@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); 
     } 
    }; 
} 

静态方法是放置在您的测试类。

+0

可能我应该提到它:我不能使用@RunWith(SpringJUnit4ClassRunner.class),因为参数化测试需要@RunWIth(Parameterized.class)。我使用SpringClassRule和SpringMethodRule代替 – Anton

+0

@Anton为什么不扩展'Parameterized' runner? –

+0

在这种情况下,我将无法为普通而非参数化测试设置属性 – Anton

0

我发现,这是可能的延长AnnotationConfigContextLoader(或任何其他ContextLoader)和压倒一切的prepareContext()方法:

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

不是自定义代码,就在@ContextConfiguration注释上测试实例指定

相关问题