Specflow测试步骤继承导致"不明确的步骤定义"

时间:2014-08-21 18:02:17

标签: c# inheritance specflow acceptance-testing ambiguous

我想拥有以下测试步骤类结构:

[Binding]
public class BaseStep
{
    [Given(@"there is a customer")]
    public void GivenThereIsACustomer(Table table)
    {
        HandleCustomer(table);
    }

    protected virtual void HandleCustomer(Table table)
    {
    }
}

[Binding]
public class FeatureOneStep : BaseStep
{
    protected override void HandleCustomer(Table table)
    {
         // feature one action
    }

    [Given(@"feature one specific step")]
    public void GivenFeatureOneSpecificAction(Table table)
    {
        // do something
    }

}

[Binding]
public class FeatureTwoStep : BaseStep
{
    protected override void HandleCustomer(Table table)
    {
         // feature two action
    }

    [Given(@"feature two specific step")]
    public void GivenFeatureTwoSpecificAction(Table table)
    {
        // do something
    }
}

“鉴于有客户”是FeatureOne和FeatureTwo中使用的常见步骤,但它在两个功能中将具有不同的处理逻辑。所以我决定把这个步骤定义放到一个基类中,并分别覆盖两个派生类中的受保护方法。

但是,当我运行测试时,出现以下错误:

TechTalk.SpecFlow.BindingException: Ambiguous step definitions found for step
'Given there is a customer': 
CustomerTestBase.GivenThereIsACustomer(Table),   
CustomerTestBase.GivenThereIsACustomer(Table)

任何人都可以告诉我如何解决这个问题吗?

3 个答案:

答案 0 :(得分:17)

现在我自己想出这个,所以有几个笔记(希望有人可以在将来使用它):

  • 不要在基类
  • 上包含[Binding]属性
  • 为每个要素文件创建派生类
    • 将[Binding]属性添加到派生类(将自动包含基类中的所有步骤定义)
    • 将[Scope]属性添加到派生类中;指定命名参数Feature
    • 的要素名称

答案 1 :(得分:12)

答案很简单;不要使用继承来定义绑定。

在运行时,SpecFlow通过在所有公共类中全局扫描来查找其方法,以查找具有匹配[Given]属性的方法。这意味着您不能为同一Given there is a customer语句提供两种不同的实现,如果您认为这是一个非常合理的设计决策,将减少歧义。

答案 2 :(得分:1)

这对我来说很好:

public class BaseSteps
{
    [Given(@"Method called")]
    public virtual void WhenMethodCalled()
    {

    }
}    



[Binding]
[Scope(Feature= "specific_feature")
public class DerivedSteps : BaseSteps
{
    [Given(@"Method called")]
    [Scope(Feature= "specific_feature", Tag ="specific_tag")]
    public override void WhenMethodCalled()
    {

    }
}