步骤内的 Specflow 调用步骤会导致“无匹配的步骤定义”错误

2024-01-12

我正在遵循概述的技术here https://stackoverflow.com/questions/24928270/is-it-valid-to-have-specflow-features-depending-on-other-features

使用如下定义的步骤

[Given("some base scenario has happened")]
public void SomeBaseScenarioHasHappened()
{
   Given("some condition");
   And("some action");
   When("some result");
}

从这样的场景

Scenario: Some dependant scenario
Given some condition 
And some base scenario has happened
When some other action
Then some other result

然而步骤

  When some other condition

产生以下错误 -> 找不到该步骤的匹配步骤定义。使用以下代码创建一个:

[When(@"some other condition")]
public void Whensome other condition()
{
ScenarioContext.Current.Pending();
}

我可以通过让基本场景仅使用给定来解决这个问题

[Given("some base scenario has happened")]
public void SomeBaseScenarioHasHappened()
{
   Given("some condition");
   Given"some action");
   Given("some result");
}

但这不是我应该做的。 我错过了什么吗? 为什么不能使用 AND 调用基本场景?


在 Specflow 中只有 3 种类型的步骤。Given, When and Then。当您使用步骤时And在您的场景描述中,SpecFlow 会查看先前类型的步骤并假设您的And步骤是同一类型。

所以当你写这个的时候

Scenario: Some dependant scenario
    Given some base scenario has happened
    And some other condition
    When some other action
    Then some other result

Specflow 查找具有绑定的步骤:

    Given("some base scenario has happened")
    Given("some other condition")
    When("some other action")
    Then("some other result")

注意没有And捆绑?

因此,您的解决方案是确保在复合步骤中必须避免使用And并仅使用原始步骤所具有的相同绑定(如果有多个,则使用其中一个)。您的最终解决方案应该如下所示:

[Given("some condition")]
public void SomeCondition()
{
   ...
}

[When("some action")]
public void SomeAction()
{
   ...
}

[Then("some result")]
public void SomeResult()
{
   ...
}

[Given("some base scenario has happened")]
public void SomeBaseScenarioHasHappened()
{
   Given("some condition");
   When("some action");
   Then("some result");
}

[Given("some other condition")]
public void SomeOtherCondition()
{
   ...
}

[When("some other action")]
public void SomeOtherAction()
{
   ...
}

[Then("some other result")]
public void SomeOtherResult()
{
   ...
}

你不能使用And在复合步骤中,因为实际上没有任何步骤与And,没有这样的绑定 - 唯一的绑定是Given, When or Then. The And and But关键字仅在生成运行的单元测试时使用,使用这些关键字的步骤仍然绑定到Given, When or Then最终迈出一步。

在场景定义中,事物按顺序处理,您可以轻松判断什么是场景And步骤实际上是基于它之后出现的步骤,因此当 Specflow 生成步骤绑定时,它知道要使用什么步骤类型(或者是Given, When or Then)。当您从另一个步骤中调用一个步骤时,您显式调用了这些步骤绑定之一,并且必须使用它所绑定的绑定来调用它。所以如果它与一个绑定Given像这样绑定:

[Given("some other condition")]
public void SomeOtherCondition()
{
   ...
}

那么你必须从代码中这样调用它:

Given("Some other condition");

但你可以在场景中这样引用它:

Given some condition
And some other condition

因为 Specflow 知道它何时生成单元测试And some other condition实际上是在调用Given绑定步骤

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

步骤内的 Specflow 调用步骤会导致“无匹配的步骤定义”错误 的相关文章

随机推荐