Unit testing Grails单元测试模拟服务返回无效对象

Unit testing Grails单元测试模拟服务返回无效对象,unit-testing,grails,groovy,Unit Testing,Grails,Groovy,我正在为这个(运行良好的)Grails服务创建单元测试: class CommonCodeService { def gridUtilService def getList(def params){ def ret = null try { def res = gridUtilService.getDomainList(CommonCode, params) def rows = []

我正在为这个(运行良好的)Grails服务创建单元测试:

class CommonCodeService {

    def gridUtilService

    def getList(def params){
        def ret = null

        try {
            def res = gridUtilService.getDomainList(CommonCode, params)
            def rows = []
            def counter = 0
            res?.rows?.each{ // this is line 15
                rows << [
                        id: counter ++,
                        cell:[

                            it.key,  
                            it.value  
                        ]
                ]
            }

            ret = [rows: rows, totalRecords: res.totalRecords, page: params.page, totalPage: res.totalPage]

        } catch (e) {
            e.printStackTrace()
            throw e
        }

        return ret
    }

}
这是我的(不工作)单元测试:

import grails.test.mixin.TestFor
import grails.test.mixin.Mock
import com.emerio.baseapp.utils.GridUtilService

@TestFor(CommonCodeService)
@Mock([CommonCode,GridUtilService])
class CommonCodeServiceTests {

    void testGetList() {
        def rowList = [new CommonCode(key: 'value', value: 'value')]
        def serviceStub = mockFor(GridUtilService)
        serviceStub.demand.getDomainList {Map p -> [rows: rowList, totalRecords: rowList.size(), page:1, totalPage: 1]}
        service.gridUtilService = serviceStub.createMock()
        service.getList() // this is line 16
    }

}
当我运行测试时,它显示异常:

No such property: rows for class: com.emerio.baseapp.CommonCodeServiceTests
groovy.lang.MissingPropertyException: No such property: rows for class: com.emerio.baseapp.CommonCodeServiceTests
    at com.emerio.baseapp.CommonCodeService.getList(CommonCodeService.groovy:15)
    at com.emerio.baseapp.CommonCodeServiceTests.testGetList(CommonCodeServiceTests.groovy:16)

模拟的
GridUtilService
似乎返回
CommonCodeServiceTests
实例,而不是
Map
。我的单元测试有什么问题?

看起来您需要修复模拟的
getDomainList()
调用的方法参数。您将其命名为
Map m
,但它可能需要是
Class c,Map m

闭包参数必须与模拟方法的数量和类型匹配,否则您可以在主体中随意添加任何内容


为什么在辩论中失利的表现如此,这是一个难解之谜。我可以用我自己的精简类复制你的问题。我还发现,当param未命中时,方法调用返回的类型是测试类的闭包,至少在我的简单示例中,可以对该类进行
.call()
,以获得所需的(模拟的)结果。我不确定这种行为是否支持某种功能或是一个bug。这确实令人困惑。

是的,它很有效!我需要为闭包定义与mock方法中相同的参数。谢谢
No such property: rows for class: com.emerio.baseapp.CommonCodeServiceTests
groovy.lang.MissingPropertyException: No such property: rows for class: com.emerio.baseapp.CommonCodeServiceTests
    at com.emerio.baseapp.CommonCodeService.getList(CommonCodeService.groovy:15)
    at com.emerio.baseapp.CommonCodeServiceTests.testGetList(CommonCodeServiceTests.groovy:16)