我有一个像这样的JUnit-Class:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(loader = AnnotationConfigContextLoader.class, classes = AppConfig.class)
public class PricelistTest {
@Autowired
MyFormBean f;
@Autowired
MyActionBean a;
@Test
public void testAction(){
MockServletContext c = new MockServletContext("/test");
c.addInitParameter("contextClass", AnnotationConfigWebApplicationContext.class.getCanonicalName());
c.addInitParameter("contextConfigLocation", AppConfig.class.getCanonicalName());
ServletContextListener listener = new ContextLoaderListener();
ServletContextEvent event = new ServletContextEvent(c);
listener.contextInitialized(event);
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
a.execute(null, f, request, response);
}
这是我的AppConfig
public class AppConfig {
@Bean
MyFormBean myFormBean(){
return new MyFormBean();
}
@Bean
MyActionBean myMyActionBean(){
return new MyActionBean ();
}
@Bean
MyService myService(){
return new MyService();
}
}
这是我的MyActionBean
public class MyActionBean {
@Autowired
MyService service;
...
public ActionForward execute(...) throws Exception {
ContextLoader.getCurrentWebApplicationContext()
.getAutowireCapableBeanFactory()
.autowireBean(this); <-- throws exception that no MyService bean found.
}
}
情况:
问题:
MyService
,因为它永远不会加载AppConfig
。问题:
AppConfig
配置的init-parameter
?答案 0 :(得分:0)
添加
@WebAppConfiguration
@BootstrapWith(WebTestContextBootstrapper.class)
到您的考试 - 班级。
添加一个类型为WebApplicationContext
的自动装配字段,用作ContextLoaderListener的构造函数参数,如下所示:
@Autowired
WebApplicationContext ctx;
...
ServletContextListener listener = new ContextLoaderListener(ctx);
...
现在你可以删除init-parameters。