2011-08-27 21 views
0

我有一個User類是這樣的:獲取NullPointerException異常,當我運行這段代碼

package com.grailsinaction 

class User { 
    String userId 
    String password; 
    Date dateCreated 
    Profile profile 
    static hasMany = [posts : Post] 
     static constraints = { 
     userId(size:3..20, unique:true) 
     password(size:6..8, validator : { passwd,user -> 
          passwd!=user.userId 
         }) 
     dateCreated() 
     profile(nullable:true) 
     } 
    static mapping = { 
     profile lazy:false 
    } 
} 

Post類是這樣的:

package com.grailsinaction 

class Post { 
    String content 
    Date dateCreated; 
    static constraints = { 
    content(blank:false) 
    } 
    static belongsTo = [user:User] 
} 

我寫這樣一個集成測試:

//other code goes here 
void testAccessingPost() { 
     def user = new User(userId:'anto',password:'adsds').save() 
     user.addToPosts(new Post(content:"First")) 
     def foundUser = User.get(user.id) 
     def postname = foundUser.posts.collect { it.content } 
     assertEquals(['First'], postname.sort()) 
    } 

而我運行使用grails test-app -integration,然後我得到一個錯誤r像這樣:

Cannot invoke method addToPosts() on null object 
java.lang.NullPointerException: Cannot invoke method addToPosts() on null object 
    at com.grailsinaction.PostIntegrationTests.testAccessingPost(PostIntegrationTests.groovy:23 

我哪裏出錯了?

回答

1

我的猜測是save()方法返回null。試試這個:

def user = new User(userId:'anto',password:'adsds') 
user.save() // Do you even need this? 
user.addToPosts(new Post(content:"First")) 

根據the documentation

的保存,如果驗證失敗,並沒有保存的情況下,如果該實例本身成功的方法返回null。

所以有可能你應該看看驗證中出了什麼問題......你是否需要指定某些字段是可選的,例如? (我不是Grails開發人員 - 只是想給你一些想法。)

+0

不是Grails開發人員而是C#開發人員;);)這工作,我犯了一個錯誤,違反了驗證:D感謝您的答案! –

+1

@螞蟻的它*是*可能知道多種技術 –

1

快速修復:您的密碼必須在6到8個字符之間(檢查您的約束字段)。

一個愚蠢的想法,充其量是一個最大的密碼大小(最終他們應該被散列,並將不會與原始密碼相似)。

在附註中,我可以建議Grails的權威指南嗎?

+0

我也有那個書:D –

相關問題