In my simple Index() ActionMethod I reference the User.Identity property. So, I thought that I need to mock that.
So i create a some mock HomeController and use that in my unit test. When I do that, the ActionMethod returns null as the view. When I replace the mock’d controller with a concrete instance (and of course comment out any reference to User.Identity) then the correct view is returned.
eg.
// Arrange.
var homeController = Mock<HomeController>(..);
homeController.Setup(x => x.User).Returns(new GenericPrincipal(..));
// Act.
var result = homeController.Index();
// Assert.
Assert.IsNotNull(result); // This fails here. result is NULL.
but when I do this (and comment out any User reference), it works…
// Arrange.
var homeController = new HomeController(..);
// Act.
var result = homeController.Index();
// Assert.
Assert.IsNotNull(result); // Tick!
Any ideas why this is?
I think you should be mocking a HttpContext for the controller to work with. I provided one on another answer that you could use. As Steve Rowbotham says, you should be mocking the dependencies of the system under test (i.e. the dependencies of the controller) and not mocking the system under test itself; you want to test the real version of the controller not a mock 🙂
Using the
HttpContextBaseclass from the link, you would simply do the following in your testYou may go a step further and create Setup and TearDown methods to set the controller up with a mocked context.