【发布时间】:2016-06-12 22:54:36
【问题描述】:
我有一个类,其方法名为 execute()。在一些 Spock 单元测试中,我模拟了 execute 方法并给它一个模拟闭包,如下所示:
def setup () {
rule = new DynamicRule ()
}
def "test default execution " (){
given : "basic AORule "
def mockres
rule.metaClass.execute = {-> mockres = "did nothing"} //mock the action
def res = rule.execute()
expect : "execute should do nothing "
mockres == "did nothing"
}
如果我运行此测试,它会失败。在想法编辑器中,它将模拟闭包显示为带下划线,但下一行的 rule.execute() 不是 - 所以它可以看到该方法。
如果我为此更改此测试:
rule.metaClass.execute2 = {-> mockres = "did nothing"} //mock the action
def res = rule.execute2()
然后测试通过。
在 Spock 之外,我只运行了一个简单的 Groovy 脚本并进行了方法重载,并且按我的预期正常工作,并且该方法被闭包模拟了
class A {
def execute () {
println "thing"
}
}
def c = new A()
def res
c.execute()
c.metaClass.execute = {-> res =2 ; println "modified thing "; }
c.execute ()
println "res = "+ res
为什么在 Spock 测试中没有发生同样的情况?
单元存根如何为 Spock 正确测试闭包?
这个修改后的版本测试成功:
def "test default execution " (){
given : "basic AORule "
def mockres
def stub = new StubFor(AORule)
stub.demand.execute { mockres = "did nothing" }
// rule.metaClass.execute = {-> mockres = "did nothing"} //mock the action
// def res = rule.execute()
expect : "execute should do nothing "
stub.use {
rule.execute()
mockres == "did nothing"
}
}
为什么简单的每个元类在 Spock 中不起作用?
【问题讨论】:
-
如果我使用
rule = new Object()而不是new DynamicRule()执行您的测试(因为您没有提供),它可以工作吗? -
我想 DynamicRule 有一个名为
execute的私有方法?
标签: unit-testing groovy spock stub