使用SpecFlow测试时,GetAsync赋值的Response在其他方法中为何为空?
问题解决:SpecFlow中异步步骤导致Response后续为null的问题
核心原因
你的Given步骤方法使用了async void返回类型,这是错误的做法。SpecFlow无法正确等待async void方法的异步操作完成,会导致后续步骤在Given的异步请求逻辑未完全执行完毕时就启动,最终出现Response为null的情况。此外,async void在.NET中仅适用于事件处理场景,它的异常处理、上下文管理机制和async Task完全不同,极易引发这类上下文丢失问题。
修复步骤
- 将异步步骤方法的返回类型从
async void改为async Task,让SpecFlow能够正确管理异步操作的等待逻辑 - 确保所有异步操作都正确使用
await关键字等待完成
修改后的代码示例
步骤绑定类
[Binding] public sealed class UsersSteps { private HttpResponseMessage Response { get; set; } = null!; private static readonly HttpClient Client = new HttpClient(); [Given(@"I access the users route (.*)")] // 改为async Task返回类型 public async Task GivenIAccessTheUsersRoute(string baseUrl) { var url = new Uri(baseUrl); Response = await Client.GetAsync(url); Console.WriteLine(">> Here it works: " + Response.StatusCode); } [Then(@"I should have only 1 registered user")] public void ThenIShouldHaveOnlyOneRegisteredUsers() { Console.WriteLine(">> Now works here: " + Response.StatusCode); } [StepDefinition(@"should be admin")] public void AndShouldBeAdmin() { Console.WriteLine(">> Now works here: " + Response.StatusCode); } [StepDefinition(@"your name should be Fulano da Silva")] public void AndYourNameShouldBeFulanoDaSilva() { Console.WriteLine(">> Now works here: " + Response.StatusCode); } }
Feature文件(无需修改)
Scenario: List users Given I access the users route https://serverest.dev/usuarios Then I should have only 1 registered users And should be admin And your name should be Fulano da Silva
额外说明
- 若后续步骤中涉及异步操作(比如解析Response的JSON内容),同样需要将方法改为
async Task并配合await使用 - SpecFlow对步骤方法的返回类型有明确要求:同步方法返回
void,异步方法必须返回Task,否则会出现执行顺序、上下文丢失等问题
内容的提问来源于stack exchange,提问作者Lucas Dittrich
相关产品推荐
相关产品推荐

