grails - 集成测试用例中的模拟 Grails 配置

标签 grails grails-controller

如何在集成测试用例中模拟 Grails 配置?

考虑以下场景

MyController.groovy

def save() {
    baseLink = Holders.getFlatConfig()["grails.test.base.link"]
    if (!baseLink) {
        response.status = HttpStatus.NOT_ACCEPTABLE.value
        respond([message: "Configuration not found."])
        return
    }
    // Some Code
}

MyControllerIntegrationSpec.groovy
def save() {
    baseLink = Holders.getFlatConfig()["grails.test.base.link"]
    if (!baseLink) {
        response.status = HttpStatus.NOT_ACCEPTABLE.value
        respond([message: "Configuration not found."])
        return
    }
    // Some Code
}


def setup() {
    //Some Setup Code
    //Update configuration
    grailsApplication.config["grails.test.base.link"] = true
}

void "Configuration not found"() {
    when: ""
    myController.save()

    then: "Configuration not found"
    controller.response.json["message"] == "Configuration not found."
    controller.response.status == HttpStatus.NOT_ACCEPTABLE.value
}    

void "Configuration found"() {
    when: ""
    myController.save()

    then: "Configuration found"
    //some code
}

最佳答案

假设您知道为什么要在集成测试中模拟 grails 应用程序,我的建议是使用 grailsApplication 的 DI .你有什么理由使用baseLink = Holders.getFlatConfig()["grails.test.base.link"]而不是 grailsApplication.config.grails.test.base.link ?你用的是什么grails版本?

当使用 grailsApplication 作为 Controller 的依赖项时,您可以在测试中注入(inject)它:

def setup() {
  myController.grailsApplication = [config: [grails: [test: [base: [link: true]]]]]
}

void "Configuration found"() {
  when: ""
  myController.save()

  then: "Configuration found"
  //some code
}  

关于grails - 集成测试用例中的模拟 Grails 配置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29986315/

相关文章:

grails - grails-在gsp上显示验证错误消息

tomcat - 为什么 grails run-war 拒绝远程连接?

grails - 为Heroku Grails应用程序配置根URL

grails - 在 Controller 中调用update()后,Grails会更改默认显示 View

grails - 由于缺少默认c'tor,bean的实例化失败

grails - 生成的 Controller 的更新方法中的version参数是什么

grails - Grails:范围的不兼容字符串:起始字符串长于结束字符串

testing - Grails:运行 test-app grails 卸载 lesscss 插件

java - 我如何在 spock 测试中使用 redisService 我需要清理 redis 数据库以进行设置和清理

grails - Grails从1.2.2升级到支持多个数据源的版本