2011-01-12 16 views
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即使使用Spock的Mock()模拟底层控制器,该方法为什么返回null?

  1. 为什么片断原因“不能空对象上获取属性‘消息’”?
  2. 如何正确设置代码片段?
  3. 一般情况下,会/不会,我需要的任何mockTagLibmockControllermockLogging GrailsUnitTestCase功能使用斯波克什么时候?

回答

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它给你,但是,你可能需要模拟你的控制器使用的其他元素。有时候通过控制器的元类添加这些就足够了

+0

太好了!谢谢,mfloryan。 在这种情况下(?),它是控制器的元类吗? – user569825 2011-01-13 11:14:21

相关问题