问题
I would like to mock a domain with everything as usual (mockDomain(Class)
), but I would like to overwrite one of the domain's methods (beforeDelete
to be specific) with custom logic just for that one unit test.
How can this be achieved?
回答1:
You can override the beforeDelete method on your domain class using 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--
Deleting 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--
Do not touch me
回答2:
Mock the domain class with mockDomain
as usual, then mock the beforeDelete
closure with mockFor
in that one specific unit test. For example:
void testDelete() {
mockDomain(MyDomainClass)
def myDomainClassControl = mockFor(MyDomainClass)
myDomainClassControl.demand.beforeDelete(1..1) { -> println "hello world" }
... // test delete
myDomainClassControl.verify()
}
来源:https://stackoverflow.com/questions/5887177/how-can-i-overwrite-a-methods-logic-when-using-mockdomain-in-grails