使用 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我遇到了这种更简单的方法,我想我不妨在这里发布以防其他人需要它。
使用这种方法,您不必模拟任何请求/会话对象。
来源: 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 配置类中的某个位置:
I came across this simpler approach, thought I might as well post here in case others need it.
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:
为了在单元测试中使用 request 和 session 作用域,您需要:
RequestContextHolder
注册模拟请求类似这样的事情(假设您使用 Spring TestContext 来运行你的测试):
abstractSessionTest.xml
:.
现在您可以在测试代码中使用这些方法:
In order to use request and session scopes in unit test you need to:
RequestContextHolder
Something like this (assume that you use Spring TestContext to run your tests):
abstractSessionTest.xml
:.
Now you can use these methods in your test code:
Spring 3.2 及更高版本为集成测试提供了对会话/请求作用域 bean 的支持
参考:
Spring 3.2 and newer provides support for session/request scoped beans for integration testing
References: