【发布时间】:2023-01-19 06:11:38
【问题描述】:
在遵循 Microsoft 的 ASP.NET Core 集成测试身份验证指南时,我为身份验证构建了以下测试:
[Fact]
public async Task Get_SecurePageIsReturnedForAnAuthenticatedUser()
{
// Arrange
var client = _factory.WithWebHostBuilder(builder =>
{
builder.ConfigureTestServices(services =>
{
services.AddAuthentication("Test")
.AddScheme<AuthenticationSchemeOptions, TestAuthHandler>(
"Test", options => {});
});
})
.CreateClient(new WebApplicationFactoryClientOptions
{
AllowAutoRedirect = false,
});
client.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Test");
//Act
var response = await client.GetAsync("/SecurePage");
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
我想要做的是使用 [Theory] 选项而不是 [Fact] 来测试多个身份验证,因此它看起来像这样:
[Theory]
[InlineData("TestAuth1","12345")]
[InlineData("TestAuth2","23456")]
[InlineData("TestAuth3","34567")]
public async Task Get_SecurePageIsReturnedForAnAuthenticatedUser(string claim, string claimsIdentity)
{
var claim = new Claim(claim, claimsIdentity);
.
.
.
但是我不确定如何通过 AddScheme<AuthenticationSchemeOptions, TestAuthHandler> 将声明传递给 TestAuthHandler
这是给定的 TestAuthHandler
public class TestAuthHandler : AuthenticationHandler<AuthenticationSchemeOptions>
{
public TestAuthHandler(IOptionsMonitor<AuthenticationSchemeOptions> options,
ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock)
: base(options, logger, encoder, clock)
{
}
protected override Task<AuthenticateResult> HandleAuthenticateAsync()
{
var claims = new[] { new Claim(ClaimTypes.Name, "Test user") };
var identity = new ClaimsIdentity(claims, "Test");
var principal = new ClaimsPrincipal(identity);
var ticket = new AuthenticationTicket(principal, "Test");
var result = AuthenticateResult.Success(ticket);
return Task.FromResult(result);
}
}
我想用传递给 Get_SecurePageIsReturnedForAnAuthenticatedUser(Claim claim) 的声明替换 HandleAuthenticaAsync() 中的声明变量
请注意,它们必须单独测试,因为只要 HandleAuthenticateAsync 声明变量中存在一个正确的身份验证,我当前的身份验证就会通过。
感谢您提供的任何帮助。
【问题讨论】:
标签: c# asp.net-core integration-testing