代码之家  ›  专栏  ›  技术社区  ›  switch201

如何为模块创建“getter”(如何使用导航器实例化模块对象?)

  •  0
  • switch201  · 技术社区  · 6 年前

    我正试图做到这样,我的所有页面和模块引用都可以在intellij中自动完成。

    由于某种类型的错误,我不能像通常那样做。(请参阅此处了解更多详细信息: How to have geb static content recognized form test script )

    为了解决上述错误。我选择为所有静态内容创建“getter”。

    例如:

    页面:

    class MyPage extends Page{
        static content = { 
            tab {$(By.xpath("somexpath")}
        }
    
        Navigator tab(){
            return tab
        }
    }
    

    剧本:

    //imagine we are in the middle of a feature method here
    def test = at MyPage
    test.tab().click()
    

    所以上面所有的代码都按我的期望工作,我想像这样重做我的页面,这样我就可以从脚本端自动完成。当我尝试对模块使用相同的技术时,会出现问题。

    例如:

    class MyPage extends Page{
        static content = { 
            mod {module(new MyModule())}
        }
    
        MyModule mod(){
            return mod
        }
    }
    

    如果我试着这样从脚本访问mod

    //imagine we are in the middle of a feature method here
    def test = at MyPage
    test.mod().someModContentMaybe().click()
    

    我得到以下错误:

    org.codehaus.groovy.runtime.typehandling.GroovyCastException: Cannot cast object 'MyPage' -> mod: 'MyModule' with class 'geb.content.TemplateDerivedPageContent' to class 'MyModule'
    

    如果我尝试在页面对象中执行以下操作:

    class MyPage extends Page{
        static content = { 
            mod {module(new MyModule())}
        }
    
        MyModule mod(){
            return new MyModule()
        }
    }
    

    尝试从脚本访问模块时出现以下错误:

    geb.error.ModuleInstanceNotInitializedException: Instance of module class MyModule has not been initialized. Please pass it to Navigable.module() or Navigator.module() before using it.
    

    我想它希望我获取一个实例化的导航器对象并调用 module(MyModule) 但我不确定这是如何工作的,或者如何决定从哪个导航器对象调用模块。

    总之,我只想能够自动完成模块名和脚本中的静态内容。

    3 回复  |  直到 6 年前
        1
  •  2
  •   erdi    6 年前

    你得到了一个 GroovyCastException 从返回类型为扩展类的方法返回包含模块的内容时 geb.Module 因为从内容定义返回的导航器和模块被包装在 geb.content.TemplateDerivedPageContent .

    您可以使用 as 关键字,如手册中有关 unwrapping modules returned from the content DSL . 因此,对于您的一个示例,它看起来是这样的:

    MyModule mod(){
        mod as MyModule
    }
    
        2
  •  3
  •   kriegaex    6 年前

    这个 Book of Geb's section about modules 回答你的问题。您不应该手动调用模块的构造函数,而是使用本章开头描述的语法。这个解决方案消除了异常,也为我解决了代码完成问题:

    static content = { 
      mod { module MyModule }
    }
    

    现在例外情况已经消失了,下面介绍如何添加您请求的getter:

    def myModule() { mod }
    
        3
  •  2
  •   Michael    6 年前

    我想问题是你 content 块。 Module S通过定义 Navigator S’ module 方法:

    static content = {
        mod { $("div.module").module(MyModule)
    }
    

    所以不需要调用构造函数。