开发者

Grails Integration test: Failure...Cannot invoke method addToPosts() on null object

开发者 https://www.devze.com 2023-02-28 00:47 出处:网络
:D I was following a tutorial in a book, and I did follow it thoroughly. However, come the part where I am supposed to write an integration test, it suddenly failed saying: Cannot invoke method addToP

:D I was following a tutorial in a book, and I did follow it thoroughly. However, come the part where I am supposed to write an integration test, it suddenly failed saying: Cannot invoke method addToPosts() on null object right after I ran the test. I wonder, what could be wrong... :| Please help! :) Below is the code for the test:

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()
}

Here is the user class:

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:开发者_StackOverflow社区true, nullable: true)
      profile (nullable: true)
   }
}

Here is the Post class:

class Post {

   String content
   Date dateCreated

   static constraints = {
      content (blank:false)
   }

   static belongsTo = [user:User]
   static hasMany = [tags:Tag]

   static mapping = {
      sort dateCreated: "desc"
   }
}


save() returns null if validation fails, and "www.geeee.com" isn't a valid URL. It would work with "http://www.geeee.com".

But you should split the creation and saving into 2 steps so you can check it:

def user = new User(userID: 'joemillan', password:'youaretheonly',
                    homepage: 'www.geeee.com')
user.save()
assertFalse user.hasErrors()

or use failOnError if you are confident that that part should succeed and only want to test the other parts, e.g.

def user = new User(userID: 'joemillan', password:'youaretheonly',
                    homepage: 'www.geeee.com').save(failOnError: true)
0

精彩评论

暂无评论...
验证码 换一张
取 消