Spring集成测试,上下文层次结构子上下文bean作为应用程序监听器

时间:2014-08-08 22:15:00

标签: java spring junit

我是Spring的新手,请原谅我,如果我做一些愚蠢的事情。我正在尝试为我的应用程序编写一个使用spring的集成测试。

我正在创建一个上下文层次结构,如下所示

  @Before
  public void setup(){
     parentContext = new AnnotationConfigApplicationContext(TestConfig.class);
     // some more setup stuff here
  }

在我的测试方法中,我试图创建一个新的子上下文,它只有一个bean,它是一个应用程序监听器,依赖于父方法中的bean。

public void test(){
    childContext = new AnnotationConfigApplicationContext();
    childContext.setParent(ctx);
    register(TestConfig2.class);
    childContext.refresh();
    // some testing stuff here that generates events
}

我面临的问题是来自子上下文的我的bean没有得到应用程序事件的通知,我的@Value注释也没有得到处理。

我在这里做错了什么?

2 个答案:

答案 0 :(得分:0)

声明

private static ClassPathXmlApplicationContext context;

方法@Before

@BeforeClass
public static void setUpBeforeClass() throws Exception {
    context = new ClassPathXmlApplicationContext("/WEB-INF/application-Context.xml");
}

在methode @After

@AfterClass
public static void tearDownAfterClass() throws Exception {
    context.close();
}

你的方法测试

@Test
public void Test() {
    //Your Code Here
}

我也是在春天开始的

答案 1 :(得分:0)

实际上我弄清楚出了什么问题。我的事件发布者位于父上下文中。我在春季论坛上看到,春天的上下文层次结构就像类加载器一样。与在子上加载的任何bean中一样,父上下文不可见。

所以我不得不手动将applicationlistener添加到父上下文。

parentContext.addApplicationListener(messageListener);

如果想让我的childContext bean从parentContext获取属性,我必须将parentContext的PropertyPlaceholderConfigurer添加为beanFactoryPostProcessor。

  configurer = parentContext.getBean(PropertyPlaceholderConfigurer.class);
  childContext.addBeanFactoryPostProcessor(configurer);

总结一下,我必须在我的测试方法中执行以下操作

public void test(){
    childContext = new AnnotationConfigApplicationContext();
    childContext.setParent(parentContext);
    register(TestConfig2.class);
    configurer = parentContext.getBean(PropertyPlaceholderConfigurer.class);
    childContext.addBeanFactoryPostProcessor(configurer);
    childContext.refresh();

    MessageListener messageListener = childContext.getBean(MessageListener.class);
    parentContext.addApplicationListener(messageListener);

    // some testing stuff here that generates events
}
相关问题