【问题标题】:How to reuse code in Spock tests如何在 Spock 测试中重用代码
【发布时间】:2017-01-05 20:15:59
【问题描述】:

我正在为网站测试编写基于 Spock + Geb 的测试。网站用于创建报价,随后可以对其执行各种操作(确认、拒绝、撤回)。我已经为创建报价创建了工作场景。但是现在当我需要为各种操作组合实现场景时,我希望能够在这些其他场景中重用“创建报价”。不幸的是,我无法找到任何示例或思考如何做到这一点的好方法。有人可以给我任何想法吗?

顺便说一句,我需要按预定义的顺序执行操作,所以我在规范中使用 Stepwise 注释。

【问题讨论】:

    标签: spock geb


    【解决方案1】:

    单页操作:

    如果不查看代码示例,很难说,但这样做的一种方法是将操作(确认、拒绝、撤回)的方法定义为 Page 类中的简单方法:

    class ActionsPage extends Page {
    
      static content = { 
        //Page content here
      }
    
      def confirm (){
        //Code to perform confirm action on the page
      }
    
      def reject (){
        //Code to perform reject action on the page
      }
    

    然后在你的规范类中你可以做

    def "Test confirm action"(){
      when: "we go to the actions pages"
      to ActionsPage
    
      and: "we perform a confirm action"
      confirm()
    
     then: "something happens"
     //Code which checks the confirmation worked 
    } 
    

    之所以有效,是因为 Geb 使用 Groovy 的方法缺失东西来查找当前页面上名为“confirm()”的方法的名称,并将执行该代码。

    多个页面操作:

    如果操作很复杂并且涉及导航到多个页面,最好为需要执行操作的测试创建一个抽象基类:

    //Not @Stepwise
    abstract class BaseActionsSpec extends Specification {
    
      //Note: don't use Spock when/then blocks in these methods as they are not feature methods
      protected void confirm(){
        //Code to perform multi-page action
      }
    
      protected void reject(){
        //Code to perform multi-page action 
      }
    }
    

    然后是扩展类:

    @Stepwise
    class ConfirmActionSpec extends BaseActionsSpec{
    
          def "Test confirm action"(){
            when: "we go to the actions pages"
            to ActionsPage
    
            and: "we perform a confirm action"
            confirm() //calls method in super class
    
            then: "something happens"
           //Code which checks the confirmation worked 
        }
    }
    

    【讨论】:

    • 感谢您的回答。实际上,这些动作并不是那么简单,而是由不同网页中的动作流组成。所以这就是为什么我想将它们作为单独的规范实现,然后有可能以某种方式将它们包含到另一个规范中。是否可以使用扩展将新功能添加到规范中?
    • 好的,这个解决方案只适用于单页操作,所以我会添加另一个适合你的解决方案
    • 顺便说一下,@Stepwise 注解不太支持继承,所以如果你在超类中有特性,它们相对于子类特性的执行顺序是没有定义的。我必须编写一个自定义的 Spock 扩展来获得你想要的行为(虽然很抱歉是专有代码)。我建议仅将操作代码从功能中移出并移入帮助方法中,如我的回答中所示。
    • 谢谢!实际上,我希望拥有完全可重用的功能甚至规范,但要明白没有这样的功能。所以将尝试使用辅助类和继承。
    • 使用特质怎么样?我们经常使用特征将常见的行为和辅助方法注入到我们的 Spock 测试中。
    猜你喜欢
    • 2018-09-18
    • 2012-06-10
    • 1970-01-01
    • 2014-08-28
    • 2015-08-21
    • 1970-01-01
    • 2021-08-09
    • 1970-01-01
    • 2014-08-21
    相关资源
    最近更新 更多