Инъекция внутренней зависимости в пазухах - PullRequest
0 голосов
/ 28 сентября 2018

В groovy / grails я использую SPOC и инфраструктуру junit для модульного тестирования и хочу внедрить MockDatabaseService для модульного теста TestControllerSpec

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
    }

}

Я пытаюсь внедрить Mock for DatabaseService в TestControllerSpec, как мы можем этого достичь?

1 Ответ

0 голосов
/ 28 сентября 2018

Вы можете сделать следующее

...
//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()
    }
}
...