0
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 中被注释掉的方法

  1. 为什么代码段会导致“无法在空对象上获取属性‘消息’ ”?
  2. 如何正确设置代码段?
  3. 一般来说,在使用Spock时,我是否需要任何mockTagLibmockControllermockLogging GrailsUnitTestCase 函数?
4

1 回答 1

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为您那样显式地模拟控制器,但是,您可能需要模拟控制器正在使用的其他元素。有时通过控制器的元类添加这些就足够了

于 2011-01-12T18:13:45.097 回答