集成测试中两个API之一中的错误403

时间:2019-10-16 20:14:58

标签: c# asp.net-core .net-core nunit integration-testing

我有一个集成测试项目,该项目已添加到大型后台解决方案中,其中有两个主要API项目需要测试。我尝试使用HttpClientFactoryTestServerWebApplicationFactory,但是两者产生的结果相同。

不起作用的API项目的Startup.cs是这样的:

public class Startup
{
    private IConfiguration Configuration { get; }
    private IHostingEnvironment CurrentEnvironment { get; set; }

    public Startup(IConfiguration configuration, IHostingEnvironment env)
    {
        Configuration = new ConfigurationBuilder()
              .AddEnvironmentVariables()
              .BuildWithSettings(env);

        CurrentEnvironment = env;
    }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddSession(options =>
        {
            options.IdleTimeout = TimeSpan.FromMinutes(2);
            options.Cookie.HttpOnly = true;
        });

        services.AddLogging(builder =>
        {
            builder.SetMinimumLevel(LogLevel.Trace);
            builder.AddGelf(options =>
            {
                options.Host = Graylog.Hostname;
                options.Port = Graylog.Port;
                options.LogSource = "Project2.Payment";
            });
            builder.AddFilter("Microsoft", LogLevel.None);
            builder.AddFilter("System", LogLevel.None);
            builder.AddFilter("Engine", LogLevel.None);
        });

        services.Configure<RequestLocalizationOptions>(options =>
        {
            var supportedCultures = new[]
            {
                new CultureInfo("pt-BR"),
            };

            options.DefaultRequestCulture = new RequestCulture("pt-BR");
            options.SupportedCultures = supportedCultures;
            options.SupportedUICultures = supportedCultures;

        });

        Configuration.GetSection("EnvironmentConfiguration").Get<EnvironmentConfiguration>().Initialize(CurrentEnvironment.EnvironmentName);

        services.AddHttpContextAccessor();
        services
            .AddMvc()
            .AddJsonOptions(opt =>
            {
                opt.SerializerSettings.ContractResolver = new DefaultContractResolver();
            })
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
            app.UseDeveloperExceptionPage();
        else
            app.UseHsts();


        app.UseCors(builder =>
        {
            builder.AllowAnyOrigin()
                    .AllowAnyHeader()
                    .WithMethods("POST", "GET", "DELETE", "PUT");
        });

        app.UseSession();
        app.UseHttpsRedirection();
        app.UseCoreAuthenticationS2P();
        app.UseMvc();
    }
}

对其中一个API的所有测试都能正常工作,但对另一个API的所有测试都给我相同的结果:在测试的路由上,此时出现“对象引用未设置为对象的实例”异常:< / p>

private IHttpContextAccessor accessor;
//...
if (string.IsNullOrWhiteSpace(transaction.IpAddress))
{
    transaction.IpAddress = objectToProcess.HttpContext.Connection.RemoteIpAddress.ToString();
}

尝试将RemoteIpAddress更改为RemoteIpAddress?,在到达请求的这一点时,它给了我The remote server returned an error: (403) Ip Forbidden

using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
    if (response.StatusCode == HttpStatusCode.OK)
    {
        string responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
        responseObject = JsonConvert.DeserializeObject(responseString);
    }
}

TestServer是通过非常简单的方式构建在TestSetup类上的:

[OneTimeSetUp]
public void SetUp()
{
    var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production";

    //This one works fine

    _testServer1 = new TestServer(WebHost.CreateDefaultBuilder()
        .UseStartup<Project1.Startup>()
        .UseEnvironment(environment));

    _client1 = _testServer1.CreateClient();
    _client1.DefaultRequestHeaders.Add(tokenType, apiToken);

    //This one DOESN'T!

    _testServer2 = new TestServer(WebHost.CreateDefaultBuilder()
        .UseStartup<Project2.Startup>()
        .UseEnvironment(environment));

    _client2 = _testServer2.CreateClient();
    _client2.DefaultRequestHeaders.Add(tokenType, apiToken);
}

我的主要问题是,我不是这种测试的初学者,而且对于如何解决此问题我一无所知,而且如果没有其他人的同意,我将无法对API项目进行更改,并且即使我不需要它,老实说,我也不知道如何或可以改变什么来解决这个问题。我为此花费了很多天,而我确实没有发现任何东西可以帮助我解决甚至无法解释为什么它对一个项目有效而对另一个项目无效。

任何帮助将不胜感激。预先感谢。

0 个答案:

没有答案