Reputation: 13801
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?
Upvotes: 0
Views: 933
Reputation:
Quick fix: your password has to be between 6 to 8 characters (check your constraints field).
A stupid idea, at best, to have a maximum size for a password (eventually they should be hashed and will bear no resemblance to the original password).
On a side note, may I suggest The Definitive Guide to Grails instead?
Upvotes: 1
Reputation: 1499800
My guess is that the save()
method is returning null. Try this instead:
def user = new User(userId:'anto',password:'adsds')
user.save() // Do you even need this?
user.addToPosts(new Post(content:"First"))
According to the documentation:
The save method returns null if validation failed and the instance was not saved and the instance itself if successful.
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.)
Upvotes: 1