Testing user if he has a specific authority using AuthorizeAsync() in Xunit-Unit Testing

前端 未结 2 710
时光取名叫无心
时光取名叫无心 2021-01-14 15:25

The question has been Updated for better explanation to the issue I have,

Simply I have this controller,

    [Authorize]
    publi         


        
2条回答
  •  我在风中等你
    2021-01-14 15:59

    I encountered this issue as well while developing an ASP.NET Core API. My situation was less complex, so not sure if the same solutions is applicable for you.

    Here is my solution

    IAuthorizationService has two methods that are not extensions. One can assume (and I verified) that the extensions are just helpers and will call either one of these methods.

    Task AuthorizeAsync(ClaimsPrincipal user, object resource, IEnumerable requirements);
    Task AuthorizeAsync(ClaimsPrincipal user, object resource, string policyName);
    

    So mocking IAuthorizationService for me was as simple as doing the following:

    var authorizeService = new Mock();
    authorizeService.Setup(service => service.AuthorizeAsync(It.IsAny(), It.IsAny(), It.IsAny())).ReturnsAsync(AuthorizationResult.Success);
    
        

    提交回复
    热议问题