【问题标题】:unittesting with ServletContextListener使用 ServletContextListener 进行单元测试
【发布时间】:2012-05-23 19:53:51
【问题描述】:

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

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

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

但是当我运行我的 AbstractTransactionalJUnit4SpringContextTests-tests 时,它不会被调用。我该怎么办?

【问题讨论】:

标签: spring unit-testing servlets listener


【解决方案1】:

我解决了

ApplicationContextAware

界面:

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

并且在

public void setApplicationContext(ApplicationContext context) throws BeansException {

我可以进行初始化,休眠,此时一切准备就绪

【讨论】:

    【解决方案2】:

    这是ServletContextListener 还是HttpSessionListener?您的命名令人困惑。

    不过,只需在 @Before 中运行它:

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

    MockServletContext 来自 Spring。如果你的监听器使用WebApplicationContextUtils,你需要在运行contextInitialized()之前添加它:

    mockServletContext.setAttribute(
      WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, 
      yourTestApplicationContext
    );
    

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

    @Autowired
    private ApplicationContext yourTestApplicationContext;
    

    【讨论】:

    • 当我调用:new MySessionListener().contextInitialized(new ServletContextEvent(mockServletContext)) 时,我得到 Context 属性不是 WebApplicationContext 类型
    • @wutzebaer 现在可能为时已晚,但是您为属性设置的值看起来不像WebApplicationContext 的实例。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-11
    • 2011-11-16
    • 2015-05-28
    • 2010-11-30
    • 2010-12-31
    • 2018-05-06
    • 2017-07-22
    相关资源
    最近更新 更多