ASP.NET MVC - unit testing, mocking HttpContext without using any mock structure

Since I had a problem with unit testing of RenderPartialViewToString () with Moq framework ( ASP.NET MVC - unit testing of RenderPartialViewToString () with Moq framework? ), I, however, am thinking of connecting my controller directly without using Moq for this a specific test, how do I mock (or install) an HttpContext for my test without using any Moq framework?

I need to do something similar, without Moq, of course:

var mockHttpContext = new Mock<ControllerContext>(); mockHttpContext.SetupGet(p => p.HttpContext.User.Identity.Name).Returns("n1\\test"); mockHttpContext.SetupGet(p => p.HttpContext.Request.IsAuthenticated).Returns(true); 

Many thanks.

+6
unit-testing asp.net-mvc asp.net-mvc-2
source share
2 answers

You can mock it as follows and declare a stringBuilder object that accepts the output.

  var response = new Mock<HttpResponseBase>(); response.Setup(x => x.Write(It.IsAny<string>())).Callback<string>(y => _stringBuilder.Append(y)); var url = new Uri("http://localhost/Home/"); var request = new Mock<HttpRequestBase>(); request.Setup(x => x.Url).Returns(url); request.Setup(x => x.ApplicationPath).Returns(""); var httpContext = new Mock<HttpContextBase>(); httpContext.Setup(x => x.Request).Returns(request.Object); httpContext.Setup(x => x.Response).Returns(response.Object); _controllerContext = new Mock<ControllerContext>(); _controllerContext.Setup(x => x.HttpContext).Returns(httpContext.Object); _homeController = autoMock.Create<HomeController>(); _homeController.ControllerContext = _controllerContext.Object; 

You perform your action as follows:

 var action=_homeController.Action(<parameters>); action.ExecuteResult(); 

and now your stringbuilder ie _stringBuilder object will produce the result, whatever it may be, and you can test it.

+2
source

If your controller needs authentication information from an HttpContext, I would:

  • Create a new class that wraps your calls. It looks like you want Name and IsAuthenticated. The new class may be AuthenticationService or something else.
  • In the methods / properties in the AuthenticationService, call the real HttpContext, for example HttpContext.Current.user.Identity.Name.
  • Create an interface over the new AuthenticationService with the public methods / properties you care about.
  • Inject IAuthenticationService into your control test in the constructor. It looks like you can already do this with other dependencies in the controller.
  • Now you can mock IAuthenticationService and this will return values ​​without having to call into a real HttpContext.

Here is more detailed information from the blog post I made http://www.volaresystems.com/Blog/post/2010/08/19/Dont-mock-HttpContext.aspx . I use RhinoMocks instead of Moq, but the concept is independent of HttpContext.

+3
source

All Articles