grails - groovy grails 中的内部依赖注入(inject)

标签 grails groovy spock

在 groovy/grails 中,我使用 SPOC 和 junit 框架进行单元测试,我想注入(inject) 模拟数据库服务 用于单元测试测试 Controller 规范

import org.springframework.beans.factory.annotation.Autowired
import grails.testing.web.controllers.ControllerUnitTest
import spock.lang.Specification

//Controller
class TestController {

    @Autowired
    BusinessService businessService

    def callServiceMethod() {

        businessService.callBusinessServiceMethod()
    }
}

//Business Service
class BusinessService {

    @Autowired
    DatabaseService databaseService

    def callBusinessServiceMethod() {
        databaseService.callDBServiceMethod()
    }
}

//Database service
class DatabaseService {


    def callDBServiceMethod() {

    }

}

//Unit test
class TestControllerSpec extends Specification implements ControllerUnitTest<TestController> {

    //Need to pass the MockDatabaseService instead of DatabaseService

    def "test "(){

        controller.callServiceMethod()
    }
}

//Mocked DatabaseService
class MockDatabaseService {

    def callDBServiceMethod() {

        //Mock method
    }

}

我正在尝试在 TestControllerSpec 中注入(inject) DatabaseService 的 Mock,我们如何实现它?

最佳答案

您可以执行以下操作

...
//Controller
class TestControllerSpec {

    @Autowired
    BusinessService businessService

    // let the unit test framework init the service
    static doWithSpring = {
        databaseService(DatabaseService)
    }


    // this runs in the beginning for all unit tests
    def setup(){
         // get the instance of the service and manually inject it.
         businessService.databaseService = Holders.grailsApplication.mainContext.getBean("databaseService")
    }

    def callServiceMethod() {

        businessService.callBusinessServiceMethod()
    }
}

关于grails - groovy grails 中的内部依赖注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52552745/

相关文章:

android - 无法在空对象上获取属性 'kotlinOutputDir' - Kotlin 和 Spock

javascript - 正确地将 Groovy 列表传递给 GSP 中的 Javascript 代码

java - Spock - 模拟存储库方法 save() 给出 NullPointerException

groovy - Groovy 特征的菱形继承(钻石问题)

java - 如何在 spock 或 hamcrest 中创建自定义域特定断言/匹配器

gradle - 无法在单独的sourceSet中配置Gradle中的Spock测试

session 变量在 Grails 中不起作用

eclipse - Grails项目:运行方式(在服务器上运行)vs运行方式(run-app)

grails - grails 2或更高版本的log4j配置,对dailyRollOver不起作用

jenkins - 将整个 Jenkins 阶段提取到共享库?