将 GMock 与 Spring 一起使用,如何为多个测试仅设置一次 Spring 上下文?
我发现当使用内存数据库运行多个 gmock 测试时,我收到有关表的错误已经在那里了。它似乎多次运行 spring 上下文创建,即使它只在给定的测试类中设置一次作为所有测试方法使用的字段。
理想情况下,我希望多个类重用相同的上下文,但即使使用单个 GMockTestCase 的多个方法也会重新创建 spring 上下文。
覆盖 Junit 设置方法没有帮助。
我发现这种行为不直观且不正确,但我可能不明白 gmock 或 groovy 作品
class MyTest extends GMockTestCase {
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("classpath:spring.test.xml")
def mockRequest = mock(RenderRequest)
def mockResponse = mock(RenderResponse)
void testHandleRequest() {
mockRequest.getAttribute('javax.portlet.userinfo').returns(userInfo)
mockRequest.getRemoteUser().returns(userName)
play {
def mav = mainController.handleRenderRequestInternal(mockRequest, mockResponse)
assertEquals userName, mav.model.un
我现在可以使用但并不理想的一种解决方法是使用带注释的技术并扩展 spring 测试类,如下所示:
@WithGMock
@ContextConfiguration(locations = ["classpath:spring.dev.xml"])
class MyTest extends AbstractTransactionalJUnit4SpringContextTests {
I find that when running multiple gmock tests using and in memory database I get errors about table already being there. It seems to run the spring context creation multiple times, even though it's only set once in a given test class as a field to be used by all the test methods.
Ideally I would like multiple classes to reuse the same context but even multiple methods with a single GMockTestCase are re creating the spring context.
Overriding Junit setup method doesn't help.
I find this behaviour unintuitive and incorrect but probably there's something I don't understand about how gmock or groovy works
class MyTest extends GMockTestCase {
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("classpath:spring.test.xml")
def mockRequest = mock(RenderRequest)
def mockResponse = mock(RenderResponse)
void testHandleRequest() {
mockRequest.getAttribute('javax.portlet.userinfo').returns(userInfo)
mockRequest.getRemoteUser().returns(userName)
play {
def mav = mainController.handleRenderRequestInternal(mockRequest, mockResponse)
assertEquals userName, mav.model.un
One workaround I can use for now but is not ideal is to use the annotated technique and extend a spring test class like this:
@WithGMock
@ContextConfiguration(locations = ["classpath:spring.dev.xml"])
class MyTest extends AbstractTransactionalJUnit4SpringContextTests {
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
@BeforeClass 允许您为每个类构建一个上下文
@BeforeClass would allow you to construct one context per class
你可以使用它
,并且可以多次使用它们。
you can use this
and you can use them many time.