集成测试用例中的Mock Grails配置

时间:2015-05-01 11:49:32

标签: grails grails-controller

如何在Integration测试用例中模拟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
}

1 个答案:

答案 0 :(得分:0)

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

当使用grailsApplication作为控制器的依赖项时,可以将其注入测试:

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

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

  then: "Configuration found"
  //some code
}