我正在运行 Grails 2.1.1,并且正在寻找一种方法来获取在测试环境中运行时在生产中设置的变量的值。配置文件:
development {
config.url = "http://local"
}
test {
config.url = "http://test.lan"
}
production {
config.url = "http://prod.lan"
}
我知道获取配置变量的唯一方法是 grailsApplication.config.url
我正在运行 Grails 2.1.1,并且正在寻找一种方法来获取在测试环境中运行时在生产中设置的变量的值。配置文件:
development {
config.url = "http://local"
}
test {
config.url = "http://test.lan"
}
production {
config.url = "http://prod.lan"
}
我知道获取配置变量的唯一方法是 grailsApplication.config.url
标准配置设置只查看当前环境。Holders
与当前配置相同grailsApplication
。你必须再次啜饮配置。尝试使用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"
}
}
查看持有人:https ://gist.github.com/mathifonseca/ab443f1502bfd9461943
import grails.util.Holders
class FooService {
def foo() {
def devUrl = Holders.config.url
assert devUrl == "http://local"
}
}