无法在groovy中传递闭包

时间:2012-03-14 20:28:25

标签: groovy closures geb

我正在尝试运行Geb库的基本示例(http://www.gebish.org/manual/current/intro.html#introduction)。这是代码:

import geb.Browser

Browser.drive {
   go "http://google.com/ncr"

    // make sure we actually got to the page
    assert title == "Google"

    // enter wikipedia into the search field
    $("input", name: "q").value("wikipedia")

    // wait for the change to results page to happen
    // (google updates the page dynamically without a new request)
    waitFor { title.endsWith("Google Search") }

    // is the first link to wikipedia?
    def firstLink = $("li.g", 0).find("a.l")
    assert firstLink.text() == "Wikipedia"

    // click the link 
    firstLink.click()

    // wait for Google's javascript to redirect to Wikipedia
    waitFor { title == "Wikipedia" }
}

当我尝试运行它时(使用Eclipse的常规支持),我得到以下异常:

Caught: groovy.lang.MissingMethodException: No signature of method: static geb.Browser.drive() is applicable for argument types: (ExampleScript$_run_closure1) values: [ExampleScript$_run_closure1@2a62610b]
Possible solutions: drive(groovy.lang.Closure), drive(geb.Browser, groovy.lang.Closure), drive(geb.Configuration, groovy.lang.Closure), drive(java.util.Map, groovy.lang.Closure), print(java.lang.Object), print(java.io.PrintWriter)
groovy.lang.MissingMethodException: No signature of method: static geb.Browser.drive() is applicable for argument types: (ExampleScript$_run_closure1) values: [ExampleScript$_run_closure1@2a62610b]
Possible solutions: drive(groovy.lang.Closure), drive(geb.Browser, groovy.lang.Closure), drive(geb.Configuration, groovy.lang.Closure), drive(java.util.Map, groovy.lang.Closure), print(java.lang.Object), print(java.io.PrintWriter)
at ExampleScript.run(ExampleScript.groovy:21)

我认为这是说我传递给静态Browser.drive方法的闭包与groovy.lang.Closure不兼容,但我不知道为什么。简单的groovy hello world脚本工作正常,但是将闭包传递给方法总会返回类似的错误。

1 个答案:

答案 0 :(得分:2)

抄袭自http://groovy.codehaus.org/Differences+from+Java

Java程序员习惯使用分号终止语句而不使用闭包。在类定义中也有实例初始值设定项。所以你可能会看到类似的东西:

class Trial {
  private final Thing thing = new Thing ( ) ;
  { thing.doSomething ( ) ; }
}

许多Groovy程序员避免使用分号作为分散注意力和冗余(尽管其他人一直使用它们 - 这是编码风格的问题)。导致困难的情况是将以上内容写在Groovy中:

class Trial {
  private final thing = new Thing ( )
  { thing.doSomething ( ) }
}

这将抛出MissingMethodException!