简体   繁体   English

我怎么能模拟HttpRequest []索引器属性

[英]How can I Mock HttpRequest[] indexer property

I'm adding unit tests to a large legacy codebase written in C#/ASP.NET/webforms. 我正在将单元测试添加到用C#/ ASP.NET / webforms编写的大型遗留代码库中。 We are using MOQ and XUnit. 我们正在使用MOQ和XUnit。 We've been able to mock query string values using syntax like: 我们已经能够使用以下语法模拟查询字符串值:

Mock<HttpRequestBase> request = new Mock<HttpRequestBase>();
NameValueCollection queryStringParams = new NameValueCollection();
queryStringParams.Add("name", "Fred Jones");
request.Setup(x => x.QueryString).Returns(queryStringParams);

That allows this code to work fine: 这允许此代码正常工作:

string name = _mockRequest.QueryString["name"];

The problem is that sprinkled throughout the codebase are many calls to get query string variables or form variables in the form of: 问题是在整个代码库中散布了很多调用来获取查询字符串变量或表单形式的变量:

string name = HttpContext.Current.Request["name"];

The indexer apparently looks in all the various collections: query strings, form values, cookies, and server variables. 索引器显然查看了所有各种集合:查询字符串,表单值,cookie和服务器变量。 I don't want to introduce a lot of potential side effects by refactoring the production code to use a single one of these collections. 我不想通过重构生产代码来使用这些集合中的单个集合来引入许多潜在的副作用。

Does anyone know a way to mock that indexer on the HttpRequest? 有没有人知道在HttpRequest上模拟该索引器的方法?

I figured this one out, it was simpler than I was making it. 我想出了这个,它比我做的简单。

//
// Set a variable in the indexer collction
//
Mock<HttpRequestBase> request = new Mock<HttpRequestBase>();
request.SetupGet(r => r["name"]).Returns("Fred Jones");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM