I have a Controller that call HttpContext like:
[Authorize(Roles = "Administrador")]
public class ApuradorController : Controller
{
private readonly Questiona2011Context _context = new Questiona2011Context();
private readonly AuthenticationService _authenticationService = new AuthenticationService();
}
The HttpContext is call in AuthenticationService class:
public class AuthenticationService
{
private IPrincipal _user = HttpContext.Current.User;
...
}
In my project where im test the controllers when I Instance the Controller a error is thrown in private IPrincipal _user = HttpContext.Current.User; Line: Object reference not set to an instance of an object.
What do I need to test my controllers?
The main thing that you miss is the knowledge of how to design ASP.NET MVC project for testing.
You should design your controller to use dependency injection. That is, controllers should not be using concrete implementation of AuthenticationService, but using IAuthenticationService, concrete implementation of which will be supplied in runtime. For now, when the controller is created, the AuthenticationService is also created. But in test scenario, HttpContext is null and Creating AuthenticationService is failing with NullReference exception. If you design that via interface, in testing purposes you will supply fake implementation of AuthenticationService to controller, and it will not throw exception.
In test scenario, you could use some mocking library for fake IAuthenticationService implementation, for example moq. And supply value for it via mocking
This time it will not throw exceptions.
The information mentioned above is not helpful if you do not understand principles of unit testable project design. For the quick start, read this link. For the further reading, address books about asp.net mvc, i would reccommend those by steven sanderson. The main idea of unit testable controller design is that you should have the ability to supply fake components to the controller, fake repositories, services, etc and leave real only the part of controller that is unit tested. Then test controller iteractions with those fake parts. The unit testing means testing that interactions. If interactions are correct, they will be correct with real implementations of those components. If they’re wrong, test fails.