【问题标题】:Cucumber - How to struct your tests steps?Cucumber - 如何构建你的测试步骤?
【发布时间】:2019-04-04 17:42:37
【问题描述】:

我目前正在学习黄瓜,在非常简单的测试中,我有一些疑问: "如何组织我的 StepClasses 的最佳方式。

这是我的 .feature:

Feature: How many potatoes have in the sack

Scenario: I put one potato in the Bag
    Given the bag has 10 potatoes
    When I put 1 potato
    Then I should be told 11 potatoes

  Scenario: I remove one potato from the Bag
    Given the bag has 10 potatoes
    When I remove 1 potato
    Then I should be told 9 potatoes

还有我的 StepClass:

公共类 Stepdefs {

private Integer potatoesInTheBag;

@Given("^the bag has 10 potatoes$")
public void the_bag_has_10_potatoes(){
    this.potatoesInTheBag=10;
}

@When("^I put 1 potato$")
public void i_put_one_potato(){
    this.potatoesInTheBag = potatoesInTheBag + 1;
}

@Then("^I should be told (\\d+) potatoes$")
public void i_should_be_told_potatoes(int potatoes) throws Exception {
    assertEquals(potatoesInTheBag.intValue(),potatoes);
}

@When("^I remove 1 potato$")
public void i_remove_one_potato(){
    this.potatoesInTheBag = potatoesInTheBag - 1;
}

}

这个例子可以正常工作,但是 i_remove_one_potato() 应该留在这里,还是留在另一个步骤类中? 另一个问题,如果我想使用场景大纲,在这种情况下我会怎么做?因为尽管添加/删除的土豆是相同的,但答案会有所不同。 有一些好的做法可以指导构建黄瓜测试的过程吗?

谢谢

【问题讨论】:

    标签: java testing cucumber


    【解决方案1】:

    到目前为止,步骤与要测试的场景相关,最好在单个步骤类文件中找到步骤。对于场景大纲,它可能类似于:从袋子中添加/移除土豆。

    :在场景中使用变量,例如 鉴于袋子里有“10”个土豆 从长远来看,它会有所帮助。

    【讨论】:

      【解决方案2】:

      关于如何构建功能文件和步骤定义有很多不同的意见,其中很多都归结为偏好和项目的需求。我在这里的所有想法都是围绕通过浏览器对大型项目进行系统测试,这可能与每个人都无关。

      也就是说,我在功能和步骤之间的一对一关系上获得了最好的运气。我喜欢有一个步骤 def 来提供单个功能文件,并避免重用步骤作为保持代码 DRY 的主要策略(这就是页面对象的用途!)。有时重用一个步骤是有意义的(例如,鉴于我已登录),但我的经验是,它会导致构建这些非常小的原子步骤的大型库,这些步骤很难找到,难以重用,并且把小黄瓜逼到极致。

      一对一方法的明显抱怨(除了在黄瓜文档中违反this anti-pattern)是它会导致重复的代码,但我发现任何你想做的事情不止一次可能是可以下推到页面对象的通用操作。除了特定于正在测试的业务规则的代码之外,这在步骤定义中留下的内容很少,无论如何您都不需要复制这些代码。

      如此简短的回答,我会将i_remove_one_potato() 与该功能的其他步骤保持在同一类中。但是就像你说的,你的例子很简单,所以我猜测你的项目最终需要什么。

      例如大纲,你应该能够做类似的事情

      Scenario Outline: I add/remove potatoes from bag
      Given the bag has <initial> potatoes
      When I <add_remove> <delta> potatoes
      Then I should be told <outcome> potatoes
      Examples:
      | add_remove | initial | delta  | outcome |
      | add        | 10      | 1      | 11      |
      | add        | 10      | 10     | 20      |
      | remove     | 10      | 1      | 9       |
      | remove     | 10      | 10     | 0       |
      

      不过,我尽量不要过度使用场景大纲,这可能太过分了。将整个功能归结为一个由通用步骤驱动的程序表可能很诱人,但在某些时候,很难提取出各个业务规则是什么。当单个示例开始失败时,您必须将整个事情分开并弄清楚作者为什么选择他这样做的表值。 BDD 工具应该阐明该功能,而大表往往会掩盖它。对于上面的示例,我可能应该将添加和删除拆分为单独的大纲,因此我不会将不同业务规则的示例混合在一起。

      一些想法!祝你好运!

      【讨论】:

        猜你喜欢
        • 2012-10-18
        • 2016-10-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-07-07
        • 2017-01-14
        • 2023-03-22
        • 1970-01-01
        相关资源
        最近更新 更多