Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

integration testing in Grails: what is the correct way?

I'm entirely new to Grails and it's testing functions since I started my current job approx 4 months ago. The person who trained me on testing left our group several weeks ago, and now I'm on my own for testing. What I've slowing been discovering is that the way I was trained on how to do Grails integration testing is almost entirely different from the way(s) that I've seen people do it on the forums and support groups. I could really use some guidance on which way is right/best. I'm currently working in Grails 2.4.0, btw.

Here is a sample mockup of an integration test in the style that I was trained on. Is this the right or even the best way that I should be doing it?

@Test
void "test a method in a controller"() { 

def fc = new FooController() // 1. Create controller

fc.springSecurityService = [principal: [username: 'somebody']]  // 2. Setup Inputs
fc.params.id = '1122' 

fc.create()  // 3. Call the method being tested

assertEquals "User Not Found", fc.flash.errorMessage   // 4. Make assertions on what was supposed to happen
assertEquals "/", fc.response.redirectUrl

}
like image 441
ry1633 Avatar asked Jun 16 '14 17:06

ry1633


1 Answers

Since Grails 2.4.0 is used, you can leverage the benefit of using spock framework by default.

Here is sample unit test case which you can model after to write Integration specs.

Note:

  • Integration specs goes to test/integration
  • should inherit IntegrationSpec.
  • Mocking is not needed. @TestFor is not used as compared to unit spec.
  • DI can be used to full extent. def myService at class level will inject the service in spec.
  • Mocking not required for domain entities.

Above spec should look like:

import grails.test.spock.IntegrationSpec

class FooControllerSpec extends IntegrationSpec {

    void "test a method in a controller"() { 
        given: 'Foo Controller'
        def fc = new FooController()

        and: 'with authorized user'
        fc.springSecurityService = [principal: [username: 'somebody']]

        and: 'with request parameter set'
        fc.params.id = '1122' 

        when: 'create is called'
        fc.create()

        then: 'check redirect url and error message'
        fc.flash.errorMessage == "User Not Found"
        fc.response.redirectUrl == "/"
    }
}
like image 144
dmahapatro Avatar answered Oct 23 '22 17:10

dmahapatro