Mocking IHttpContextAccessor and IAuthorizationService in ASP.NET Core unit tests
Today I did some refactoring of an ASP.NET Core project with a controller-service-repository architecture to add resource-based authorization. As a result of this, my service classes are derived from an abstract class that has IHttpContextAccessor and IAuthorizationService injected with dependency injection. As a result, unit tests of the service classes need mock implementations.
This shows exactly what is is that I am mocking for the unit tests:
Since the mocks are going to be needed for the tests of every service derived from this, I chose to put the mocks for these dependencies in an abstract class for service test classes:
For now this works, but I imagine I will need something more to cover tests of cases where the user is unauthenticated. In discovering the above solution, I found I could not use FindFirstValue of ClaimsPrincipal because I could not mock it due to it being an extension method.
Unit tests that use this will pass while in the running app things are failing if you forgot to register the authorization handler for dependency injection in Program.cs (I made this mistake today):