2010-07-13 80 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()方法的主体。 这就是你在哪里以及如何定义局部变量。