使用 Junit 的 Spring 测试会话范围 bean

发布于 2024-10-19 15:11:09 字数 130 浏览 0 评论 0原文

我有一个会话范围的 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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

堇色安年 2024-10-26 15:11:09

我遇到了这种更简单的方法,我想我不妨在这里发布以防其他人需要它。

<bean class="org.springframework.beans.factory.config.CustomScopeConfigurer">
    <property name="scopes">
        <map>
            <entry key="session">
                <bean class="org.springframework.context.support.SimpleThreadScope"/>
            </entry>
        </map>
    </property>
</bean>

使用这种方法,您不必模拟任何请求/会话对象。

来源: http://tarunsapra .wordpress.com/2011/06/28/junit-spring-session-and-request-scope-beans/

spring 5.x 的更新(适用于 spring 5.3.22,在 JUnit5 测试中,注释为@ExtendWith(SpringExtension.class) ):通过注解定义相同的bean。将此代码放置在 spring 配置类中的某个位置:

/**
 * Used in CustomScopeConfigurer bean below
 *
 * @return
 */
@Bean
public static SimpleThreadScope simpleThreadScope()
{
    return new SimpleThreadScope();
}

/**
 * This bean is needed in order to mimic spring's SessionScope
 *
 * @param aSimpleThreadScope
 * @return
 */
@Bean
public static CustomScopeConfigurer customScopeConfigurer(SimpleThreadScope aSimpleThreadScope)
{
    CustomScopeConfigurer result = new CustomScopeConfigurer();
    result.addScope( "session", aSimpleThreadScope );
    return result;
}

I came across this simpler approach, thought I might as well post here in case others need it.

<bean class="org.springframework.beans.factory.config.CustomScopeConfigurer">
    <property name="scopes">
        <map>
            <entry key="session">
                <bean class="org.springframework.context.support.SimpleThreadScope"/>
            </entry>
        </map>
    </property>
</bean>

With this approach, you don't have to mock any request/session objects.

Source: http://tarunsapra.wordpress.com/2011/06/28/junit-spring-session-and-request-scope-beans/

Update for spring 5.x (works in spring 5.3.22, in a JUnit5 test, annotated by @ExtendWith(SpringExtension.class) ): The same bean definitions by annotations. Place this code somewhere in a spring configuration class:

/**
 * Used in CustomScopeConfigurer bean below
 *
 * @return
 */
@Bean
public static SimpleThreadScope simpleThreadScope()
{
    return new SimpleThreadScope();
}

/**
 * This bean is needed in order to mimic spring's SessionScope
 *
 * @param aSimpleThreadScope
 * @return
 */
@Bean
public static CustomScopeConfigurer customScopeConfigurer(SimpleThreadScope aSimpleThreadScope)
{
    CustomScopeConfigurer result = new CustomScopeConfigurer();
    result.addScope( "session", aSimpleThreadScope );
    return result;
}
伊面 2024-10-26 15:11:09

为了在单元测试中使用 request 和 session 作用域,您需要:

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

类似这样的事情(假设您使用 Spring TestContext 来运行你的测试):
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;
    }
}

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

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

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

  • register these scopes in application context
  • create mock session and request
  • register mock request via RequestContextHolder

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();
不美如何 2024-10-26 15:11:09

Spring 3.2 及更高版本为集成测试提供了对会话/请求作用域 bean 的支持

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = TestConfig.class)
@WebAppConfiguration
public class SampleTest {

    @Autowired WebApplicationContext wac;

    @Autowired MockHttpServletRequest request;

    @Autowired MockHttpSession session;    

    @Autowired MySessionBean mySessionBean;

    @Autowired MyRequestBean myRequestBean;

    @Test
    public void requestScope() throws Exception {
        assertThat(myRequestBean)
           .isSameAs(request.getAttribute("myRequestBean"));
        assertThat(myRequestBean)
           .isSameAs(wac.getBean("myRequestBean", MyRequestBean.class));
    }

    @Test
    public void sessionScope() throws Exception {
        assertThat(mySessionBean)
           .isSameAs(session.getAttribute("mySessionBean"));
        assertThat(mySessionBean)
           .isSameAs(wac.getBean("mySessionBean", MySessionBean.class));
    }
}

参考:

Spring 3.2 and newer provides support for session/request scoped beans for integration testing

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = TestConfig.class)
@WebAppConfiguration
public class SampleTest {

    @Autowired WebApplicationContext wac;

    @Autowired MockHttpServletRequest request;

    @Autowired MockHttpSession session;    

    @Autowired MySessionBean mySessionBean;

    @Autowired MyRequestBean myRequestBean;

    @Test
    public void requestScope() throws Exception {
        assertThat(myRequestBean)
           .isSameAs(request.getAttribute("myRequestBean"));
        assertThat(myRequestBean)
           .isSameAs(wac.getBean("myRequestBean", MyRequestBean.class));
    }

    @Test
    public void sessionScope() throws Exception {
        assertThat(mySessionBean)
           .isSameAs(session.getAttribute("mySessionBean"));
        assertThat(mySessionBean)
           .isSameAs(wac.getBean("mySessionBean", MySessionBean.class));
    }
}

References:

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文