【问题标题】:How to better use ScenarioContext in SpecFlow for maintainability如何在 SpecFlow 中更好地使用 ScenarioContext 以实现可维护性
【发布时间】:2019-04-04 09:48:30
【问题描述】:

在用于存储运行时值的测试项目中,我在 SpecFlow 中使用了许多测试上下文变量,如下所示。我在 VS2018 中使用 SpecFlow 和 C#。

ScenarioContext.Current["PostResponse"] = postResponse;
ScenarioContext.Current["PutResponse"] = putResponse;

但目前实现中有一些变化,需要将 PUT 响应更改为 POST 响应以创建新对象,并在更新时保持原样。因此,现在我必须根据场景单独更新场景上下文的每个部分,并且需要对其进行更新。这不是聪明的做法。我会像“objectcreationResponse”、“objectupdateResponse”一样存储在一个共同的地方,在一个地方更改会更容易。而且我在运行时使用了很多 Scneario Context。有没有更好的使用方法?

【问题讨论】:

  • postResponse 和 putResponse 变量有哪些类型?

标签: c# cucumber bdd specflow


【解决方案1】:

您可以使用 C# 扩展方法将其集中化:

public static class ScenarioContextExtensions
{
    public static UpdateResponseType GetUpdateReponse(this ScenarioContext context)
    {
        return context["updateResponse"] as UpdateResponseType;
    }

    public static void SetUpdateResponse(this ScenarioContext context, UpdateResponseType updateResponse)
    {
        return context["updateResponse"] = updateResponse;
    }
}

现在任何有 ScenarioContext 对象的地方,都可以为这些公共信息强类型化 getter 和 setter:

ScenarioContext.Current.GetUpdateResponse();
ScenarioContext.Current.SetUpdateResponse(...);

这允许您利用 Visual Studio 中可用的所有重构工具,这应该可以缓解您描述的问题。

【讨论】:

    猜你喜欢
    • 2020-08-13
    • 1970-01-01
    • 2010-10-08
    • 2012-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-24
    相关资源
    最近更新 更多