gpt4 book ai didi

c# - 在 C# 单元测试中使用 HttpContext.GetTokenAsync

转载 作者:行者123 更新时间:2023-12-01 21:54:34 37 4
gpt4 key购买 nike

我正在尝试为我的 Controller 类编写单元测试,该类使用以下命令检索 token :

string token = await HttpContext.GetTokenAsync("access_token");

因此我用以下代码模拟了 HttpContext:

public static HttpContext MakeFakeContext()
{
var serviceProvider = new Mock<IServiceProvider>();
var authservice = new Mock<IAuthenticationService>();

authservice.Setup(_ => _.GetTokenAsync(It.IsAny<HttpContext>(), It.IsAny<string>())).Returns(Task.FromResult("token"));
serviceProvider.Setup(_ => _.GetService(typeof(IAuthenticationService))).Returns(authservice);

return new DefaultHttpContext
{
RequestServices = serviceProvider.Object
};
}

我正在设置模拟上下文:

var mockcontext = MakeFakeContext();

unitUnderTest.ControllerContext = new ControllerContext
{
HttpContext = mockcontext
};

现在,当我运行单元测试时,出现以下错误:

System.NotSupportedException : Unsupported expression: _ => _.GetTokenAsync(It.IsAny(), It.IsAny()) Extension methods (here: AuthenticationTokenExtensions.GetTokenAsync) may not be used in setup / verification expressions.

在我的研究过程中,我偶然发现了一些解决方案,您可以在这些解决方案中模拟幕后涉及的不属于扩展的特定部分。其中一些:Moq IServiceProvider / IServiceScope , How to unit test HttpContext.SignInAsync()? 。第二个显示了类似的问题,在我尝试后似乎有效。但由于某种原因,它不适用于 GetTokenAsync 方法。

你们有什么提示吗?

最佳答案

这里以 Zer0 的答案为基础,是一个使用 Moq 的示例:

    private void MockHttpContextGetToken(
Mock<IHttpContextAccessor> httpContextAccessorMock,
string tokenName, string tokenValue, string scheme = null)
{
var authenticationServiceMock = new Mock<IAuthenticationService>();
httpContextAccessorMock
.Setup(x => x.HttpContext.RequestServices.GetService(typeof(IAuthenticationService)))
.Returns(authenticationServiceMock.Object);

var authResult = AuthenticateResult.Success(
new AuthenticationTicket(new ClaimsPrincipal(), scheme));

authResult.Properties.StoreTokens(new[]
{
new AuthenticationToken { Name = tokenName, Value = tokenValue }
});

authenticationServiceMock
.Setup(x => x.AuthenticateAsync(httpContextAccessorMock.Object.HttpContext, scheme))
.ReturnsAsync(authResult);
}

关于c# - 在 C# 单元测试中使用 HttpContext.GetTokenAsync,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60602018/

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