javatestinggroovytddgmock

Using GMock with Spring how to I setup up a spring context only once for several tests?


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 {

Solution

  • @BeforeClass would allow you to construct one context per class