2011-04-23 50 views
0

:D 我正在關注一本書中的教程,並且我完全按照它進行了。 但是,我應該寫一個集成測試的部分,它突然失敗說:Cannot invoke method addToPosts() on null object我跑了測試後。我想知道,有什麼可能是錯的......:|請幫忙! :)下面是測試代碼:Grails集成測試:失敗...無法在空對象上調用方法addToPosts()

void testFirstPost() { 
    def user = new User(userID: 'joemillan', password:'youaretheonly', 
         homepage: 'www.geeee.com').save() 

    def post = new Post (content: 'hellloo oasdo sjdosa daodkao ') 
    user.addToPosts(post) 

    assertEquals 1, User.get(user.id).posts.size() 
} 

這裏是用戶等級:

class User { 

    String userID 
    String password 
    String homepage 

    Profile profile 

    static hasMany=[posts:Post, tags:Tag] 

    static constraints = { 
     userID (unique: true, size: 6..20) 
     password (size: 6..20, validator:{password,userID-> return password !=userID.userID}) //validator = The password must not match the username. 
     homepage (url:true, nullable: true) 
     profile (nullable: true) 
    } 
} 

這裏是郵政類:

class Post { 

    String content 
    Date dateCreated 

    static constraints = { 
     content (blank:false) 
    } 

    static belongsTo = [user:User] 
    static hasMany = [tags:Tag] 

    static mapping = { 
     sort dateCreated: "desc" 
    } 
} 

回答

2

save()返回NULL如果驗證失敗,和「www.geeee.com」不是有效的網址。它將與「http://www.geeee.com」一起工作。

但是,你應該分裂的創建和保存到2個步驟,所以你可以檢查一下:

def user = new User(userID: 'joemillan', password:'youaretheonly', 
        homepage: 'www.geeee.com') 
user.save() 
assertFalse user.hasErrors() 

或使用failOnError如果你有信心,這部分應該會成功,只想要測試的其他部分,例如

def user = new User(userID: 'joemillan', password:'youaretheonly', 
        homepage: 'www.geeee.com').save(failOnError: true) 
+0

順便說一句......失敗意味着測試失敗,而錯誤與我測試的代碼有關,對嗎? – 2011-04-23 11:03:13

+0

'def user = new User(userID:'joemillan',password:'youaretheonly', homepage:'www.geeee.com')。save(failOnError:true)' 有點像我在引導教程中看到的! :D – 2011-04-23 11:08:52

+0

YAY !!!它沒有失敗了!非常感謝!! <3 – 2011-04-23 11:10:21

相關問題