2012-05-16 57 views
2

我有一个ServletContextListener初始化我的数据库。我已经addid它在我的web.xml中:单元测试与ServletContextListener

<listener> 
    <listener-class>util.MySessionListener</listener-class> 
</listener> 

当我启动服务器一切都很好。

但是当我运行我的AbstractTransactionalJUnit4SpringContextTests-测试它没有被调用。我能做什么?

+0

使用http://static.springsource.org/spring/docs/2.5.x /api/org/springframework/mock/web/package-summary.html – NightWolf

回答

0

我解决了它在

ApplicationContextAware 

接口:

<bean id="springApplicationContext" class="server.utils.SpringApplicationContext" /> 

,并在

public void setApplicationContext(ApplicationContext context) throws BeansException { 

我可以做我的初始化,休眠和万事俱备此时

9

这是ServletContextListenerHttpSessionListener?你的命名很混乱。凡MockServletContext来自春天

MockServletContext mockServletContext = new MockServletContext() 
new MySessionListener().contextInitialized(
    new ServletContextEvent(mockServletContext) 
) 

然而,简单地在@Before运行此。如果你的听众使用WebApplicationContextUtils,您将需要运行contextInitialized()前补充一点:

mockServletContext.setAttribute(
    WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, 
    yourTestApplicationContext 
); 

yourTestApplicationContextApplicationContext一个实例,你可以在你的测试用例简单地注入:

@Autowired 
private ApplicationContext yourTestApplicationContext; 
+0

谢谢我以后再试 – wutzebaer

+0

当我调用:new MySessionListener()。contextInitialized( new ServletContextEvent(mockServletContext) ),我得到的上下文属性是不是类型WebApplicationContext – wutzebaer

+0

有什么想法为什么? – wutzebaer