Search code examples
testinggrailsgroovy

grails 4 unit test controller could not find class


I am using grails 4 to create unit test for controller https://testing.grails.org/latest/guide/index.html

My controller is under grails-app/controllers/mypack/myfolder/exampleController.groovy

My unit test is under src/test/groovy/mypack/myfolder/exampleControllerSpec.groovy

my unit test is like this class exampleControllerSpec extends Specification implements ControllerUnitTest< exampleController>

but it complain can not resolve symbol 'exampleController'

anything wrong here?

how to import exampleController


Solution

  • The project at https://github.com/jeffbrown/leecontrollertest demonstrates how to construct the test.

    https://github.com/jeffbrown/leecontrollertest/blob/d6fc272a69406f71286bf5268794ef4a4252a15b/grails-app/controllers/mypack/myfolder/exampleController.groovy

    package mypack.myfolder
    
    // NOTE: The nonstandard class naming convention here is intentional
    // per https://stackoverflow.com/questions/65723769/grails-4-unit-test-controller-could-not-find-class
    class exampleController {
    
        def hello() {
            render 'Hello, World!'
        }
    }
    

    https://github.com/jeffbrown/leecontrollertest/blob/d6fc272a69406f71286bf5268794ef4a4252a15b/src/test/groovy/mypack/myfolder/exampleControllerSpec.groovy

    package mypack.myfolder
    
    import grails.testing.web.controllers.ControllerUnitTest
    import spock.lang.Specification
    
    // NOTE: The nonstandard class naming convention here is intentional
    // per https://stackoverflow.com/questions/65723769/grails-4-unit-test-controller-could-not-find-class
    class exampleControllerSpec extends Specification implements ControllerUnitTest<exampleController> {
    
        void "test action which renders text"() {
            when:
            controller.hello()
    
            then:
            status == 200
            response.text == 'Hello, World!'
        }
    }