2010-07-13 74 views
2

我不知道如何使用綁定與閉包在grooy.I寫了一個測試代碼,並在運行時,它說,缺少方法setBinding作爲參數傳遞的閉包。綁定和關閉groovy

void testMeasurement() { 
    prepareData(someClosure) 
} 
def someClosure = { 
    assertEquals("apple", a) 
} 


    void prepareData(testCase) { 
    def binding = new Binding() 
    binding.setVariable("a", "apple") 
    testCase.setBinding(binding) 
    testCase.call() 

    } 

回答

2

這對我的作品使用Groovy 1.7.3:

someClosure = { 
    assert "apple" == a 
} 
void testMeasurement() { 
    prepareData(someClosure) 
} 
void prepareData(testCase) { 
    def binding = new Binding() 
    binding.setVariable("a", "apple") 
    testCase.setBinding(binding) 
    testCase.call() 
} 
testMeasurement() 

在此腳本示例中,setBinding呼叫設定在腳本a結合(如你所看到的from the Closure documentation,沒有setBinding呼叫)。所以setBinding通話後,你可以調用

println a 

,它會打印出「蘋果」

因此,要做到這一點的班,你可以設置委託封閉(封閉將恢復這代表當一個屬性無法在本地找到),像這樣:

class TestClass { 
    void testMeasurement() { 
    prepareData(someClosure) 
    } 

    def someClosure = { -> 
    assert "apple" == a 
    } 

    void prepareData(testCase) { 
    def binding = new Binding() 
    binding.setVariable("a", "apple") 
    testCase.delegate = binding 
    testCase.call() 
    } 
} 

它應該從委託類搶值來回a(在這種情況下,結合)

This page here去的,而不是使用Binding對象通過委託的使用和變量在瓶蓋

事實上的範圍,你應該能夠使用一個簡單的地圖,像這樣:

void prepareData(testCase) { 
    testCase.delegate = [ a:'apple' ] 
    testCase.call() 
    } 

希望它可以幫助!

+0

添加到我的答案 – 2010-07-14 09:27:06

0

這真是奇怪的現象:除去someClosure聲明前面的「高清」使得JDK1.6的Groovy腳本工作:1.7.3

更新:這是貼在上面的答案。我的錯誤重複它。 更新:爲什麼它有效?如果沒有def,第一行將被視爲一個屬性賦值,它調用setProperty並使綁定中的變量可用,稍後解決。 一個高清應該曾作爲以及每個(http://docs.codehaus.org/display/GROOVY/Groovy+Beans

someClosure = { 
    assert "apple", a 
    print "Done" 
} 

void testMeasurement() { 
    prepareData(someClosure) 
} 

void prepareData(testCase) { 
    def binding = new Binding() 
    binding.setVariable("a", "apple") 
    testCase.setBinding(binding) 
    testCase.call() 
} 
testMeasurement() 

我可以重現你提到通過下面的代碼的問題。但我不確定這是否是使用Binding的正確方法。 GroovyDocs表示,他們將與腳本一起使用。你能否指出我的文檔暗示了封閉綁定的使用方法。

class TestBinding extends GroovyTestCase { 
    void testMeasurement() { 
     prepareData(someClosure) 
    } 

    def someClosure = { 
     assertEquals("apple", a) 
    } 

    void prepareData(testCase) { 
     def binding = new Binding() 
     binding.setVariable("a", "apple") 
     //this.setBinding(binding) 
     testCase.setBinding(binding) 
     testCase.call() 
    } 
} 

這是回答Groovy郵件列表:

在腳本中,DEF foo將創建一個局部變量,而不是一個屬性 (私有字段+的getter/setter)。 想象腳本有點像是run()或main()方法的主體。 這就是你在哪裏以及如何定義局部變量。