首页 > 解决方案 > 使用 swagger 运行 Web API 核心的集成测试时出错

问题描述

在执行我的集成测试以将数据发布到动态 crm 中的一种方法时,我遇到了以下错误。这是我第一次编写集成测试,其中我的项目是 web api,用于招摇和一些 azure 资源,如密钥库、活动目录。

在执行 Get 调用时,它似乎运行良好,所有步骤都已执行并获得结果。但是对于 Post 调用,我可以看到调用成功并且为最新调用插入了数据库记录,但是在从我的 PostAsync 方法将执行点返回到我的集成测试时,它在两者之间失败了。

以下是错误:

 Message: 
    System.IO.IOException : The request was aborted or the pipeline has finished
  Stack Trace: 
    ResponseStream.CheckNotComplete()
    ResponseStream.WriteAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken)
    ErrorHandller.InvokeAsync(HttpContext context)
    AuthenticationMiddleware.Invoke(HttpContext context)
    StaticFileMiddleware.Invoke(HttpContext context)
    SwaggerUIMiddleware.Invoke(HttpContext httpContext)
    SwaggerMiddleware.Invoke(HttpContext httpContext, ISwaggerProvider swaggerProvider)
    CorrelationIdMiddleware.Invoke(HttpContext context, ICorrelationContextFactory correlationContextFactory)
    <<SendAsync>b__0>d.MoveNext()
    --- End of stack trace from previous location where exception was thrown ---
    ClientHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    HttpClient.FinishSendAsyncBuffered(Task`1 sendTask, HttpRequestMessage request, CancellationTokenSource cts, Boolean disposeCts)
    GeoIntegrationTest.Test_AddState() line 72
    --- End of stack trace from previous location where exception was thrown ---

代码如下

public async Task Test_AddState()
        {
            try
            {
                var data = new StateRequestModel
                {
                        StateCode = "AL",
                        Name ="Alabama",
                    }
                };
                ByteArrayContent byteContent = BuildRequestObject(data);
                var response = await httpClient.PostAsync("api/Geo/AddState", byteContent);
                var result = response?.Content.ReadAsStringAsync().Result;
                var addStateReposne = (ResponseModel<List<string>>) JsonConvert.DeserializeObject(result);
                Assert.NotNull(result);
                Assert.Equal(HttpStatusCode.OK, response.StatusCode);
            }
            catch (Exception ex)
            {
                throw;
            }

        }

如果我能提高代码质量,请帮我解决这个问题并建议我。

标签: swaggerintegration-testingasp.net-core-webapiazure-keyvault

解决方案


所以,我只有自己解决了。问题在于超时,因为一些长时间运行的进程运行的时间超过了 HttpClient 对象的默认超时时间。

client.Timeout = System.TimeSpan.FromMinutes(5);

感谢大家!!!


推荐阅读