Grails - 如何在控制器测试时在控制器中实例化服务

Grails - How to instantiate service in Controller when doing controller testing

我正在控制器中使用服务。我正在为控制器编写单元测试,但无法在控制器中实例化服务。它总是 null.

如果我在控制器测试 class 中使用 new 运算符实例化服务。服务class中的服务未实例化。

如何在测试中实例化服务class?

你可以让 Spring 为你做。

依赖于服务的控制器:

// grails-app/controllers/demo/DemoController.groovy
package demo

class DemoController {
    def helperService

    def index() {
        def answer = helperService.theAnswer
        render "The answer is ${answer}"
    }
}

服务:

// grails-app/services/demo/HelperService.groovy
package demo

class HelperService {

    def getTheAnswer() {
        42
    }
}

注入服务的单元测试:

// src/test/groovy/demo/DemoControllerSpec.groovy
package demo

import grails.test.mixin.TestFor
import spock.lang.Specification

@TestFor(DemoController)
class DemoControllerSpec extends Specification {

    static doWithSpring = {
        helperService HelperService
    }

    void "test service injection"() {
        when:
        controller.index()

        then:
        response.text == 'The answer is 42'
    }
}

注入虚假服务版本的单元测试:

// src/test/groovy/demo/AnotherDemoControllerSpec.groovy
package demo

import grails.test.mixin.TestFor
import spock.lang.Specification

@TestFor(DemoController)
class AnotherDemoControllerSpec extends Specification {

    static doWithSpring = {
        helperService DummyHelper
    }

    void "test service injection"() {
        when:
        controller.index()

        then:
        response.text == 'The answer is 2112'
    }
}

class DummyHelper {

    def getTheAnswer() {
        2112
    }
}