Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I Mock HttpRequest[] indexer property

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?

like image 528
Lavamantis Avatar asked Feb 20 '23 11:02

Lavamantis


1 Answers

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");
like image 131
Lavamantis Avatar answered Feb 23 '23 14:02

Lavamantis