grails - Grails集成测试:失败...无法在空对象上调用方法addToPosts()

标签 grails groovy

: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"
   }
}

最佳答案

如果验证失败,则save()返回null,并且“www.geeee.com”不是有效的URL。它将与“http://www.geeee.com”一起使用。

但是您应该将创建和保存分为两个步骤,以便可以检查它:

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)

关于grails - Grails集成测试:失败...无法在空对象上调用方法addToPosts(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5762701/

相关文章:

grails - 没有读取外部配置值

java - 将 SoapUI 插件与 Jenkins 集成

常规 ^ 运算符

email - 如何获取当前 Jenkins 用户的电子邮件地址以在 groovy 脚本中使用

Grails Spring Security-登录后始终重定向到特定页面吗?

Grails:动态调用另一个操作

css - 使用 Grails 资源插件 1.2.7 破坏的 CSS 文件中的 URL

groovy - Spock框架: what is the purpose of Spies vs.使用真实对象还是模拟?

grails - MissingPropertyException:没有此类属性:*用于类:java.util.LinkedHashMap $ Entry

Grails 脚手架显示的列数少于域