用于测试的spring ContextLoader子类化的正确用法
对于我的spring应用程序与junit的集成测试,我正在对用于测试的spring ContextLoader子类化的正确用法,spring,jakarta-ee,spring-annotations,spring-test,Spring,Jakarta Ee,Spring Annotations,Spring Test,对于我的spring应用程序与junit的集成测试,我正在对org.springframework.test.context.ContextLoader进行子类化,因为我想使用一个已经存在的XmlWebApplicationContext来连接我的测试类,如下所示: @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(loader=MyContextLoader.class) @Transactional public cl
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);
}
}
}
@覆盖
公共字符串[]进程位置(类clazz、字符串…位置){
返回地点;
}
@凌驾
公共应用程序上下文loadContext(字符串…位置)引发异常{
试一试{
//启动嵌入式Tomcat
EmbeddedTomcat-tomcat=新的EmbeddedTomcat(“mas”,8080);
tomcat.launch();
Context-rootContext=tomcat.getRootContext();
ContextLoaderListener ContextLoaderListener=(ContextLoaderListener)rootContext.GetApplicationLifeCycleSteners()[0];
XmlWebApplicationContext上下文=(XmlWebApplicationContext)contextLoaderListener.getContext();
GenericaApplicationContext c=新的GenericaApplicationContext(上下文);
AnnotationConfigUtils.registerAnnotationConfigProcessors(c);
//context.refresh();
//registerShutdownHook();
返回上下文;
}
捕获(例外e){
e、 printStackTrace();
抛出新的运行时异常(e);
}
}
}
在loadContext(…)
方法中放置断点时,我可以调用getBean(AccountDao.class),一切正常。然而,似乎我的测试类实际上不是自动连接的。我对spring代码进行了一点调试并逐步完成,似乎在AbstractAutowireCapableBeanFactory.populateBean(String beanName、AbstractBeanDefinition mbd、BeanRapper bw)方法中,没有为我的类测试设置PropertyValue
也许,我设置注释处理错误了吗
代码信息:正如您可能猜到和看到的,我正在进行集成测试,因此启动了一个嵌入式tomcat服务器,以测试我的RESTful Web服务。我在这里的帖子中展示了如何通过“黑客”从嵌入式tomcat获取应用程序上下文:
我期待着你的答复。
Erik我认为这里的问题是您正在创建一个新的
通用应用程序上下文
,它不是Spring用来自动连接测试bean的