问题描述
TL;DR;如何创建一个调用另一个测试作为第一步的 specflow 测试?
Given I already have one specflow test
And I want to run another test that goes deeper than the first test
Then I create a second test that runs the first test as its first step
And I add additional steps to test the deeper functionality
抱歉,这里有点规范流幽默.
Sorry, little bit of specflow humor there.
例如,我已经有一个测试可以创建销售:
eg I have a test that creates a sale already:
Given I want to create a sales order
And I open the sales order page
And I click the add new order button
Then a new sales order is created
我想进行另一个测试来测试添加销售线
And I want to have another test that tests adding a sales line
另一个测试完成销售的测试
And another test that tests completing the sale
另一个取消销售的测试
然后……等等
所有这些测试都将从与简单测试相同的前四个步骤开始,这违反了 DRY 原则.那么我该怎么做才能让第二个测试的第一步只运行第一个测试呢?例如:
All of those tests would start with the same first four steps as the simple test, which breaks the DRY principle. So how can I do it so that the first step of the 2nd test just runs the first test? eg something like:
Given I have run the create sales order test // right here it just runs the first test
And I add a sales order line
Then the order total is updated
如果每个测试都以相同的前四行开始,后来我意识到我需要更改简单的 create sale 测试,那么我还需要去寻找并修复重复这四行的其他地方.
If every test starts off with the same first four lines, and later on I realize that I need to change the simple create sale test, then I will also need to go and find and fix everywhere else that repeats those four lines.
请注意,这也应该能够跨功能工作.例如,上面的简单测试是在销售功能中定义的.但我也会有一个积分功能,这需要每次都创建一个销售才能获得积分:
Note that this should also be able to work across features. eg The simple test above is defined in the sales feature. But I would also have a credits feature, and that would require creating a sale each time in order to be able to credit it:
Given I want to credit a sale
And I run the create sales order test
And I complete the the sale
And I click the credit button
Then the sale is credited
推荐答案
如前所述,您可以为此使用背景(这可能是大多数情况下的最佳选择),但您也可以创建一个调用另一个的步骤步骤.
As noted already you can use a background for this (and that's probably the best option in most situations), but you can also create a step which calls the other steps.
[Binding]
public class MySteps: Steps //Inheriting this base class is vital or the methods used below won't be available
{
[Given("I have created an order")]
public void CreateOrder()
{
Given("I want to create a sales order");
Given("I open the sales order page");
Given("I click the add new order button");
Then("a new sales order is created");
}
}
然后你可以在你的场景中使用它:
which you can then use in your scenario:
Scenario: I add another sale
Given I have created an order
When I add a sales order line
Then the order total is updated
这样做的好处是,这个复合步骤可以在场景中的任何地方使用,而不仅仅是作为起点.如果您需要,此步骤可以在多个功能中重复使用
This has the advantage that this composite step can be used anywhere in the scenario and not just as a starting point. This step can then be reused across multiple features if you need
这篇关于在 Specflow 中,我可以将一个测试作为另一个测试的一个步骤运行吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!