Perché questo metodo nullo tornando anche se il controller sottostante viene deriso utilizzando Mock Spocks' ()?

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

Domanda

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
    }
}

Nota Il metodo commentata che si trova nel EventController

  1. Perché la causa frammento di " Impossibile ottenere proprietà 'messaggio' sul oggetto null "?
  2. Come faccio a impostare il frammento correttamente?
  3. In generale, ti / vi Non ho bisogno di nessuna delle mockTagLib , mockController , mockLogging funzioni GrailsUnitTestCase quando si utilizza Spock
È stato utile?

Soluzione

Se sei unità testare un controllore v'è una convenzione che imposta automaticamente il controller per voi. Basta fare riferimento al controller nel tuo test come segue;

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
  }
}

Non è necessario prendere in giro in modo esplicito il controller come ControllerSpec fa per voi, tuttavia, potrebbe essere necessario prendere in giro gli altri elementi che il controller sta usando. A volte è sufficiente aggiungere queste attraverso metaclasse del controllore

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top