域类 insertBefore 的 Grails 单元测试
如何使用 Grails 中的单元测试来测试 Groovy 域类的 initBefore 方法?
我创建了虚拟对象,但在调用 myObject.save() 且 save 在测试环境中不可用之前,不会调用 beforeInsert 方法。
编辑:它是一个单元测试。没有错误,但是没有调用beforeInsert方法
How can I test the initBefore method of Groovy Domain-Classes with a unit test in Grails?
I created the dummy object but the beforeInsert-method is not called until myObject.save() is invoked and save is unavailable in the testing environments.
Edit: its a unit-test. there is no error, but the method beforeInsert is not called
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
beforeInsert 在单元测试期间被调用。我可以在我的测试中验证这一点。需要考虑以下几点:
beforeInsert is called during unit tests. I can verify this in my tests. A couple things to consider:
您想测试 beforeInsert 方法是否被调用或者 beforeInsert 的逻辑是否正确?
如果您想测试 beforeInsert 是否被调用,测试类应该扩展 GrailsUnitTestCase。这样做应该为您提供模拟功能并添加所有方法,例如 save() 和 validate()。您可以在执行 save() 时验证模拟对象是否调用了 beforeInsert 方法。
如果您正在测试 beforeInsert 的逻辑,那么您不需要模拟它。您可以像其他单元测试一样创建对象并测试逻辑。
希望这有帮助。
Do you want test if the beforeInsert method is being called or the logic of beforeInsert is correct?
If you want to test if beforeInsert is being called the test class should extend the GrailsUnitTestCase. Do so should give you mocking capabilities and add all the methods like save() and validate(). You can verify if the mocked object called the beforeInsert method or not when you do a save().
If you are testing the logic of beforeInsert then you don't need to mock it. You can create the object and test the logic just like other unit test.
Hope this helps.
只需创建一个域对象并 save() 它即可。然后检查“beforeInsert”是否操纵了您的对象。
save() 在测试环境中可用。调用 myDomainobject.save() 时请显示您的堆栈跟踪
Just creat a domain object and save() it. Then check whether or not the "beforeInsert" manipulated your Object.
save() is available in the testing enviroments. Please show your Stacktrace when calling myDomainobject.save()
我有同样的问题!在GORM中(至少直到当前版本)save方法并不会因为被调用而立即生效!如果您希望它立即生效,您需要指定
flush:true
,如domain.save(flush:true)
。它在这里说http://grails.org/doc/2.2。 x/ref/Domain%20Classes/save.html
要回答您的问题,在保存持久(保存生效)之前不会调用beforeInsert,因此您应该使用flush调用save来测试
beforeInsert
和beforeUpdate< /代码> 方法。
希望这有帮助!
I had the same exact problem! In GORM (at least until the current version) the save method does not take effect immediately just because it is called! If you want it to take effect right away you need to specify
flush:true
like thisdomain.save(flush:true)
.it says here http://grails.org/doc/2.2.x/ref/Domain%20Classes/save.html
To answer your question, beforeInsert is not called until the save is persisted (save takes effect) therefor you should invoke save with flush to test
beforeInsert
andbeforeUpdate
methods.Hope this helps!