views:

52

answers:

1

I'm using this helper method to turn my PartialViewResult into string and returning it as Json - http://www.atlanticbt.com/blog/asp-net-mvc-using-ajax-json-and-partialviews/

My problem is that I'm using Moq to mock the controller, and whenever I run unit test that uses this RenderPartialViewToString() method, I got the "Object reference not set to an instance of an object." error on 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 a proxy controller, and maybe it's the reason why I got that error. Any idea how to unit testing this?

Thank you very much.

A: 

try this:

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);
        }
Omu
Hi Omu, I'm having this error on this line: `ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);` The error is "The RouteData must contain an item named 'controller' with a non-empty string value." Thanks.
Saxman
@saxman try adding it
Omu
I tried but no luck, same error :( *** Edited *** How do you manually add a controller variable to the RouteData?
Saxman
add your stuff between these 2 lines: var routes = new RouteCollection(); RouteConfigurator.RegisterRoutesTo(routes);
Omu
Tried that as well but no luck, same error on. Thanks.
Saxman
are you using some custom ViewEngine ?
Omu
No, I'm using the MVC ViewEngine, together with the method to renders the view as string. I'm not sure where the problem lies.
Saxman