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

标签 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 = []
            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
    }

}

这是协作者GridUtilService的一种方法:
import grails.converters.JSON

class GridUtilService {

    def getDomainList(Class domain, def params){
        /* some code */
        return [rows: rows, totalRecords: totalRecords, page: params.page, totalPage: totalPage]
    }
}

这是我(不起作用)的单元测试:
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

docs

The closure arguments must match the number and types of the mocked method, but otherwise you are free to add whatever you want in the body.



为什么错过参数的行为方式是一个绊脚石。我可以使用自己的精简类来复制您的问题。我还发现,发生参数缺失时,调用该方法所返回的类型是测试类的关闭,至少就我的简单情况而言,可以将其作为.call()以获得所需的(模拟的)结果。我不确定这种行为是否支持某种功能或是否有错误。这肯定令人困惑。

关于unit-testing - Grails单元测试模拟服务返回无效对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13696355/

相关文章:

java - 如何按照提供的ID顺序从列表中的条件查询中获取对象

javascript - Google 放置自动完成限制类型和隐藏键

java - Tomcat 6 Web 应用程序随时间消耗内存

spring - 在spring框架中使用JDBCTemplate

unit-testing - 如何在 pyCharm 中进行单元测试

unit-testing - 请建议一种对简单功能进行单元测试的方法

python - python (2.7) unittest 的测试描述如何修改

c# - 错误单元测试 webapi Controller

java - Java 8 是否支持插值

Java/GPars - 我的线程池似乎得到 "clogged"