使用 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 (将#修改为@)