ASP.NET MVC - unit testing of RenderPartialViewToString () with Moq framework?

I use this helper method to turn the PartialViewResult into a string and return it as Json - http://www.atlanticbt.com/blog/asp-net-mvc-using-ajax-json-and-partialviews/

My problem is that I use Moq to mock the controller, and whenever I run the unit test, which uses this RenderPartialViewToString () method, I get the link "Object not installed to object instance". error in ControllerContext.

private ProgramsController GetController() { var mockHttpContext = new Mock<ControllerContext>(); mockHttpContext.SetupGet(p => p.HttpContext.User.Identity.Name).Returns("test"); mockHttpContext.SetupGet(p => p.HttpContext.Request.IsAuthenticated).Returns(true); // Mock Repositories var mockOrganizationRepository = new MockOrganizationRepository(MockData.MockOrganizationsData()); var mockIRenderPartial = new BaseController(); var controller = new ProgramsController(mockOrganizationRepository, mockIRenderPartial); controller.ControllerContext = mockHttpContext.Object; return controller; } 

This returns the proxy controller, and maybe this is the reason I got this error. Any idea how to check this?

Many thanks.

+5
unit-testing asp.net-mvc moq asp.net-mvc-2
source share
1 answer

try the following:

 public static void SetContext(this Controller controller) { var httpContextBase = new Mock<HttpContextBase>(); var httpRequestBase = new Mock<HttpRequestBase>(); var respone = new Mock<HttpResponseBase>(); var session = new Mock<HttpSessionStateBase>(); var routes = new RouteCollection(); RouteConfigurator.RegisterRoutesTo(routes); httpContextBase.Setup(x => x.Response).Returns(respone.Object); httpContextBase.Setup(x => x.Request).Returns(httpRequestBase.Object); httpContextBase.Setup(x => x.Session).Returns(session.Object); session.Setup(x => x["somesessionkey"]).Returns("value"); httpRequestBase.Setup(x => x.Form).Returns(new NameValueCollection()); controller.ControllerContext = new ControllerContext(httpContextBase.Object, new RouteData(), controller); controller.Url = new UrlHelper(new RequestContext(controller.HttpContext, new RouteData()), routes); } 
+4
source share

All Articles