How to Mock an Object Request in Unit Testing with asp.net mvc application

I am working on an asp.net mvc 3.0 application. In the module testing one of the action methods in my controller, I received an error.

How to taunt: Request.Params["FieldName"]

I turned on the Moq framework, but was not sure how to pass the value

Here is my code ... Please suggest ...

  var request = new Mock<System.Web.HttpRequestBase>(); request .SetupGet(x => x.Headers) .Returns( new System.Net.WebHeaderCollection { {"X-Requested-With", "XMLHttpRequest"} }); var context = new Mock<System.Web.HttpContextBase>(); context.SetupGet(x => x.Request).Returns(request.Object); ValidCodeController target = new ValidCodeController(); target.ControllerContext = new ControllerContext(context.Object, new RouteData(), target); 
+6
source share
2 answers

Params is a NameValueCollection property that can be configured similarly to Headers :

 var requestParams = new NameValueCollection { { "FieldName", "value"} }; request.SetupGet(x => x.Params).Returns(requestParams); 
+9
source

Another alternative to bullying the Context and all its dependencies is to abstract the entire collection of context / Params into a separate class and instead simulate it. In many cases, this will simplify the work and avoid the displacement of the complex graph of the object:

Example:

 public void MainMethod() { var valueInQuestion = ISomeAbstraction.GetMyValue("FieldName"); } 

Now you can mock the GetMyValue method.

0
source

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


All Articles