我不知道如何在Groovy中使用绑定与闭包.我写了一个测试代码,在运行它时,它说,在作为参数传递的闭包上缺少方法setBinding.
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() }
解决方法
这适用于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() } }
它应该从委托类中获取值(在这种情况下,绑定)
This page here通过委托的使用和闭包中的变量范围
实际上,您应该能够像这样使用简单的Map,而不是使用Binding对象:
void prepareData( testCase ) { testCase.delegate = [ a:'apple' ] testCase.call() }
希望能帮助到你!