【发布时间】:2014-06-19 17:35:09
【问题描述】:
在 Spock 单元测试中,我试图测试独立于 getGithubUrlForPath 的方法 findRepositoriesByUsername 的行为,它们都属于同一个服务。
多次尝试使用metaClass 均失败:
-
String.metaClass.blarg产生错误No such property: blarg for class: java.lang.String -
service.metaClass.getGithubUrlForPath修改服务实例无效 -
GithubService.metaClass.getGithubUrlForPath修改服务类不起作用 - 尝试在测试方法设置中的
metaClass上添加/修改方法,当阻塞时,均未按预期工作
测试:
package grails.woot
import grails.test.mixin.TestFor
@TestFor(GithubService)
class GithubServiceSpec extends spock.lang.Specification {
def 'metaClass test'() {
when:
String.metaClass.blarg = { ->
'brainf***'
}
then:
'some string'.blarg == 'brainf***'
}
def 'can find repositories for the given username'() {
given:
def username = 'username'
def requestPathParts
when: 'the service is called to retrieve JSON'
service.metaClass.getGithubUrlForPath = { pathParts ->
requestPathParts = pathParts
}
service.findRepositoriesByUsername(username)
then: 'the correct path parts are used'
requestPathParts == ['users', username, 'repos']
}
}
服务:
package grails.woot
import grails.converters.JSON
class GithubService {
def apiHost = 'https://api.github.com/'
def findRepositoriesByUsername(username) {
try{
JSON.parse(getGithubUrlForPath('users', username, 'repos').text)
} catch (FileNotFoundException ex) {
// user not found
}
}
def getGithubUrlForPath(String ... pathParts) {
"${apiHost}${pathParts.join('/')}".toURL()
}
}
我已经在 groovy shell(由 grails 启动)中测试了 String.metaClass.blarg 示例,结果符合预期。
我在这里有一个根本的误解吗?我究竟做错了什么?是否有更好的方法来处理所需的测试(替换被测服务上的方法)?
【问题讨论】:
标签: grails groovy spock metaclass