:d
我正在阅读一本书中的教程,我确实完全遵循了它。
但是,在我应该编写集成测试的部分,它突然失败说:Cannot invoke method addToPosts() on null object
在我运行测试之后。我想知道,有什么可能是错的......:请帮忙! :)下面是测试的代码:
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)
}
}
这是Post类:
class Post {
String content
Date dateCreated
static constraints = {
content (blank:false)
}
static belongsTo = [user:User]
static hasMany = [tags:Tag]
static mapping = {
sort dateCreated: "desc"
}
}
答案 0 :(得分:2)
save()
将返回null,并且“www.geeee.com”不是有效的URL。它适用于“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)