在与Asp.Net Core TestServer的集成测试中设置虚拟IP地址 [英] Set dummy IP address in integration test with Asp.Net Core TestServer

查看:106
本文介绍了在与Asp.Net Core TestServer的集成测试中设置虚拟IP地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个C#Asp.Net Core(1.x)项目,实现了一个Web REST API,以及与之相关的集成测试项目,在进行任何测试之前,有一个类似于以下内容的设置:

I have a C# Asp.Net Core (1.x) project, implementing a web REST API, and its related integration test project, where before any test there's a setup similar to:

// ...

IWebHostBuilder webHostBuilder = GetWebHostBuilderSimilarToRealOne()
    .UseStartup<MyTestStartup>();

TestServer server = new TestServer(webHostBuilder);
server.BaseAddress = new Uri("http://localhost:5000");

HttpClient client = server.CreateClient();

// ...

在测试过程中,client用于将HTTP请求发送到Web API(被测系统)并检索响应.

During tests, the client is used to send HTTP requests to web API (the system under test) and retrieve responses.

在测试中的实际系统中,有一些组件会从每个请求中提取发件人IP地址,例如:

Within actual system under test there's some component extracting sender IP address from each request, as in:

HttpContext httpContext = ReceiveHttpContextDuringAuthentication();

// edge cases omitted for brevity
string remoteIpAddress = httpContext?.Connection?.RemoteIpAddress?.ToString()

现在,在集成测试中,由于RemoteIpAddress始终为空,所以这部分代码无法找到IP地址.

Now during integration tests this bit of code fails to find an IP address, as RemoteIpAddress is always null.

是否可以通过测试代码将其设置为某个已知值?我在此处搜索了SO,但找不到类似的内容. TA

Is there a way to set that to some known value from within test code? I searched here on SO but could not find anything similar. TA

推荐答案

由于此属性可写,因此您可以编写中间件来设置自定义IP地址:

You can write middleware to set custom IP Address since this property is writable:

public class FakeRemoteIpAddressMiddleware
{
    private readonly RequestDelegate next;
    private readonly IPAddress fakeIpAddress = IPAddress.Parse("127.168.1.32");

    public FakeRemoteIpAddressMiddleware(RequestDelegate next)
    {
        this.next = next;
    }

    public async Task Invoke(HttpContext httpContext)
    {
        httpContext.Connection.RemoteIpAddress = fakeIpAddress;

        await this.next(httpContext);
    }
}

然后您可以像这样创建StartupStub类:

Then you can create StartupStub class like this:

public class StartupStub : Startup
{
    public StartupStub(IConfiguration configuration) : base(configuration)
    {
    }

    public override void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        app.UseMiddleware<FakeRemoteIpAddressMiddleware>();
        base.Configure(app, env);
    }
}

并使用它来创建TestServer:

new TestServer(new WebHostBuilder().UseStartup<StartupStub>());

这篇关于在与Asp.Net Core TestServer的集成测试中设置虚拟IP地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆