Spring JUnit Mocking StrutsServlet发现错误的AppConfig

时间:2015-08-05 17:10:48

标签: java spring junit autowired

我有一个像这样的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.
     }
}

情况:

  • 我有两个Spring-Contexts:一个用于JUnit,一个用于MockedServlet。

问题:

  • MockedServlet无法自动装配MyService,因为它永远不会加载AppConfig

问题:

  • 我可以将JUnit-ApplicationContext放入MockedServlet吗?
  • 如何强制MockedServlet加载测试方法中AppConfig配置的init-parameter

1 个答案:

答案 0 :(得分:0)

添加

@WebAppConfiguration
@BootstrapWith(WebTestContextBootstrapper.class)

到您的考试 - 班级

添加一个类型为WebApplicationContext的自动装配字段,用作ContextLoaderListener的构造函数参数,如下所示:

@Autowired
WebApplicationContext ctx;

...
   ServletContextListener listener = new ContextLoaderListener(ctx);
...

现在你可以删除init-parameters。