2011-01-12 3 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 
    } 
} 

ノートEventControllerSpockのMock()を使って基礎となるコントローラを偽装したのに、なぜこのメソッドがnullを返すのですか?

  1. なぜスニペットの原因「はnullオブジェクトにプロパティ 『メッセージ』を取得できません」んであるコメントアウト方法?
  2. スニペットを正しく設定するにはどうすればよいですか? スポックを使用した場合
  3. 一般的に、/ Iは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

+0

controller.metaClass – mfloryan

+0

Grails(2.3.x)のそれ以降のバージョンのユーザーにとっては、SpockがデフォルトでGrailsのテストの一部となったため、この問題は修正されたようです。 http://jira.grails.org/browse/GRAILS-11239 – jonnybot