2016-02-29 71 views
2

具有問題每個實例的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工作簡單的斯波克?我在這裏不理解的東西

+0

如果我用'rule = new Object()'而不是'new DynamicRule()'來執行測試(因爲你沒有提供它),它的工作原理是什麼? –

+0

我想DynamicRule有一個名爲'execute'的私有方法? –

回答

1

這是Groovy> = 2.4.3的一個公開問題,在這裏:GROOVY-7368

在重寫帶有元類的私有方法時存在一個錯誤。

+0

這就解釋了 - 我以爲我是愚蠢的,很高興知道幾個彈珠留在舊坦克 - 謝謝 - 我有一個解決方法(可能更好)使用存根(stub),所以我現在在這裏現在 –

+0

@WILLIAMWOODMAN如果這個答案對你有幫助,請不要接受它;-) –

+0

完成 - 之前沒有看到過這個選項 - 接受 –