Java 不使用xml测试spring上下文

Java 不使用xml测试spring上下文,java,spring,unit-testing,testing,web-applications,Java,Spring,Unit Testing,Testing,Web Applications,我在web应用程序中使用基于java的配置: public class SpringInitializer implements WebApplicationInitializer { @Override public void onStartup(ServletContext servletContext) { AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationConte

我在web应用程序中使用基于java的配置:

public class SpringInitializer implements WebApplicationInitializer {

  @Override
  public void onStartup(ServletContext servletContext) {
    AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
    ctx.getEnvironment().getPropertySources().addLast( myMethod() );
    ctx.scan("com.xxx.xxx");

  }
}
我如何测试它

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(????????????)
public class PersistenceConfigurationTest {

    @PersistenceContext EntityManager entityManager;
    @Autowired DataSource dataSource;

    @Test
    public void infrastructureShouldBeAutowired() {
        assertNotNull(dataSource);
        assertNotNull(entityManager);
    }
}
附加备注:
对于如何基于同一配置类创建另一个上下文,有一些答案和建议。我不能这样做,因为我微调了创建的上下文(添加了一些属性)。我刚刚添加了代码

,这篇博文应该几乎准确地回答了您的问题(我只希望您使用的是Spring 3.1)

滚动至@Configuration Classes集成测试部分


希望这能解决你的问题。

我想这会回答你的问题:
@Configuration
@ComponentScan("com.xxx.xxx")
public class Config {}

public class SpringInitializer implements WebApplicationInitializer {

    public void onStartup(ServletContext servletContext) throws ServletException {
        AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
        ctx.register(Config.class);

        // Register and map the dispatcher servlet
        ServletRegistration.Dynamic dispatcher = servletContext.addServlet("dispatcher", new DispatcherServlet(ctx));
        dispatcher.setLoadOnStartup(1);
        dispatcher.addMapping("/");
    }

}

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes = {Config.class})
public class PersistenceConfigurationTest {

    @PersistenceContext EntityManager entityManager;
    @Autowired DataSource dataSource;

    @Test
    public void infrastructureShouldBeAutowired() {
        assertNotNull(dataSource);
        assertNotNull(entityManager);
    }

}


一句话:你想做的还不可能。彼此彼此。我使用WebApplicationInitializer来使用CustomBeanFactory并实现注入。但是现在我无法将记录器注入到我的测试对象中。

需要一些说明,您想知道如何测试
SpringInitializer
类吗?或者您想知道如何为使用java配置的测试加载
@ContextConfiguration
?不,我想测试我的dao。但我正在手动构建上下文,我刚刚更新了我的问题。这篇文章没有解决办法我现在不明白你的问题。。你说你想要单元测试,或者测试你的dao;但是您还想加载整个上下文吗?难道你不应该只加载你想测试的东西并测试它吗?我刚刚更新了我的问题(很抱歉没有更具体)。我无法使用此解决方案,因为它不允许我配置上下文