在Grails 2. *中获取其他环境的配置

时间:2018-08-02 14:53:44

标签: grails grails-2.0 grails-test

我正在运行Grails 2.1.1,并且我正在寻找一种在测试环境中运行时获取生产中变量集值的方法。 配置文件:

development {
  config.url = "http://local"
}
test {
  config.url = "http://test.lan"
}
production {
  config.url = "http://prod.lan"
}

我知道获取配置变量的唯一方法是grailsApplication.config.url

2 个答案:

答案 0 :(得分:1)

标准配置设置仅针对当前环境。 HoldersgrailsApplication具有相同的当前配置。您必须再次设置配置。尝试使用ConfigurationHelper。下面是spock测试。 (请注意,有时加倍的config.config是因为第一个config是属性(或getConfig()方法的缩写),并且您的密钥包含第二个config。)

import grails.test.mixin.TestMixin
import grails.test.mixin.support.GrailsUnitTestMixin
import spock.lang.Specification

import org.codehaus.groovy.grails.commons.cfg.ConfigurationHelper

@TestMixin(GrailsUnitTestMixin)
class ConfigSpec extends Specification {

    void "test prod config"() {
        def configSlurper = ConfigurationHelper.getConfigSlurper('production',null)
        def configObject = configSlurper.parse(grailsApplication.classLoader.loadClass(grailsApplication.CONFIG_CLASS))

        expect:
        configObject.config.url == "http://prod.lan"
    }

    void "test dev config"() {
        def configSlurper = ConfigurationHelper.getConfigSlurper('development',null)
        def configObject = configSlurper.parse(grailsApplication.classLoader.loadClass(grailsApplication.CONFIG_CLASS))

        expect:
        configObject.config.url == "http://local"
    }

    void "test grailsApplication config"() {
        expect:
        grailsApplication.config.config.url == "http://test.lan"
    }

    void "test Holders config"() {
        expect:
        grails.util.Holders.config.config.url == "http://test.lan"
    }

}

答案 1 :(得分:0)

签出Holdershttps://gist.github.com/mathifonseca/ab443f1502bfd9461943

import grails.util.Holders

class FooService {

     def foo() {

          def devUrl = Holders.config.url

          assert devUrl == "http://local"     
     }

}