我有一个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 回答
您可以编写中间件来设置自定义IP地址,因为此属性是可写的:
然后你可以像这样创建
StartupStub
类:并使用它来创建
TestServer
: