unit-testing - 为什么即使使用 Spocks 的 Mock() 模拟了底层 Controller ,此方法仍返回 null?

标签 unit-testing grails mocking grails-plugin spock

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 中被注释掉的方法
  • 为什么代码段会导致“ 无法在空对象 上获取属性 'message'”?
  • 如何正确设置代码段?
  • 一般来说,在使用 时,我是否需要任何 mockTagLib、mockController、mockLogging GrailsUnitTestCase 函数?斯波克 ?
  • 最佳答案

    如果您正在对 Controller 进行单元测试,则有一个约定可以自动为您设置 Controller 。只需引用 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
      }
    }
    

    您不需要将 Controller 显式模拟为 ControllerSpec为你做,但是,你可能需要模拟你的 Controller 正在使用的其他元素。有时通过 Controller 的元类添加这些就足够了

    关于unit-testing - 为什么即使使用 Spocks 的 Mock() 模拟了底层 Controller ,此方法仍返回 null?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4671828/

    相关文章:

    ios - 是否可以使用 OCMock stub NSProcessInfo ?

    .net - 有没有类似 TypeMock 的开源 mocking 框架?

    grails - GORM:可以查询州和县

    java - 如何使用 Mockito 模拟 void 方法

    安卓。 @RunWith(AndroidJUnit4.class) - 无法在包 "androidTest"中解析

    json - Grails中将JSON作为渲染标准的问题!在一个 Restful 服务中找到一个字段并进行渲染

    maven - Maven Grails web.xml

    .net - 如何使用 Moq 模拟具有两个索引的索引属性

    java - 如何模拟 super 方法调用

    java - 在 Android 的单元测试中覆盖 SLF4J 实现