2

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

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

 @ClassRule 
 static PluginThatSetsUpSomethingEmbedded pluginRule = new PluginThatSetsUpSomethingEmbedded();



}

现在我的一个 Spring bean 需要一些只能脱离规则的东西,比如:

pluginRule.getEmbeddedToolConfig()

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

4

1 回答 1

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) {
    }


}

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

于 2017-11-11T11:46:06.300 回答