使用 xUnit 进行集成测试

时间:2021-08-01 17:38:41

标签: asp.net-core asp.net-web-api xunit xunit.net

我有一个 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);
                        }
                    }
            }

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

0 个答案:

没有答案