我有一個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
我哪裏出錯了?
不是Grails開發人員而是C#開發人員;);)這工作,我犯了一個錯誤,違反了驗證:D感謝您的答案! –
@螞蟻的它*是*可能知道多種技術 –