Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/sql-server-2008/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Unit testing Grails String.encodeAsBase64()在Spock测试中失败_Unit Testing_Grails_Spock - Fatal编程技术网

Unit testing Grails String.encodeAsBase64()在Spock测试中失败

Unit testing Grails String.encodeAsBase64()在Spock测试中失败,unit-testing,grails,spock,Unit Testing,Grails,Spock,当我在Grails中运行这段代码时,它工作得很好 String getLoginToken() { generatePassword() passwordExpired = false [email, password].join(',').encodeAsBase64() } 但是,此Spock测试失败 def "test getLoginToken"() { setup: String email = "bacon@eggs.edu" Per

当我在Grails中运行这段代码时,它工作得很好

String getLoginToken() {
    generatePassword()
    passwordExpired = false
    [email, password].join(',').encodeAsBase64()
}
但是,此Spock测试失败

def "test getLoginToken"() {
    setup:
    String email = "bacon@eggs.edu"
    Person person = new Person(email: email)

    when:
    String token = person.getLoginToken()

    then:
    token.decodeBase64() == "$email,$person.password"
}
除了以下例外

| Failure:  test getLoginToken(com.campuscardtools.myphotoid.PersonSpec)
|  groovy.lang.MissingMethodException: No signature of method: java.lang.String.encodeAsBase64() is applicable for argument types: () values: []
Possible solutions: decodeBase64()
    at com.campuscardtools.myphotoid.Person$$EPFScS6i.getLoginToken(Person.groovy:140)
    at com.campuscardtools.myphotoid.PersonSpec.test getLoginToken(PersonSpec.groovy:68)

我的理解是Groovy在String类上提供了encodeAsBase64()(请参见:),那么为什么在单元测试中这不起作用呢?

这是可行的,但我觉得这是个糟糕的黑客。当然,必须有更清洁的解决方案:

def cleanup () {
    String.metaClass = null
}

def "test getLoginToken"() {
    setup:
    String email = "bacon@eggs.edu"
    Person person = new Person(email: email)
    String encoded = null

    and:
    String.metaClass.encodeAsBase64 {
        encoded = delegate
        return delegate
    }

    when:
    String token = person.getLoginToken()

    then:
    token == "$email,$person.password"
    encoded == "$email,$person.password"
}
而不是

"Blah".encodeAsBase64()
你需要

"Blah".encodeBase64()

如果没有'As'

,您还可以为正在使用的方法包含一个mockCodec

and: "add the Base64 codec"
    mockCodec(org.codehaus.groovy.grails.plugins.codecs.Base64Codec)

出于好奇,encodeAsBase64方法来自哪里?Grails必须将其添加到元类中。有人能链接到它的文档吗?谢谢你的帮助!Grails
encodeAsXXX
方法来自编解码器,在