我想像往常一样使用所有内容(mockDomain(Class)
)来模拟一个域,但我想用一个自定义逻辑覆盖一个域的方法(beforeDelete
是特定的)单元测试。
如何实现这一目标?
答案 0 :(得分:2)
您可以使用Groovy metaClass覆盖域类的beforeDelete方法。
域类:
class Person {
String name
boolean deleted
def beforeDelete() {
println "Deleting Person ${id}"
deleted = true
return false
}
}
单元测试:
void testBeforeDelete() {
mockDomain(Person)
def p = new Person(name:"test")
p.save()
assertEquals false, p.deleted
p.delete()
assertEquals true, p.deleted
}
- 来自testBeforeDelete的输出 -
删除第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
}
- 来自testBeforeDeleteOverrideBeforeDelete -
的输出别碰我
答案 1 :(得分:1)
照常使用mockDomain
模拟域类,然后在该特定单元测试中使用beforeDelete
模拟mockFor
闭包。例如:
void testDelete() {
mockDomain(MyDomainClass)
def myDomainClassControl = mockFor(MyDomainClass)
myDomainClassControl.demand.beforeDelete(1..1) { -> println "hello world" }
... // test delete
myDomainClassControl.verify()
}