用Spock测试我的控制器

时间:2012-03-22 14:54:10

标签: unit-testing grails groovy spock

我需要测试一个动作index的控制器(由grails generate-all命令生成)。我有这样的测试(在Spock中):

package mnm.schedule

import grails.test.mixin.*
import org.junit.*
import grails.plugin.spock.*
import spock.lang.Specification
import org.example.*;

class UserControllerSpec extends ControllerSpec {


def "test"() {
            setup:
            mockLogging(UserController, true)

            when:
            controller.index()

            then:
            redirectArgs.action == "list"
    }

} 

我收到这样的错误:

Error Error running script test-app :spock : cannot find shared instance field (Use --stacktrace to see the full trace)

过了一段时间我可以运行测试,测试正在通过。

实际上出了什么问题?为什么第一次出现错误?我是Spock环境的新手。

提前致谢。

1 个答案:

答案 0 :(得分:3)

鉴于您使用的是Grails 2.x.x,您应该使用@TestFor注释来增强使用mixins的单元测试框架类。

在您的情况下,您应该将@TestFor(UserController)添加为类级注释,以便使用mockLogging方法。