¿Por qué es este método vuelve nula a pesar de que el controlador subyacente puede ser burlado usando Mock Spocks' ()?
-
10-10-2019 - |
Pregunta
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 El método comentado que está en el EventController
- ¿Por qué la causa fragmento " No se puede obtener la propiedad 'mensaje' de objeto nulo "?
- ¿Cómo puedo configurar el fragmento correctamente?
- En general, a / a, no me necesitar cualquiera de los mockTagLib , mockController , mockLogging GrailsUnitTestCase funciones al utilizar Spock ?
Solución
If you are unit testing a controller there is a convention which automatically sets the controller up for you. Just refer to the controller
in your test as follows;
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
}
}
You don't need to explicitly mock the controller as ControllerSpec
does it for you, however, you may need to mock other elements that your controller is using. Sometimes it is sufficient to add these through the controller's metaclass
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow