我有一个这样的 Controller :

class NotificationApiController { 
 
    def countService 
 
    def getCount() { 
        def results = countService.getCount() 
 
        render results as JSON 
    } 
} 

Controller 测试如下:
Closure doWithSpring() {{ -> 
        countService(CountService) 
    }} 
 
CountService countService 
 
def setup() { 
} 
 
def cleanup() { 
} 
 
void "test getCount method"() { 
        given: 
        def countService = Mock(CountService) { 
            1 * getCount(_) >> [count: 2] 
        } 
        when: 
        def y = controller.getCount() 
 
        then: 
        y == [count: 2] 
    } 

看来它总是调用在 Closure doWithSpring() 中注入(inject)的实际 CountService,而不是我的模拟 countService,但没有 Closure doWithSpring() 的定义...,我会收到此错误
Cannot invoke method getCount() on null object 
java.lang.NullPointerException: Cannot invoke method getCount() on null object 

4.0 中的单元测试文档非常有限,我不确定我应该如何做。我在 Grails 2.3 或 3.3 中看到了一些示例。版本,但它们似乎都不适合我,主要是由于我猜 Spock 和 Mixin 框架的差异。关于如何做到这一点的任何建议?

请您参考如下方法:

您省略了一些可能会影响推荐的细节,但项目位于 https://github.com/jeffbrown/chrisjiunittest显示了解决此问题的 1 种方法。

https://github.com/jeffbrown/chrisjiunittest/blob/a59a58e3b6ed6b47e1a8104f3e4d3bdb138abacc/src/test/groovy/chrisjiunittest/NotificationApiControllerSpec.groovy

package chrisjiunittest 
 
import grails.testing.web.controllers.ControllerUnitTest 
import spock.lang.Specification 
 
class NotificationApiControllerSpec extends Specification implements ControllerUnitTest<NotificationApiController> { 
 
    void "test something"() { 
        setup: 
        // whether or not this is the right thing to do 
        // depends on some other factors, but this is 
        // an example of one approach... 
        controller.countService = Mock(CountService) { 
            getCount() >> [count: 2] 
        } 
 
        when: 
        controller.getCount() 
 
        then: 
        response.json == [count: 2] 
    } 
} 

另外一个选项:
package chrisjiunittest 
 
import grails.testing.web.controllers.ControllerUnitTest 
import spock.lang.Specification 
 
class NotificationApiControllerSpec extends Specification implements ControllerUnitTest<NotificationApiController> { 
 
    Closure doWithSpring() { 
        // whether or not this is the right thing to do 
        // depends on some other factors, but this is 
        // an example of one approach... 
        { -> 
            countService MockCountService 
        } 
    } 
 
    void "test something"() { 
        when: 
        controller.getCount() 
 
        then: 
        response.json == [count: 2] 
    } 
} 
 
class MockCountService { 
    Map getCount() { 
        [count: 2] 
    } 
} 


评论关闭
IT序号网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!