NullpointerException:无法在空对象上获取 属性

NullpointerException: cannot get property on null object

正在使用 IDEA 并尝试启动以下代码:

package com.myCompany.routing.spring

import com.dropbox.core.DbxRequestConfig
import grails.util.Holders
import spock.lang.Specification

class DropboxSpringConfigSpec extends Specification {
    def grailsApplication=Holders.grailsApplication

    def "It instantiates and configures the dropboxRequestConfig component"() {
        given:
        def ctx = grailsApplication.mainContext
        //do stuff...
    }
}

我收到以下错误:

java.lang.NullPointerException: Cannot get property 'mainContext' on null object

at com.myCompany.routing.spring.DropboxSpringConfigSpec.It instantiates and configures the dropboxRequestConfig component(DropboxSpringConfigSpec.groovy:20)

我最近拉动了我的 VCS,所以代码应该可以工作。

当 运行 测试为 Grails 测试时,出现以下错误:

Error | 2015-03-04 13:32:00,989 [localhost-startStop-1] ERROR context.GrailsContextLoader - Error initializing the application: Missing configuration in Config.groovy: connection.uri.

根据您的 extends Specification 看来您拥有的是单元测试。 grailsApplication 在单元规范中不可用,但它可以被模拟(即使用 @TestFor(ClassUnderTest) 注释为您模拟它)。

如果您要测试的是配置,我建议您编写一个 integration 规范。在 integration 阶段,您基本上拥有一个没有 Web 界面的有线 grails 应用程序。在那种情况下,您需要做的就是

package com.myCompany.routing.spring

import com.dropbox.core.DbxRequestConfig
import grails.util.Holders
import grails.test.spock.IntegrationSpec

class DropboxSpringConfigSpec extends IntegrationSpec {
    def grailsApplication //This will be auto-wired 

    def "It instantiates and configures the dropboxRequestConfig component"() {
        given:
        def ctx = grailsApplication.mainContext
        //do stuff...
    }
}

关于该测试以前在您的 VCS 中运行过。我从未在 unit 规范中使用过 Holders,所以我不能说它真的不起作用,但它可能只是一个误报。根据我对 unit 阶段的理解,您没有 运行 grails 应用程序,bean(包括配置)在您或测试框架(再次使用 @TestFor@Mock)

好的,似乎 Config.groovy 中的一些配置被赋予了一些环境变量的值:

elasticSearch {
    connection {
        uri = env.ES_URL
        username = env.ES_USER
        password = env.ES_PASSWORD
    }
    indexPrefix = 'test-'
}

由于我没有创建对应的环境变量,GrailsContextLoader找不到对应的值,计算失败

在我的 IDE 和 运行 测试中初始化所需的环境变量,因为 Grails 测试解决了问题。