import grails.plugin.spock.*
class EventControllerSpec extends ControllerSpec {
def "Creating a breadcrumb from an event"() {
given: "I have a named event"
def eventController = Mock(EventController)
def event = Mock(Event)
event.title >> 'Space-Journey with Sprock and the Crew'
event.title == 'Space-Journey with Sprock and the Crew'
when: "I create a breadcrumb from it"
def eventCrumb = eventController.createCrumb("Event", "show", "1", event.title)
/*
private Map createCrumb (String controllerName, String actionName, String id, String msg) {
msg = (msg ? msg : "cr.breadcrumb.${controllerName}.${actionName}")
[ 'controller':controllerName,
'action':actionName,
'id':id,
'message':msg
]
*/
then: "I receive a map where the message-value is the events' title"
eventCrumb.message == event.title
}
}
注意在EventController中注释掉的方法
答案 0 :(得分:1)
如果您正在对控制器进行单元测试,则会有一个约定,可以自动为您设置控制器。只需在测试中参考controller
,如下所示;
import grails.plugin.spock.*
class EventControllerSpec extends ControllerSpec {
def "Creating a breadcrumb from an event"() {
given: "I have a named event"
def event = Mock(Event)
event.title >> 'Space-Journey with Sprock and the Crew'
when: "I create a breadcrumb from it"
def eventCrumb = controller.createCrumb("Event", "show", "1", event.title)
/*
private Map createCrumb (String controllerName, String actionName, String id, String msg) {
msg = (msg ? msg : "cr.breadcrumb.${controllerName}.${actionName}")
[ 'controller':controllerName,
'action':actionName,
'id':id,
'message':msg
]
*/
then: "I receive a map where the message-value is the events' title"
eventCrumb.message == event.title
}
}
您不需要显式模拟控制器,因为ControllerSpec
为您执行此操作,但是,您可能需要模拟控制器正在使用的其他元素。有时通过控制器的元类