Post
ASP.NET Core - Unit testing IAuthorizationService and dependencies inside of your controller
Unit Testing - IAuthorizationService, Requirement and Handler
You have a controller that makes use of IAuthorizationService and you have a custom requirement - implementation of IAuthorizationRequirement. You might also have your custom handler which is an implementation of IAuthorizationHandler.
As an honourable .NET Core citizen, you are doing some unit tests for your controller and you wonder how you can test that one pesky method which makes use of Authorization Service and uses your custom requirement and/or your custom handler. And to make the situation even worse, your handler depends on some other service, might be your repository, lovely…
Well, it turns out it isn’t that hard.
You need a small snippet that will build out the ServiceCollection used with DI and then you will get an instance of IAuthorizationService:
https://gist.github.com/Ibro/79e6bd4cb7c224f86c2fe5059de5d654
Now you need to make use of this code inside your unit test:
https://gist.github.com/Ibro/1eed7d987f66b8974d17da10fa1333f0
That’s about it! Now you can pass this authService instance to your controller.