Specflow-您能否收集所有集成测试步骤以作为对真实服务器的系统测试运行?

问题描述

我的解决方案中有许多子项目,每个子项目都有自己的Specflow集成测试。这些都针对本地Web服务器实例(Kestrel)运行。我想做的是创建一个新项目,该项目将解决方案中的所有现有测试汇总在一起,并在实时服务器上运行它们。显然,这只会偶尔执行。

是否可以不重新定义步骤?

解决方法

如果可以将Selenium或Web服务调用使用的根URL设置为可配置的,这应该是可能的。根据您使用的是.NET Core(appsettings.json)还是Framework(App.config),在这些配置文件中添加一些设置以定义根URL。只需在配置文件中更改该根URL并运行测试即可。

一种替代方法是定义一个保存该根URL的环境变量,但是配置设置是理想的。诀窍是在您访问应用程序或Web服务URL的每个位置使用此配置设置。为此目的专门创建一个类可能并不困难:

internal class TestUrls
{
    private readonly string rootUrl;

    internal string HomePage => rootUrl;

    internal TestUrls(string rootUrl)
    {
        this.rootUrl = rootUrl;
    }

    internal string UserProfilePage(string username)
    {
        return $"{rootUrl}/profiles/{username}";
    }

    internal string UpdateUserWebService(string username)
    {
        return $"{rootUrl}/users/{username}";
    }
}

然后在[BeforeScenario]钩子中初始化并在SpecFlow依赖项注入框架中注册它:

[Binding]
public class SpecFlowHooks
{
    private readonly IObjectContainer container;

    public SpecFlowHooks(IObjectContainer container)
    {
        this.container = container;
    }

    [BeforeScenario]
    public void BeforeScenario()
    {
        var rootUrl = // read from config file
        var urls = new TestUrls(rootUrl);

        container.RegisterInstanceAs(urls);
    }
}

通过在步骤定义类中将其定义为构造函数参数来使用TestUrls对象:

[Binding]
public class UserSteps
{
    private readonly TestUrls urls;

    public UserSteps(TestUrls urls)
    {
        this.urls = urls;
    }

    [When(@"the ""(.*)"" user views their profile")]
    public void WhenTheUserViewsTheirProfile(string username)
    {
        // Generate dynamic URL to user profile page based on argument in step
        var userProfilePageUrl = urls.UserProfilePage(username);

        // navigate to use profile page
    }
}