假设您在测试spring上下文时遇到以下情况
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {ConfigClass.class})
public class IntegrationTest {
@ClassRule
static PluginThatSetsUpSomethingEmbedded pluginRule = new PluginThatSetsUpSomethingEmbedded();
}
现在我的一个Spring bean需要一些只能从规则中得到的东西,比如:
pluginRule.getEmbeddedToolConfig()
我如何为bean提供该配置,注意该规则是ClassRule并且也是静态的…
我建议你使用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) {
}
}
在method initialize中你可以实现你的逻辑