1

在运行 Spock 控制器测试时:

导入 grails.plugin.spock.* 导入 grails.test.mixin.*

@Mock(MusicItem) 类 MusicItemControllerSpec 扩展 ControllerSpec {

def "Creating element with correct parameters"() {
    setup:
    controller.params.artist = "John Lennon"
    controller.params.name = "Imagine"
    controller.params.location = new URL ("http://localhost")

    when:
    controller.save()

    then:
    redirectArgs.action == "show"
    controller.flash.message != null
    MusicItem.count() == 1
}

}

测试的部分是:

def save() {
    def musicItemInstance = new MusicItem(params)
    if (!musicItemInstance.save(flush: true)) {
        render(view: "create", model: [musicItemInstance: musicItemInstance])
        return
    }

    flash.message = message(code: 'default.created.message', args: [message(code: 'musicItem.label', default: 'MusicItem'), musicItemInstance.id])
    redirect(action: "show", id: musicItemInstance.id)
}

那是控制器的一部分。我得到了这个例外:

| 运行 6 个 spock 测试... 3 of 6 | 失败:创建具有正确参数的元素(myvibe.fondation.MusicItemControllerSpec)| java.lang.IllegalStateException:未找到 WebApplicationContext:未注册 ContextLoaderListener?在 myvibe.fondation.MusicItemController.save(MusicItemController.groovy:29) 在 myvibe.fondation.MusicItemControllerSpec.Creating 具有正确参数的元素 (MusicItemControllerSpec.groovy:39) | 运行 6 个 spock 测试... 4 of 6

当我从 save() 方法中删除这一行时:

        flash.message = message(code: 'default.created.message', args: [message(code: 'musicItem.label', default: 'MusicItem'), musicItemInstance.id])

比一切都好。我错过了什么?

4

1 回答 1

3

由于消息标签,它失败了。以下应该工作

setup:
controller.metaClass.message = {args -> "mockMessage"}

http://greybeardedgeek.net/2011/05/13/testing-grails-controllers-with-spock/

于 2012-04-06T20:47:53.200 回答