扩展Specflow中的StepDefinitions

本文关键字:StepDefinitions 中的 Specflow 扩展 | 更新日期: 2023-09-27 18:13:36

我试着用Specflow做实验。因此,我正在为REST API编写功能测试,并创建了几个步骤定义,如CreatePersonStepDefinitionsGetPeopleStepDefinition

扩展了CommonStepDefinition,它提供了如下内容:

[Given(@"a valid API key is given")]
public void AValidApiKeyIsGiven()
{
     ApiKey = "Some Api Key";
}
[Then(@"the response HTTP code should be (.*)")]
public void ThenTheStatusCodeShouldBe(int statusCode)
{
     Assert.AreEqual (statusCode, (int)Response.StatusCode);
}

这是为了能够运行像

这样的场景
Given I am retrieving all people
And an invalid API key is given
When I make the call
Then the response HTTP code should be 200
And the API response code is 104
And the API call didn't take more than 200 milliseconds

所以在步骤定义之间有几个共同的步骤。我知道我不能这样做,因为Steps是全球性的。我想问的是,在每个步骤定义中不重复相同步骤的情况下,实现这一目标的最佳方法(即最佳实践)是什么。

谢谢

扩展Specflow中的StepDefinitions

因为步骤是全局的,你不需要在每个步骤定义中都重复它们,你可以在所有特性中使用它们,specflow会调用它们。

如果你真正的问题是我如何在我的功能步骤和我的公共步骤之间共享ApiKey和Response,有几种方法,但我建议使用链接中的上下文注入方法。我会创建上下文对象并将它们传递给你的步骤类。Specflow有一个简单的DI框架,它会自动(大多数时候)为你做这些。

我将创建如下内容:

public class SecurityContext
{
    public string ApiKey {get;set;}
}
public class ResponseContext
{
    public IHttpResponse Response{get;set;}
}
[Binding]
public class CommonSteps
{
     private SecurityContext securityContext;
     private ResponseContext responseContext;
     public CommonSteps(SecurityContext securityContext,ResponseContext responseContext)
    {
         this.securityContext = securityContext;
         this.responseContext = responseContext;
    }
    [Given(@"a valid API key is given")]
    public void AValidApiKeyIsGiven()
    {
         securityContext.ApiKey = "Some Api Key";
    }
    [Then(@"the response HTTP code should be (.*)")]
    public void ThenTheStatusCodeShouldBe(int statusCode)
    {
         Assert.AreEqual (statusCode, (int)responseContext.Response.StatusCode);
    }
}
public class MyFeatureSteps
{
     private SecurityContext securityContext;
     private ResponseContext responseContext;
     public MyFeatureSteps(SecurityContext securityContext,ResponseContext responseContext)
    {
         this.securityContext = securityContext;
         this.responseContext = responseContext;
    }
    ///Then in your feature steps you can use the Api key you set and set the response
}

你甚至可以考虑不使用Common步骤,因为这只是一个大桶,对于所有不是特定功能的东西,但我们通常做的是将步骤类分解为SecuritySteps,它只会接受SecurityContextResponseSteps,它只会接受ResponseContext