【问题标题】:Correct usage subclassing a spring ContextLoader for testing正确使用子类化 spring ContextLoader 进行测试
【发布时间】:2011-03-09 12:19:39
【问题描述】:

对于我的 spring 应用程序与 junit 的集成测试,我将 org.springframework.test.context.ContextLoader 子类化,因为我想使用已经存在的 XmlWebApplicationContext 来连接我的测试类,如下所示:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(loader=MyContextLoader.class)
@Transactional
public class MyTest {
    @Autowired
    public AccountDao accountDao;
}

我的ContextLoader的实现如下:

公共类 MyContextLoader 实现 ContextLoader {

    @Override
    public String[] processLocations(Class<?> clazz, String... locations) {
        return locations;
    }

    @Override
    public ApplicationContext loadContext(String... locations) throws Exception {
        try {
            // Start Embedded Tomcat
            EmbeddedTomcat tomcat = new EmbeddedTomcat("mas", 8080);
            tomcat.launch();

            Context rootContext = tomcat.getRootContext();
            ContextLoaderListener contextLoaderListener = (ContextLoaderListener) rootContext.getApplicationLifecycleListeners()[0];
            XmlWebApplicationContext context = (XmlWebApplicationContext) contextLoaderListener.getContext();


            GenericApplicationContext c = new GenericApplicationContext(context);
            AnnotationConfigUtils.registerAnnotationConfigProcessors(c);

            //context.refresh();
            //context.registerShutdownHook();

            return context;
        }
        catch(Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }   
    }   
}

loadContext(...) 方法中放置断点时,我可以调用 getBean(AccountDao.class) 并且一切正常。但是,似乎我的测试类实际上不是自动装配的。我调试了一下并逐步执行了 spring 代码,似乎在方法 AbstractAutowireCapableBeanFactory.populateBean(String beanName, AbstractBeanDefinition mbd, BeanWrapper bw) 中没有为我的类 Test 设置 PropertyValues。

也许,我是否设置了注释处理错误?

代码信息:正如您可能猜到的那样,我正在做一个集成测试,因此启动了一个嵌入式 tomcat 服务器来测试我的 RESTful web 服务。我在此处的帖子中显示了如何通过“hack”从嵌入式 tomcat 获取应用程序上下文:Getting Access to Spring with Embedded Tomcat 6

期待您的回复。 埃里克

【问题讨论】:

    标签: spring jakarta-ee spring-annotations spring-test


    【解决方案1】:

    我认为这里的问题是您正在创建一个新的GenericApplicationContext,它不是 Spring 用来自动装配测试 bean 的那个。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多