微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用 xUnit 进行集成测试

如何解决使用 xUnit 进行集成测试

我有一个 MVC 应用程序和一个 Web API。 Web API 使用 xUnit 进行测试。现在我想测试 MVC 应用程序,它具有控制器和一个帮助程序类来调用 API。我的MVC启动类如下。

 public void ConfigureServices(IServiceCollection services)
        {
        
            services.AddHttpClient("gatewayapiclient",(client) =>
            {
                client.BaseAddress = new Uri(Configuration["GatewayAPI"]);
            });
            services.AddHttpClient("identityapiclient",(client) =>
            {
                client.BaseAddress = new Uri(Configuration["IdentityAPI"]);
            });

            services.AddSingleton<IIdentityClientServices,IdentityClientServices>();
            services.AddSingleton(typeof(IBaseApiServiceClient<>),typeof(BaseApiServiceClient<>));
            services.AddSingleton<IHttpContextAccessor,HttpContextAccessor>();

            services.AddControllersWithViews();
         
        }

控制器构造函数如下

 public ItemsController(ILogger<BaseClientMvcController<Item>> logger,IBaseApiServiceClient<Item> apiServices) : base(logger,apiServices)
        {
            _logger = logger;
            _apiServices = apiServices;
        }

IBaseApiServiceClient 构造函数如下

public BaseApiServiceClient(IHttpClientFactory httpClientFactory,IHttpContextAccessor httpContextAccessor)
       {
           _httpContextAccessor = httpContextAccessor;
           _apiEndpointPrefix = $"/api/" + typeof(TEntity).Name.ToLower() + "s/";

           _httpGatewayClient = httpClientFactory.CreateClient("gatewayapiclient");


           _options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true,DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,ReferenceHandler = ReferenceHandler.IgnoreCycles };

       }

调用方法如下

 public virtual async Task<IEnumerable<TEntity>> GetAllAsync(string apiEndpoint)
            {

               using (var response = await _httpGatewayClient.GetAsync(apiEndpoint,HttpCompletionoption.ResponseHeadersRead))
                    {
                        if (response.StatusCode == System.Net.HttpStatusCode.OK)
                        {
                            var stream = await response.Content.ReadAsstreamAsync();
                            var data = await JsonSerializer.DeserializeAsync<IEnumerable<TEntity>>(stream,_options);
                            return data;
                        }
                        else
                        {
                            var problemDetails = await response.Content.ReadFromJsonAsync<ValidationDetailsException>();
                            throw new ProblemFoundException(problemDetails);
                        }
                    }
            }

我尝试了几个选项,但没有任何效果。希望各位高手帮忙

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。