Groovy 如何在不使用GEB和Spock将方法声明为静态的情况下从任何其他页面调用方法?

Groovy 如何在不使用GEB和Spock将方法声明为静态的情况下从任何其他页面调用方法?,groovy,spock,geb,Groovy,Spock,Geb,我想在2-3页中使用以下函数,所以我想调用该函数,但出现异常“需要静态方法…” 在代码中,CommonFunction是一个扩展Page类的类 def "User clicks on My Account Link"(){ CommonFunction."User clicks on My Account Link"() } 我也尝试了以下方法,但仍然得到异常“geb.error.PageInstanceNotificationDexception:页面类com.caseSt

我想在2-3页中使用以下函数,所以我想调用该函数,但出现异常“需要静态方法…”

在代码中,CommonFunction是一个扩展Page类的类

def  "User clicks on My Account Link"(){

    CommonFunction."User clicks on My Account Link"()   
}
我也尝试了以下方法,但仍然得到异常“geb.error.PageInstanceNotificationDexception:页面类com.caseStudio.util.CommonFunctions的实例尚未初始化。请在使用它之前将其传递给Browser.to()、Browser.via()、Browser.page()或Browser.at()

下面是用户单击我的帐户链接()函数的代码


现在有点不清楚您到底想做什么,但看起来您在多个页面上有一个“我的帐户”链接,您希望有一种方法可以单击此链接,而不必在每个页面上重复代码。如果是这种情况,您应该这样做:

创建一个“BasePage”类,所有其他具有“我的帐户”功能的页面都应该扩展该类

class BasePage extends Page{

  static content = {
    myAccountLink { $("#myAccountLink") } //CSS selector for the link you want on your page
  }

  //You don't actually need this method. In your tests you can just say myAccountLink.click() and it'll still work.
  def "User clicks on My Account Link"(){
    myAccountLink.click()
  }
}
然后,您的其他页面可以定义为:

class HomePage extends BasePage {
  ... 
}
在测试中,只要浏览器位于从BasePage扩展而来的页面上,就可以调用该方法:

def "User can go to my account page"(){
 setup:
    to HomePage

 when: "The user clicks the MyAccount link"
   "User clicks on My Account Link"()

 then:
   at MyAccountPage
}

我已经更改了子类中的函数名,然后在子函数中调用函数(这里父函数名与子函数名不同)


谢谢你,Jk你所建议的也很好

如果你有一个可以存在于多个页面上的通用组件,那么你要做的是创建一个带有控制访问器的Geb“模块”,然后将该模块包含在包含该模块的页面中

class moduleName extends Module {
    static clickUserLink() { userLink.click() }
    static content = {
        userLink = {$(locator)}
    }
}

class pageName extends Page {
    static content = {
        localName { module moduleName }
    }
}

这样,您的clickUserLink将迁移到通过localName.clickUserLink导入模块的任何页面。您还可以考虑在CLIKUSSRink方法或助手方法中添加一个等待(USELink)。

您需要在与PAGEVE进行交互之前先访问一个页面。我已经编写了这样的代码:类主页扩展了公共函数{UnFultualStudio。“用户点击我的帐户链接”()}。和CommonFunction类我扩展了Page类并导入了这个类geb.pageThank实际上我想在所有页面中使用这行代码:def“User clicks on My Account Link”({def actions=新操作(驱动程序)myaccountMenu.displayed WebElement myaccountMenu=myaccountMenu.firstElement()actions.click(myaccountMenu).build().perform()}您好,请查看我编辑的问题,希望您能够理解,在selenium with Java中,我们用于在单独的页面或类中编写公共函数,每当需要这些函数时,我们是通过它的object.function名称来调用的,这样我们的代码就没有多余的代码了。您尝试过我的解决方案吗?我使用的站点需要鼠标悬停,因此需要操作方法,您建议的方法对我无效,因为在将此问题发布到stack overflow之前,我已经在代码中尝试过。您不能将该方法放在BasePage类中吗?然后所有扩展它的页面都可以使用它
def "User can go to my account page"(){
 setup:
    to HomePage

 when: "The user clicks the MyAccount link"
   "User clicks on My Account Link"()

 then:
   at MyAccountPage
}
class moduleName extends Module {
    static clickUserLink() { userLink.click() }
    static content = {
        userLink = {$(locator)}
    }
}

class pageName extends Page {
    static content = {
        localName { module moduleName }
    }
}