简体   繁体   English

使用 Moq 测试 HttpClient RequestClientCredentialsTokenAsync

[英]Using Moq to test HttpClient RequestClientCredentialsTokenAsync

I am trying to mock an Http Client that uses the IdentityModel extension to request a client credentials token.我正在尝试模拟使用 IdentityModel 扩展请求客户端凭据令牌的 Http 客户端。

var tokenResponse = await _httpClient.RequestClientCredentialsTokenAsync(requestContent);

I started doing the setup with:我开始进行设置:

var httpClient = new Mock<HttpClient>();


var httpResponseMessage = new HttpResponseMessage(HttpStatusCode.OK)
{
    Content = JsonContent.Create(new
    {
        access_token = "token",
        expires_in = 5000
    })
};

var tokenResponse = ProtocolResponse.FromHttpResponseAsync<TokenResponse>(httpResponseMessage);

httpClient.Setup(x => x.RequestClientCredentialsTokenAsync(It.IsAny<ClientCredentialsTokenRequest>(), It.IsAny<CancellationToken>())).Returns(tokenResponse);

But i end up with:但我最终得到:

System.NotSupportedException: Unsupported expression: x => x.RequestClientCredentialsTokenAsync(It.IsAny(), It.IsAny()) Extension methods (here: HttpClientTokenRequestExtensions.RequestClientCredentialsTokenAsync) may not be used in setup / verification expressions. System.NotSupportedException:不支持的表达式:x => x.RequestClientCredentialsTokenAsync(It.IsAny(), It.IsAny()) 扩展方法(此处:HttpClientTokenRequestExtensions.RequestClientCredentialsTokenAsync)不能用于设置/验证表达式。

How can i mock the RequestClientCredentialsTokenAsync extension?我如何模拟RequestClientCredentialsTokenAsync扩展?

Looking at the internals of RequestClientCredentialsTokenAsync we can see that the base request it is using is SendAsync, so we need to mock SendAsync.查看 RequestClientCredentialsTokenAsync 的内部结构,我们可以看到它使用的基本请求是 SendAsync,因此我们需要模拟 SendAsync。

Extension call:分机呼叫:

response = await client.SendAsync(request, cancellationToken).ConfigureAwait();

Final Setup:最终设置:

var httpClient = new Mock<HttpClient>();

var httpResponseMessage = new HttpResponseMessage(HttpStatusCode.OK)
{
    Content = JsonContent.Create(new
    {
        access_token = "token",
        expires_in = 5000
    })
};

httpClient.Setup(x => x.SendAsync(It.IsAny<HttpRequestMessage>(), It.IsAny<CancellationToken>())).Returns(Task.FromResult(httpResponseMessage));

Result:结果: 结果

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM