C# 如何使用NSubstitute模拟服务器变量

C# 如何使用NSubstitute模拟服务器变量,c#,.net-core,nunit,nsubstitute,C#,.net Core,Nunit,Nsubstitute,我使用以下方法获取用户的IP地址: 公共字符串GetUserIpAddress(HttpContext上下文) { var ipAddress=context.Request.ServerVariables[“HTTP_X_FORWARDED_FOR”]; 如果(!string.IsNullOrEmpty(ipAddress)) { 字符串[]地址=ipAddress.Split(','); if(addresses.Length!=0) { 返回地址[0]; } } 返回context.Req

我使用以下方法获取用户的IP地址:

公共字符串GetUserIpAddress(HttpContext上下文) { var ipAddress=context.Request.ServerVariables[“HTTP_X_FORWARDED_FOR”]; 如果(!string.IsNullOrEmpty(ipAddress)) { 字符串[]地址=ipAddress.Split(','); if(addresses.Length!=0) { 返回地址[0]; } } 返回context.Request.ServerVariables[“REMOTE_ADDR”]; } 我正试图为此编写一个单元测试,但很难做到(使用NSubstitute和NUnit)。我已经阅读了其他文章,到目前为止,这是我的尝试:

var request=Substitute.For();
request.ServerVariables.Returns(新System.Collections.Specialized.NameValueCollection
{
{“HTTP_X_FORWARDED_FOR”,“value here”}
});
var httpContext=Substitute.For();
httpContext.Request.Returns(请求);
var helper=new UserIpAddressHelper();
var result=helper.GetUserIpAddress(httpContext.ApplicationInstance.Context);

错误在于,当我希望使用上面的服务器变量对结果进行正确配置时,结果返回null。

HttpRequestBase
是专门为可测试而创建的,因为它是抽象的,因此可以被模拟框架覆盖

如果希望
GetUserIpAddress
可测试,请让它接受
HttpContextBase
实例:

public string GetUserIpAddress(HttpContextBase context)
如果需要从使用可包装的
HttpContext
的代码调用它:

HttpContext context;
var ipAddress = GetUserIpAddress(new HttpContextWrapper(context));