How can I rewrite method logic when using mockDomain in grails?

I would like to mock the domain with everything as usual ( mockDomain(Class) ), but I would like to overwrite one of the domain methods ( beforeDelete for specific) with custom logic for this unit test only.

How can this be achieved?

+2
source share
2 answers

You can override the beforeDelete method in your domain class using the Groovy metaClass.

Domain Class:

 class Person { String name boolean deleted def beforeDelete() { println "Deleting Person ${id}" deleted = true return false } } 

Unit Test:

 void testBeforeDelete() { mockDomain(Person) def p = new Person(name:"test") p.save() assertEquals false, p.deleted p.delete() assertEquals true, p.deleted } 

- output from testBeforeDelete -

Removing a person 1

 void testBeforeDeleteOverrideBeforeDelete() { mockDomain(Person) Person.metaClass.'static'.beforeDelete = {println 'Do not touch me'} def p = new Person(name:"test") p.save() assertEquals false, p.deleted p.delete() assertEquals true, p.deleted } 

- output from testBeforeDeleteOverrideBeforeDelete -

Dont touch me

+2
source

Highlight the domain class with mockDomain as usual, then scoff at closing beforeDelete with mockFor in this particular unit test. For example:

 void testDelete() { mockDomain(MyDomainClass) def myDomainClassControl = mockFor(MyDomainClass) myDomainClassControl.demand.beforeDelete(1..1) { -> println "hello world" } ... // test delete myDomainClassControl.verify() } 
+1
source

All Articles