首页 > 解决方案 > 黄瓜迁移场景到场景大纲

问题描述

我想将多行场景移动到场景大纲,以便可以将表格的各个行作为单独的测试进行测试。这是我想到的一个简化示例:

Scenario: This scenario loops through the lines of the table performing an assert on each line
    When I do something and verify it
      | name         | parameter1 | parameter2   | parameter3 |
      | A and 1      | A          | 1            | true       |
      | B and 1      | B          | 1            | false      |
      | A and 2      | A          | 2            | false      |
      | B and 2      | B          | 2            | true       |

步骤定义如下所示:

@When("I do something and verify it")
public void doSomethingAndVerifyIt(DataTable dataTable) {
    List<Map<String, String>> keyValues = dataTable.asMaps();
    for (Map<String, String> keyValue : keyValues) {
        assertSomething(keyValue.get("parameter1"), keyValue.get("parameter2"), keyValue.get("parameter3"));
    }
}

这工作正常,但如果任何行未能通过断言步骤,那么测试将在此时停止。我想将其更改为沿这些线使用场景大纲,以便这些线可以彼此独立地通过或失败:

Scenario Outline: This scenario loops through the lines of the table performing an assert on each line
    When I do something and verify it

Examples:
      | name         | parameter1 | parameter2  | parameter3 |
      | A and 1      | A          | 1           | true       |
      | B and 1      | B          | 1           | false      |
      | A and 2      | A          | 2           | false      |
      | B and 2      | B          | 2           | true       |

如何更改步骤定义,以便每次测试读取一行?我知道我可以通过在步骤定义下添加一行来按名称显式声明每个参数来做到这一点,但在我的情况下,这将涉及大量参数。

有没有更简单的方法来做到这一点:

@When("I do something and verify it")
public void doSomethingAndVerifyIt(Map<String, String> keyValue) {
    assertSomething(keyValue.get("parameter1"), keyValue.get("parameter2"), keyValue.get("parameter3"));
}

标签: javadatatablecucumberscenarios

解决方案


有关如何使用表的信息,请参阅我的其他答案。

改进方案的更好方法是将示例转换为命名规则。在讨论行为时从业务中获取信息时,示例非常有用。但是,在编写代码时,它们并不是很好。让我们用密码登录来探索一下。

说我们有

password     | success?

123456       |   no
xb32drthcyfe |   no
p@ssword1    |   yes

作为我们的例子。我们在这里遇到的问题是我们不知道为什么xb32drthcyfe会失败并且p@ssword1应该成功。我们可以猜测,但我们的场景未能记录 WHY。

现在考虑

Scenario: Passwords must contain a symbol
 When I register with a password without a symbol
 Then I should see my password needs a symbol

现在您有了一个场景,不仅记录了 WHY,还允许您挑战 WHY,并探索 WHY,例如

Scenario: Weak password that contains a symbol
 Given my password is long enough has a symbol but it is really weak
 When I register with my password
 Then I should be registered.

现在您可以向您的企业展示上述行为并说,我们真的想要这样做吗?

每个示例背后都应该有一个唯一的命名规则。对于一个足够成熟的例子,你需要揭示这个规则,给它一个名字,然后用探索规则的场景替换你的cukes中示例的用法。


推荐阅读