如何将来自规则的值注入测试弹簧上下文?

时间:2015-07-17 17:17:15

标签: spring testing junit spring-test junit-rule

假设您在测试弹簧上下文时遇到以下情况

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {ConfigClass.class})
public class IntegrationTest   {

 @ClassRule 
 static PluginThatSetsUpSomethingEmbedded pluginRule = new PluginThatSetsUpSomethingEmbedded();



}

现在,我的一个Spring bean需要的东西只能来自规则,例如:

pluginRule.getEmbeddedToolConfig()

如何为我的bean提供该配置,注意规则是ClassRule并且也是静态的......

1 个答案:

答案 0 :(得分:1)

我建议您使用ApplicationContextInitializer,您的测试类将是这样的:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {ConfigClass.class}, initializers = IntegrationTest.Initializer.class)
public class IntegrationTest   {

 @ClassRule 
 static PluginThatSetsUpSomethingEmbedded pluginRule = new PluginThatSetsUpSomethingEmbedded();

 public static class Initializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {
    @Override
    public void initialize(ConfigurableApplicationContext configurableApplicationContext) {
    }


}

在方法初始化中,您可以实现逻辑。