使用specflow将字符串输入参数转换为自定义类的隐式运算符

时间:2017-11-27 10:56:56

标签: c# implicit-conversion specflow

我创建了一个将specflow参数转换为自定义类

的类
public class KeyphraseState
{
    private Dictionary<string, bool> Keyphrase = new Dictionary<string, bool>()
    {
        { "displayed", true },
        { "not displayed", false }
    };

    private string Phrase;
    private bool State;

    public KeyphraseState(string text)
    {
        this.Phrase = text;
        this.State = GetState(this.Phrase);
    }

    private bool GetState(string phrase)
    {
        return Keyphrase[phrase];
    }

    public static implicit operator KeyphraseState(string text)
    {            
        return new KeyphraseState(text);
    }
}

然后我尝试在步骤定义中使用它,如

    [When(@"link is (.*) on the page")]
    public void WhenLinkIs(string status)
    {
        KeyphraseState st = status;
        // ...
    }

它很有效。但是当我尝试在步骤构造函数中使用它时

    [When(@"link is (.*) on the page")]
    public void WhenLinkIs(KeyphraseState status)
    {
        // ...
    }

然后我收到一条错误消息 从'System.String'到'KeyphraseState'的无效演员

在这种情况下,有人可以解释是否可以使用 隐式运算符 ,或者是否有其他方式来实现此类转换?

1 个答案:

答案 0 :(得分:1)

在SpecFlow中,有一个名为“步骤参数转换”的功能。将您在场景中的步骤值转换为步骤绑定方法中参数的类型。

文档和示例如下:http://specflow.org/documentation/Step-Argument-Conversions/