基礎となるコントローラーがspocks 'mock()を使用してmockedされている場合でも、この方法がnullを返すのはなぜですか?

StackOverflow https://stackoverflow.com/questions/4671828

質問

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. なぜスニペットは原因です」nullオブジェクトでプロパティ「メッセージ」を取得できません"?
  2. スニペットを正しくセットアップするにはどうすればよいですか?
  3. 一般的に、ウィル/私はどれも必要ありません モックタグリブ, mockcontroller, モックロギング GrailSunittestCaseを使用するときに機能します スポック?
役に立ちましたか?

解決

コントローラーをユニットテストしている場合、コントローラーを自動的に設定するコンベンションがあります。を参照してください 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
  }
}

コントローラーを明示的にock笑する必要はありません ControllerSpec ただし、コントローラーが使用している他の要素をモックする必要がある場合があります。コントローラーのメタラスを介してこれらを追加するだけで十分な場合があります

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top