具有問題每個實例的metaClass方法重寫不工作常規按預期在斯波克測試
我有方法()的一類稱爲執行。在一些spock單元測試中,我假設執行方法並給它一個模擬關閉像這樣
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()
然後測試通過。
外斯波克的,我只是進行了簡單的Groovy腳本,並做了方法重載和正常工作的ID預期和方法嘲笑了與關閉
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"
}
}
爲什麼沒有每元類FRIG工作簡單的斯波克?我在這裏不理解的東西
如果我用'rule = new Object()'而不是'new DynamicRule()'來執行測試(因爲你沒有提供它),它的工作原理是什麼? –
我想DynamicRule有一個名爲'execute'的私有方法? –