使用ServletContextListener进行单元测试

wut*_*aer 2 spring unit-testing servlets listener

我有一个ServletContextListener初始化我的数据库.我在我的web.xml中添加它:

<listener>
   <listener-class>util.MySessionListener</listener-class>
</listener>
Run Code Online (Sandbox Code Playgroud)

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

但是当我运行我的AbstractTransactionalJUnit4SpringContextTests-tests时,它不会被调用.我能做什么?

Tom*_*icz 10

是这个ServletContextListener还是HttpSessionListener?你的命名令人困惑.

然而,只需运行@Before:

MockServletContext mockServletContext = new MockServletContext()
new MySessionListener().contextInitialized(
  new ServletContextEvent(mockServletContext)
)
Run Code Online (Sandbox Code Playgroud)

MockServletContext来自春天.如果您的侦听器使用WebApplicationContextUtils,则需要在运行之前添加contextInitialized():

mockServletContext.setAttribute(
  WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, 
  yourTestApplicationContext
);
Run Code Online (Sandbox Code Playgroud)

哪里yourTestApplicationContext是一个实例ApplicationContext,你可以简单地在你的测试用例注入:

@Autowired
private ApplicationContext yourTestApplicationContext;
Run Code Online (Sandbox Code Playgroud)