【问题标题】:Grails String.encodeAsBase64() Fails in Spock TestsGrails String.encodeAsBase64() 在 Spock 测试中失败
【发布时间】:2015-06-13 04:56:28
【问题描述】:

当我在 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()(见:http://mrhaki.blogspot.com/2009/11/groovy-goodness-base64-encoding.html),那么为什么这在单元测试中不起作用呢?

【问题讨论】:

    标签: unit-testing grails spock


    【解决方案1】:

    而不是

    "Blah".encodeAsBase64()
    

    你需要

    "Blah".encodeBase64()
    

    没有“作为”

    【讨论】:

    • 只是出于好奇,方法 encodeAsBase64 来自哪里? Grails 必须将其添加到元类中。任何人都可以链接到它的文档吗?感谢您的帮助!
    • Grails encodeAsXXX 方法来自编解码器,在 grails.github.io/grails-doc/2.4.x/ref/Plug-ins/codecs.html 中进行了描述
    【解决方案2】:

    您还可以为您正在使用的方法添加一个 mockCodec。

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

    【讨论】:

      【解决方案3】:

      这行得通,但我感觉很糟糕。当然必须有更清洁的解决方案:

      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"
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-02-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-11-16
        • 2021-12-06
        • 1970-01-01
        相关资源
        最近更新 更多