2011-08-27 17 views
0

を実行したときにNullPointerExceptionを取得する私はこのようなUserクラスがあります。私はこのコード

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を使用して実行し、その後エラーが発生しますこのように:

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#開発者;);)これが動作し、私は間違いを犯して検証に違反しました。 –

+1

@Ant's it *は複数の技術を知ることができます –

1

クイックフィックス:パスワードは6〜8文字の間でなければなりません。

愚かなアイデアは、せいぜいパスワードの最大サイズを持つことになります(最終的にハッシュして元のパスワードと似ていないはずです)。

代わりに、Grailsの定型ガイドをお勧めしますか?

+0

ああ私もその本を持っています:D –

関連する問題