在 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/