0

Using MOQ to mock ASP.Net MVC controller, I follow this approach:

var fakeHttpContext = new Mock<HttpContextBase>();

fakeHttpContext.Setup(t => t.User).Returns(genericPrincipal);

var request = new Mock<HttpRequestBase>();

var controllerContext = new Mock<ControllerContext>();
controllerContext.Setup(t => t.HttpContext)
    .Returns(fakeHttpContext.Object);

var controller = InitMyontrollerConstroctor(controllerContext);

And Here is how I initialize mycontroller:

var controller = new MyController(IService service)
{
    ControllerContext = controllerContext.Object,
};

return controller;

But a read-only property exist inside of MyController, which depends on HttpContext:

private static readonly string ServerPath = System.Web.HttpContext.Current.Server.MapPath("~/content/");

public ProfileController(IService service)
{

}

When I try to initialize my controller, it throws "Object reference not set to an instance of an object." Not error. It is because HttpContext is null.

So, How can I supply HttpContext to my controller, without using as a parameter of the constructor.

Nkosi
  • 235,767
  • 35
  • 427
  • 472
Babak Fakhriloo
  • 2,076
  • 4
  • 44
  • 80
  • Do not couple your code to static `HttpContext`. That is only available at run time and is provided by IIS. Create a service to encapsulate that and inject it into the controller as well. – Nkosi May 19 '18 at 12:12
  • 1
    Possible duplicate of [How do I get fake path for HttpContext.Current.Server.MapPath which is assigned to protected object inside method unit testing?](https://stackoverflow.com/questions/38805765/how-do-i-get-fake-path-for-httpcontext-current-server-mappath-which-is-assigned) – Nkosi May 19 '18 at 12:27

0 Answers0