Pourquoi cette méthode retourne null même si le contrôleur sous-jacent est raillé à l'aide Mock () de Spocks?
-
10-10-2019 - |
Question
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
}
}
noter la méthode commentée qui est dans le EventController
- Pourquoi l'extrait cause " Impossible d'obtenir la propriété 'message' sur l'objet null "?
- Comment puis-je configurer l'extrait correctement?
- En général, est-ce / je ne besoin des mockTagLib , mockController , mockLogging Fonctions GrailsUnitTestCase lors de l'utilisation Spock ?
La solution
Si vous êtes un contrôleur test unité il y a une convention qui règle automatiquement le contrôleur pour vous. Il suffit de se référer à la controller
dans votre test comme suit:
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
}
}
Vous n'avez pas besoin de se moquer explicitement le contrôleur comme ControllerSpec
pour vous le fait, cependant, vous devrez peut-être de se moquer d'autres éléments que votre contrôleur utilise. Parfois, il suffit d'ajouter ces à travers la métaclasse du contrôleur
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow