2011-04-23 60 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

相关问题