carlpaton / carlpaton.github.io

1 stars 2 forks source link

Alternative Built-In way to call public HandleAsync() method in Unit Tests for a custom authorization handler #1

Open seantleonard opened 2 years ago

seantleonard commented 2 years ago

I ran across your article / github page while trying to figure out how to unit test my custom authorization handler. Thank you for posting!

I believe you could accomplish the unit testing you're seeking for AuthorizationHandler by creating a AuthorizationHandlerContext instance by using this constructor to supply the ClaimsPrincipal, object, and IAuthorizationRequirement. That way you can then call the public method HandleAsync(AuthorizationHandlerContext context) from your unit testing code.

So, something like the following would mean you don't have to override a protected method

            AuthorizationHandlerContext context = new(requirements: new List<IAuthorizationRequirement> { _sampleRequirement }, user: user, resource: object);
            CustomAuthorizationHandler handler = new();
            await handler.HandleAsync(context);

Ultimately, for the specific use case you document, at this point, you wouldn't need to create an additional class to expose the protected method. Thoughts?

carlpaton commented 2 years ago

Hello @seantleonard

Ah great, hope the post helped you find the best solution for your problem.

Thank you so much for opening this issue and suggesting an alternative - this kind of collaboration is the reason I post content and actively seek out feedback. Good on you!

My work around is a total hack brother! I'll certainly give your suggestion a go and add it to the post with credit to this issue.

I've had luck using constructors when Mocking HttpClient SendAsync so pretty keen to give it a try!

Cheers!