2015-08-05 3 views
0

У меня есть JUnit-класс вроде этого:Spring JUnit Mocking StrutsServlet находит неправильно AppConfig

@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: один для JUnit, один для MockedServlet.

Проблема:

  • MockedServlet не может autowire MyService, потому что он никогда не загружает AppConfig.

Вопрос:

  • Могу ли я поставить JUnit-ApplicationContext в MockedServlet?
  • Как я могу заставить MockedServlet загрузить AppConfig, сконфигурированный init-parameter в тестовом методе?

ответ

0

Добавить

@WebAppConfiguration 
@BootstrapWith(WebTestContextBootstrapper.class) 

к вашему Тест- класса.

И добавить autowired поле типа WebApplicationContext, который используется в качестве конструктора-аргумента ContextLoaderListener, как это:

@Autowired 
WebApplicationContext ctx; 

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

Теперь вы можете уронить Init-параметров.