使用 Junit 的 Spring 测试会话范围 bean [英] Spring Test session scope bean using Junit

查看:32
本文介绍了使用 Junit 的 Spring 测试会话范围 bean的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个会话范围的 bean,它保存每个 http 会话的用户数据.我想编写一个 Junit 测试用例来测试会话范围的 bean.我想编写测试用例,以便它可以证明每个会话都创建了 bean.任何关于如何编写此类 Junit 测试用例的指针?

I have a session scoped bean which holds user data per http session. I would like to write a Junit test case to test the session scoped bean. I would like to write the test case such that it can prove that the beans are getting created per session. Any pointer as how to write such Junit test case?

推荐答案

为了在单元测试中使用请求和会话作用域,你需要:

In order to use request and session scopes in unit test you need to:

  • 在应用程序上下文中注册这些范围
  • 创建模拟会话和请求
  • 通过RequestContextHolder
  • 注册模拟请求
  • register these scopes in application context
  • create mock session and request
  • register mock request via RequestContextHolder

类似这样(假设您使用 Spring TestContext 来运行您的测试):abstractSessionTest.xml:

Something like this (assume that you use Spring TestContext to run your tests): abstractSessionTest.xml:

<beans ...>
    <bean class="org.springframework.beans.factory.config.CustomScopeConfigurer">
        <property name="scopes">
            <map>
                <entry key="session">
                    <bean class="org.springframework.web.context.request.SessionScope" />
                </entry>
                <entry key="request">
                    <bean class="org.springframework.web.context.request.RequestScope" />
                </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;
    }
}

现在您可以在测试代码中使用这些方法:

Now you can use these methods in your test code:

startSession();
startRequest();
// inside request
endRequest();
startRequest();
// inside another request of the same session
endRequest();
endSession();

这篇关于使用 Junit 的 Spring 测试会话范围 bean的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆