• Home >>
  • ASP.NET Core >>

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:

Now you need to make use of this code inside your unit test:

That’s about it! Now you can pass this authService instance to your controller.

 

Ibrahim Šuta

Software Consultant interested and specialising in ASP.NET Core, C#, JavaScript, Angular, React.js.