首页 文章

使用Asp.Net Core TestServer在集成测试中设置虚拟IP地址

提问于
浏览
6

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

// ...

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(被测系统)并检索响应 .

在实际测试系统中,有一些组件从每个请求中提取发送方IP地址,如下所示:

HttpContext httpContext = ReceiveHttpContextDuringAuthentication();

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

现在在集成测试期间,这段代码无法找到IP地址,因为 RemoteIpAddress 始终为空 .

有没有办法将其设置为测试代码中的某个已知值?我在这里搜索了SO,但找不到类似的东西 . TA

1 回答

  • 9

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

    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 类:

    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>());
    

相关问题