对象未在spock集成测试中保存

时间:2015-07-29 21:45:22

标签: grails groovy gorm integration-testing spock

我有一个令牌实体:

class Token {
    /**
     * Constants for various namespaces
     */
    public static final String NS_PASSWORD_RESET = "pass-reset";

    /**
     * A simple string unlimited in content that defines a scope of the token
     */
    String namespace

    /**
     * This fields holds an identifier for anything specific that the process might need 
     */
    Long identifier

    /**
     * The actual token itself
     */
    String token

    Timestamp dateCreated
    Timestamp lastUpdated
    Timestamp expiration

    static mapping = {
        autoTimestamp true
    }

    static constraints = {
    }
}

以及具有以下方法的服务类:

def creareNewToken(String ns, int timeout) {
        def token = new Token()

        token.setNamespace(ns)
        token.setToken(this.generateToken(15))

        //persist the object
        token.save(flush: true)

        return token
    }

我为服务类创建了一个集成测试:

class TokenServiceIntegrationSpec extends IntegrationSpec {

    TokenService tokenService

    def "test creareNewToken"() {
        when:
        def token = tokenService.creareNewToken(Token.NS_PASSWORD_RESET, 60)

        then:
        token instanceof Token
        token.getNamespace() == Token.NS_PASSWORD_RESET
        token.getToken().length() == 15
        token.getDateCreated() == ''
    }
}

当我执行测试时,我得到:

Failure:  test
creareNewToken(com.iibs.security.TokenServiceIntegrationSpec)
    |  Condition not satisfied:
    token.getDateCreated() == ''
    |     |                |
    |     null             false
    com.iibs.security.Token : (unsaved)
        at com.iibs.security.TokenServiceIntegrationSpec.test creareNewToken(TokenServiceIntegrationSpec.groovy:31)

这个问题可能是什么原因?看起来实际上没有保存对象,并且粗略地,也没有填充 dateCreated 。我的问题是为什么没有保存?我有许多其他测试以类似的方式构建,并且它们没有任何问题。

感谢您的任何建议。

2 个答案:

答案 0 :(得分:2)

您有两个未设置的字段(标识符和过期日期)。默认情况下,每个字段都不可为空。尝试添加:

assert token.save(...)

检查您的对象是否真的被保存。

如果您希望它们接受null作为值,则需要在约束中指定它

static constraints = { 
identifier nullable: true
expiration nullable: true 
} 

答案 1 :(得分:0)

尝试将failOnError:true添加到保存选项中,仅用于调试目的。如果没有设置字段等,结果堆栈跟踪通常会指出

def creareNewToken(String ns, int timeout) {
    def token = new Token()

    token.setNamespace(ns)
    token.setToken(this.generateToken(15))

    //persist the object
    token.save(flush: true, failOnError:true)//this will throw an error if save does not occur

    return token
}
相关问题