#unittest mockcontroller fakehttpcontext
Explore tagged Tumblr posts
manishdhoj-blog · 8 years ago
Text
Mocking .net objects in controller for unit tests
Recently I was writing some unit tests for the controller in the application I worked on. I ran into some issues creating fake objects and setting fake values for the .net classes and linked to the controller. Due to these objects creating unit tests for methods in controller was a little tricky. Here are some of my findings that I came across that may be helpful for others creating unit tests for mvc controller in .NET.
1. The controller class is always tied with the HttpContext. Faking a HttpContext maybe a first step to write a unit test. Below I have created an HttpContext class with no values. You can write the values according to your need
Create a Fake HttpContext public class MockHelpers     {         public static HttpContext FakeHttpContext()         {             var httpRequest = new HttpRequest("", "http://localhost/", "");             var stringWriter = new StringWriter();             var httpResponse = new HttpResponse(stringWriter);             var httpContext = new HttpContext(httpRequest, httpResponse);             return httpContext;         }     }
You can then consume the object like this HttpContext.Current = MockHelpers.FakeHttpContext();
2. There are multiple instances where you check for error in ModelState before moving forward with rest of the code. One issue I faced during writing test was to find a way to set the ModelState error to false. Setting this Boolean to false will allow you to test the case when an error occurs in the Model.
To set ModelState=false   controller.ModelState.AddModelError("test","testing controller...");   
3. There was an instance where I had to fake Url.Content(""). My test failed at this point because the virtualPath value was null. To resolve this I had to find a way to set virtualPath value. To do this   To set virtualpath
_context = new Mock<HttpContextBase>(); _context.Setup(c => c.Request.ApplicationPath).Returns("/tmp/testpath"); _context.Setup(c => c.Response.ApplyAppPathModifier(It.IsAny<string>())).Returns("/mynewVirtualPath/");
Upon doing this the code below will not fail. var urlBuilder = new UriBuilder(Request.Url.AbsoluteUri);
4. At one place I was faced with the problem of setting UrlHelper object. Here is how you fake urlHelper object.
To set UrlHelper.Url    var requestContext = new RequestContext(_context.Object, new RouteData());   var urlHelper = new UrlHelper(requestContext);    _controller.Url = urlHelper;
this was the code that was failing which resolved after UrlHelper was assigned to controller.
var path= Url.Content("~/images/test.png");
0 notes