如何在SpecFlow中共享Feature文件步骤?ScenarioContext失效问题
问题描述
我用SpecFlow做API测试,编写的Feature文件如下:
Scenario: make a get Request to get 200 success When the user has request for postman workspace endpoint /workspaces/ And I adds header for key x-api-key and header value PMAK- 631c80301dfdc01013ecf295-43132564d8545ac2c36ad8c005234e19fa And I send the Get Request Then the response should be success with code 200
我将前3个步骤写在GetRequestStepDefinitions类中,最后一个校验状态码的步骤放在CommonStep公共类,希望跨所有Feature文件复用步骤。尝试用ScenarioContext共享上下文未生效,还出现“Exit code is 0(not available)”异常,推测是前3步的上下文未传递到最后一步。
解决方案
核心问题分析
问题根源是请求后的RestResponse对象未存入ScenarioContext,导致公共步骤类无法获取请求结果;同时CommonStep中存在逻辑错误(如使用未初始化的response对象取字符串当键)。
具体修改方案
1. 在请求步骤类中存储响应到上下文
修改GetRequestStepDefinitions的WhenISendTheRequest方法,将响应对象存入ScenarioContext:
[When(@"I send the Get Request")] public async Task WhenISendTheRequest() { _response = await _restClient.ExecuteGetAsync<Root>(_request); // 用固定键名将响应存入上下文,方便后续统一获取 _scenarioContext.Set(_response, "ApiResponse"); }
2. 修复公共步骤类的校验逻辑
删除CommonStep中未初始化的冗余字段,修改状态码校验方法,从上下文取出响应并完成校验:
[Binding] public class CommonStep { private readonly ScenarioContext _scenarioContext; private RestClient _restClient; public CommonStep(ScenarioContext scenarioContext) { _scenarioContext = scenarioContext; _restClient = _scenarioContext.Get<RestClient>("RestClient"); } [Then(@"the response should be success with code 200")] public void ThenTheResponseShouldBeOk() { // 从上下文获取响应对象 var response = _scenarioContext.Get<RestResponse<Root>>("ApiResponse"); // 校验状态码为200 response.StatusCode.Should().Be(System.Net.HttpStatusCode.OK); // 可选:打印响应内容用于调试 Debug.WriteLine(response.Content); } // 保留其他有用方法,删除未实现/未使用的冗余代码(如IRestBuilder相关逻辑) }
3. 完善请求初始化逻辑
修改GetRequestStepDefinitions中的请求创建方法,补充端点路径(Driver已设置BaseUrl,此处只需填相对路径):
[When(@"the user has request for postman workspace endpoint /workspaces/")] public async Task WhenTheUserMakesRequestForPostmanWorkspaceEndpointWorkspaces() { _request = new RestRequest("/workspaces/"); }
4. 清理冗余代码
- 移除
CommonStep中未使用的IRestBuilder、root字段及未实现的方法(如SendRestRequestToGetService); - 确认
Driver和Hooks类逻辑正常,当前这部分代码已正确将RestClient存入上下文。
修改后流程验证
- 钩子类在场景执行前初始化
RestClient并存入ScenarioContext; - 请求步骤类从上下文取出
RestClient,创建请求、添加请求头、发送请求后将响应存入上下文; - 公共步骤类从上下文取出响应,执行状态码校验;
- 所有步骤共享同一
ScenarioContext,上下文传递生效。
内容的提问来源于stack exchange,提问作者amazo Tv
相关产品推荐
相关产品推荐

