运行Spock控制器测试时:
import grails.plugin.spock。* import grails.test.mixin。*
@Mock(MusicItem) class 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? at myvibe.fondation.MusicItemController.save(MusicItemController.groovy:29) at 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])
比所有工作都好。我缺少什么?
答案 0 :(得分:3)
因为消息标记而失败。以下应该工作
setup:
controller.metaClass.message = {args -> "mockMessage"}
http://greybeardedgeek.net/2011/05/13/testing-grails-controllers-with-spock/