首页 > 解决方案 > grails 4单元测试控制器找不到类

问题描述

我正在使用 grails 4 为控制器创建单元测试 https://testing.grails.org/latest/guide/index.html

我的控制器在 grails-app/controllers/mypack/myfolder/exampleController.groovy 下

我的单元测试在 src/test/groovy/mypack/myfolder/exampleControllerSpec.groovy

我的单元测试就像这个类 exampleControllerSpec extends Specification implements ControllerUnitTest<exampleController>

但它抱怨无法解析符号'exampleController'

这里有什么问题吗?

如何导入示例控制器

标签: testinggrailsgroovy

解决方案


https://github.com/jeffbrown/leecontrollertest上的项目演示了如何构建测试。

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!'
    }
}

推荐阅读