How can I define the property of the HttpRequest [] indexer

I am adding unit tests to a large old codebase written in C # / ASP.NET / webforms. We use MOQ and XUnit. We managed to make fun of the values โ€‹โ€‹of the query string using syntax, for example:

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

This allows this code to work fine:

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

The problem is that there are many calls throughout the code base to get the string variables of the query or form variables in the form:

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

The indexer seems to be looking at all the different collections: query strings, form values, cookies, and server variables. I do not want to introduce many potential side effects, refactoring production code to use one of these collections.

Does anyone know a way to mock this index in HttpRequest?

+4
source share
1 answer

I realized this, it was easier than I did.

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

Source: https://habr.com/ru/post/1412696/


All Articles