我尝试使用Specflow进行实验。所以我正在编写REST API的功能测试并创建了几个步骤定义,比如CreatePersonStepDefinitions
和GetPeopleStepDefinition
那些扩展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
因此,步骤定义之间有几个常见步骤。我明白我不能这样做,因为步骤是全球性的。我想问的是,如果不在每个步骤定义中重复相同的步骤,最好的方法(即最佳实践)是什么。
由于
答案 0 :(得分:1)
因为步骤是全局的,所以您不需要在每个步骤定义中复制它们,您只需在所有功能中使用它们,specflow就会调用它们。
如果您真正的问题是我如何在我的功能步骤和常见步骤之间共享ApiKey和响应,那么a few ways但我建议使用链接中的上下文注入approqach。我将创建上下文对象并将它们传递给您的步骤类。 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
类只需SecurityContext
和ResponseSteps
即可取ResponseContext