开发者

Grails unit test for domain class insertBefore

开发者 https://www.devze.com 2023-03-08 11:45 出处:网络
How can I test the initBefore method of Groovy Dom开发者_运维百科ain-Classes with a unit test in Grails?

How can I test the initBefore method of Groovy Dom开发者_运维百科ain-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


beforeInsert is called during unit tests. I can verify this in my tests. A couple things to consider:

  1. ensure you use a beforeInsert method, and not a closure. A closure will not work correctly.
  2. it is called when the object is flushed, so perhaps you are having silent save errors beforehand. In your test when you save the object do .save(flush: true, failOnError: true)


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.


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


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 this domain.save(flush:true).

it says here http://grails.org/doc/2.2.x/ref/Domain%20Classes/save.html

The save method informs the persistence context that an instance should be saved or updated. The object will not be persisted immediately unless the flush argument is used:

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 and beforeUpdate methods.

Hope this helps!

0

精彩评论

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

关注公众号