I have a User class like this:
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 class like this:
package com.grailsinaction
class Post {
String content
Date dateCreated;
static constraints = {
content(blank:false)
}
static belongsTo = [user:User]
}
And I write an integration test like this:
//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())
}
And I run using grails test-app -integration, then I get a error like this :
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
Where I went wrong?
My guess is that the
save()method is returning null. Try this instead:According to the documentation:
So it’s possible that you should be looking at what’s going wrong in validation… do you need to specify that some of the fields are optional, for example? (I’m not a Grails developer – just trying to give you some ideas.)