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 中被注释掉的方法
最佳答案
如果您正在对 Controller 进行单元测试,则有一个约定可以自动为您设置 Controller 。只需引用 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
}
}
您不需要将 Controller 显式模拟为
ControllerSpec
为你做,但是,你可能需要模拟你的 Controller 正在使用的其他元素。有时通过 Controller 的元类添加这些就足够了
关于unit-testing - 为什么即使使用 Spocks 的 Mock() 模拟了底层 Controller ,此方法仍返回 null?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4671828/