栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

使用Junit的Spring Test会话作用域bean

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

使用Junit的Spring Test会话作用域bean

为了在单元测试中使用请求和会话范围,您需要:

  • 在应用程序上下文中注册这些范围
  • 创建模拟会话并请求
  • 通过注册模拟请求
    RequestContextHolder

这样的事情(假设您使用Spring TestContext运行测试)

abstractSessionTest.xml

<beans ...>    <bean >        <property name="scopes"> <map>     <entry key="session">         <bean  />     </entry>     <entry key="request">         <bean  />     </entry> </map>        </property>    </bean></beans>

@ContextConfiguration("abstractSessionTest.xml")public abstract class AbstractSessionTest {    protected MockHttpSession session;    protected MockHttpServletRequest request;    protected void startSession() {        session = new MockHttpSession();    }    protected void endSession() {        session.clearAttributes();        session = null;    }    protected void startRequest() {        request = new MockHttpServletRequest();        request.setSession(session);        RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(request));    }    protected void endRequest() {        ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).requestCompleted();        RequestContextHolder.resetRequestAttributes();        request = null;    }}

现在,您可以在测试代码中使用以下方法:

startSession();startRequest();// inside requestendRequest();startRequest();// inside another request of the same sessionendRequest();endSession();


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/435492.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号