2011-08-27 51 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 –

相关问题