我正在为此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/