Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/opengl/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何模拟HttpRequest[]索引器属性_C#_Moq_Httprequest_Xunit - Fatal编程技术网

C# 如何模拟HttpRequest[]索引器属性

C# 如何模拟HttpRequest[]索引器属性,c#,moq,httprequest,xunit,C#,Moq,Httprequest,Xunit,我正在将单元测试添加到用C#/ASP.NET/webforms编写的大型遗留代码库中。我们正在使用MOQ和XUnit。我们已经能够使用以下语法模拟查询字符串值: Mock<HttpRequestBase> request = new Mock<HttpRequestBase>(); NameValueCollection queryStringParams = new NameValueCollection(); queryStringParams.Add("name",

我正在将单元测试添加到用C#/ASP.NET/webforms编写的大型遗留代码库中。我们正在使用MOQ和XUnit。我们已经能够使用以下语法模拟查询字符串值:

Mock<HttpRequestBase> request = new Mock<HttpRequestBase>();
NameValueCollection queryStringParams = new NameValueCollection();
queryStringParams.Add("name", "Fred Jones");
request.Setup(x => x.QueryString).Returns(queryStringParams);
问题在于,在整个代码库中散布着许多调用,以获取以下形式的查询字符串变量或表单变量:

string name = HttpContext.Current.Request["name"];
索引器显然会查看所有不同的集合:查询字符串、表单值、cookie和服务器变量。我不想通过重构生产代码来使用这些集合中的一个来引入很多潜在的副作用


有人知道在HttpRequest上模仿索引器的方法吗?

我想出了这个方法,它比我做的要简单

//
// Set a variable in the indexer collction
//
Mock<HttpRequestBase> request = new Mock<HttpRequestBase>();
request.SetupGet(r => r["name"]).Returns("Fred Jones");
//
//在索引器集合中设置一个变量
//
模拟请求=新建模拟();
request.SetupGet(r=>r[“name”])。返回(“Fred Jones”);

WebForms还是MVC?使用MVC,您可以设置控制器。ControllerContext查看MVC contrib测试帮助程序。这个链接可能会有所帮助:是的,我们正在按照那篇文章的建议模拟上下文和请求。正是这个特定的索引器给了我们问题。
//
// Set a variable in the indexer collction
//
Mock<HttpRequestBase> request = new Mock<HttpRequestBase>();
request.SetupGet(r => r["name"]).Returns("Fred Jones");