在没有XML的情况下测试Spring上下文

3

我在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);
    }
}

附加说明:有一些答案给出了如何基于相同的配置类创建另一个上下文的建议。但是我不能这样做,因为我会微调已创建的上下文(添加一些属性)。我只是添加了代码。


需要澄清一下,您想知道如何测试您的 SpringInitializer 类吗?还是您想知道如何使用Java配置加载测试的 @ContextConfiguration - Akshay
不,我想测试我的DAO。但是我手动构建我的上下文。 - piotrek
3个回答

3

1
@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);
    }

}

我刚刚更新了我的问题(很抱歉没有更具体)。我不能使用这个解决方案,因为它不允许我配置上下文。 - piotrek

0

我刚刚更新了我的问题。这篇文章中没有解决方案。 - piotrek
我现在不理解你的问题。你是说你想进行单元测试,还是测试你的 DAO;但是你也想加载整个上下文吗?你难道不应该只加载你想测试的部分并对其进行测试吗? - Akshay

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接