根据您的描述,如果您想要使用 JWT 符号将请求发送到服务器并测试该属性是否有效,您只能使用整合测试,因为 JWT 认证验证包含许多单位, 如验证、设定索赔、检查索赔角色等等,使得这项测试不是单位测试。
有关如何使用整合测试的更多细节, 您可以设置 WebApplication Facoritory 如下:
public class BasicTests
: IClassFixture<WebApplicationFactory<Program>>
{
private readonly WebApplicationFactory<Program> _factory;
public BasicTests(WebApplicationFactory<Program> factory)
{
_factory = factory;
}
[Theory]
[InlineData("/MyController/MyEndpoint")]
public async Task Get_EndpointsReturnSuccessAndCorrectContentType(string url)
{
// Arrange
var client = _factory.CreateClient();
var token = "YOUR_VALID_JWT_TOKEN_WITH_ADMIN_ROLE";
// Add the JWT token to the request headers
client.DefaultRequestHeaders.Add("Authorization", $"Bearer {token}");
// Act
var response = await client.GetAsync(url);
// Assert
response.EnsureSuccessStatusCode(); // Status Code 200-299
Assert.Equal("text/html; charset=utf-8",
response.Content.Headers.ContentType.ToString());
}
}
更多细节, 您可以参考此 < a href=" "https://learn.microsoft. com/ en- us/aspnet/core/ test/ international- tests? view=aspnetcore- 800# 基本测试- with- default- Webapitfactfactory" rel= "nofollown norefererr" >link 。