我正在为此(工作正常)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
. 我的单元测试有什么问题?