Spring JUnit Mocking StrutsServlet 发现错误的 AppConfig

Spring JUnit Mocking StrutsServlet finds wrong AppConfig

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

情况:

问题:

问题:

添加

@WebAppConfiguration
@BootstrapWith(WebTestContextBootstrapper.class)

你的测试-Class.

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

@Autowired
WebApplicationContext ctx;

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

现在您可以删除初始参数。