单元测试AuthorizationHandler

时间:2018-07-10 19:17:54

标签: c# unit-testing asp.net-core authorization asp.net-core-2.0

我使用了here中所述的.NET Core 2.1中基于资源的授权模式。我唯一的问题是我不知道如何干净地测试AuthorizationHandler

这里有人做过类似的事情吗?

AuthorizationHandler示例(来自上面的链接):

public class DocumentAuthorizationHandler : 
    AuthorizationHandler<SameAuthorRequirement, Document>
{
    protected override Task HandleRequirementAsync(AuthorizationHandlerContext context,
                                                   SameAuthorRequirement requirement,
                                                   Document resource)
    {
        if (context.User.Identity?.Name == resource.Author)
        {
            context.Succeed(requirement);
        }

        return Task.CompletedTask;
    }
}

public class SameAuthorRequirement : IAuthorizationRequirement { }

1 个答案:

答案 0 :(得分:6)

所有必需的依赖项都可用于隔离的单元测试。

可以通过Task HandleAsync(AuthorizationHandlerContext context)来访问所需的测试方法HandleRequirementAsync

/// <summary>
/// Makes a decision if authorization is allowed.
/// </summary>
/// <param name="context">The authorization context.</param>
public virtual async Task HandleAsync(AuthorizationHandlerContext context)
{
    if (context.Resource is TResource)
    {
        foreach (var req in context.Requirements.OfType<TRequirement>())
        {
            await HandleRequirementAsync(context, req, (TResource)context.Resource);
        }
    }
}

该成员仅依赖于AuthorizationHandlerContext,后者具有如下构造函数

public AuthorizationHandlerContext(
    IEnumerable<IAuthorizationRequirement> requirements,
    ClaimsPrincipal user,
    object resource) {

    //... omitted for brevity
}

Source

用于验证DocumentAuthorizationHandler预期行为的简单隔离单元测试。

public async Task DocumentAuthorizationHandler_Should_Succeed() {
    //Arrange    
    var requirements = new [] { new SameAuthorRequirement()};
    var author = "author";
    var user = new ClaimsPrincipal(
                new ClaimsIdentity(
                    new Claim[] {
                        new Claim(ClaimsIdentity.DefaultNameClaimType, author),
                    },
                    "Basic")
                );
    var resource = new Document {
        Author = author
    };
    var context = new AuthorizationHandlerContext(requirements, user, resource);
    var subject = new DocumentAuthorizationHandler();

    //Act
    await subject.HandleAsync(context);

    //Assert
    context.HasSucceeded.Should().BeTrue(); //FluentAssertions
}