I'm adding unit tests to a large legacy codebase written in C#/ASP.NET/webforms. We are using MOQ and 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. 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?
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With