加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

Grails – Spock不使用Groovy MetaClass更改为服务测试

发布时间:2020-12-14 16:22:16 所属栏目:大数据 来源:网络整理
导读:在Spock单元测试中,我试图测试独立于get GithubUrlForPath的方法findRepositoriesByUsername的行为,两者都属于同一个服务. 重复尝试使用metaClass失败: String.metaClass.blarg产生错误没有这样的属性:blarg for class:java.lang.String service.metaClas
在Spock单元测试中,我试图测试独立于get GithubUrlForPath的方法findRepositoriesByUsername的行为,两者都属于同一个服务.

重复尝试使用metaClass失败:

> String.metaClass.blarg产生错误没有这样的属性: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','repos').text)
        } catch (FileNotFoundException ex) {
            // user not found
        }
    }

    def getGithubUrlForPath(String ... pathParts) {
        "${apiHost}${pathParts.join('/')}".toURL()
    }
}

我已经测试了groovy shell中的String.metaClass.blarg示例(由grails启动),它按预期方式执行.

我在这里有一个根本的误解吗?我究竟做错了什么?有没有更好的方法来处理所需的测试(替换测试服务上的方法)?

解决方法

这就是如何编写测试以使它们通过:

def 'metaClass test'() {
    given:
        String.metaClass.blarg = { -> 'brainf***' }

    expect:
        // note blarg is a method on String metaClass 
        // not a field,invoke the method
        '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 = { String... pathParts ->
            requestPathParts = pathParts
            [text: 'blah'] // mimicing URL class
        }
        service.findRepositoriesByUsername(username)

    then: 'the correct path parts are used'
        requestPathParts == ['users','repos']
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读