【问题标题】:Is it possible to Mock Specflow's ScenarioContext? (C#)是否可以模拟 Specflow 的 ScenarioContext? (C#)
【发布时间】:2020-08-13 17:17:00
【问题描述】:

尝试为使用 ScenarioContext 的 Specflow 步骤编写单元测试。此步骤试图从 ScenarioContext 检索属性的值。是否可以模拟 ScenarioContext 以便我可以为此属性设置值?

在本地使用 VS Professional 和 Moq 框架。谢谢

据我所知,ScenarioContext 没有实现任何接口。在 ScenarioContext 上尝试 Mock 失败(原因在下面的代码块中)

private Mock<IPropertyBucket> _propertyBucket;

ctor(){

    var mo = new Mock<ScenarioContext>(); // this line fails as ScenarioContext has no public contructor.
    mo.Object.Add("response", Response);  // this property is what the specflow step is using eventually

    _propertyBucket = new Mock<IPropertyBucket>();
    _propertyBucket.Setup(pb => pb.ScenarioContext).Returns(mo.Object);  
}

仅供参考:我正在研究多框架目标解决方案。该框架适用于 net472 和 netCore3.1.x。 ScenarioContext 的实现在 .Net Core 和 .Net 框架之间是不同的。

【问题讨论】:

  • 你有没有尝试过?关于 ScenarioContext 类型,Intellisense 告诉您什么?
  • 嗨@GregBurghardt,我用迄今为止的尝试更新了这个问题。谢谢
  • ScenarioContext 继承自 Dictionary,它实现了 IDictionary

标签: c# unit-testing specflow


【解决方案1】:

发布我最终采用的伪代码,它在过去一年中对我很有帮助,无需进行任何更改。

基本上围绕 ScenarioContext 创建了一个包装器,该包装器具有 ScenarioContext 的私有实例(以下代码中的 MyScenarioContext),现在只公开了所需的方法。不用说,包装器有一个与之绑定的接口,它确实允许一起模拟 ScenarioContext。

public class ScenarioContext : IScenarioContext
{
    public ScenarioContext(TechTalk.SpecFlow.ScenarioContext scenarioContext)
    {            
        MyScenarioContext = scenarioContext;
    }

    private TechTalk.SpecFlow.ScenarioContext MyScenarioContext { get; }

    public IObjectContainer ScenarioContainer => MyScenarioContext.ScenarioContainer;

    public StepInfo StepInfo => MyScenarioContext.StepContext.StepInfo;

    ScenarioInfo IScenarioContext.ScenarioInfo => MyScenarioContext.ScenarioInfo;

    public bool Clear(string propertyName)
    {
        if (!MyScenarioContext.ContainsKey(propertyName)) return false;
        MyScenarioContext.Remove(propertyName);
        return true;
    }

    public T GetProperty<T>(string key)
    {
        if (MyScenarioContext.ContainsKey(key))
            return (T)MyScenarioContext[key];
        throw new Exception($"No key remembered with the name {key}");
    }
    //.
    //.
    //.
    // Other useful functions such as Remember etc.
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-08-12
    • 1970-01-01
    • 1970-01-01
    • 2021-12-12
    • 1970-01-01
    • 2012-04-07
    • 2018-10-08
    相关资源
    最近更新 更多