gpt4 book ai didi

c# - 单元测试 AuthorizationHandler

转载 作者:太空狗 更新时间:2023-10-29 17:42:54 24 4
gpt4 key购买 nike

我在 .NET Core 2.1 中使用了基于资源的授权模式,如所述 here .我遇到的唯一问题是我不知道如何干净地测试我的 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 { }

最佳答案

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

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

/// <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
}

关于c# - 单元测试 AuthorizationHandler,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51272610/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com