在单元测试HttpClient时模拟GetDiscoveryDocumentAsync可以使用模拟框架来模拟该方法的行为。以下是一个示例的解决方案:
var discoveryEndpointMock = new Mock<IDiscoveryEndpoint>();
discoveryEndpointMock.Setup(e => e.GetDiscoveryDocumentAsync()).ReturnsAsync(new DiscoveryDocument());
var httpClient = new HttpClient(new DiscoveryEndpointHandler(discoveryEndpointMock.Object));
public class DiscoveryEndpointHandler : DelegatingHandler
{
private readonly IDiscoveryEndpoint _discoveryEndpoint;
public DiscoveryEndpointHandler(IDiscoveryEndpoint discoveryEndpoint)
{
_discoveryEndpoint = discoveryEndpoint;
}
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
if (request.RequestUri.AbsoluteUri.EndsWith("/.well-known/openid-configuration"))
{
var discoveryDocument = await _discoveryEndpoint.GetDiscoveryDocumentAsync();
var response = new HttpResponseMessage(HttpStatusCode.OK);
response.Content = new StringContent(JsonConvert.SerializeObject(discoveryDocument), Encoding.UTF8, "application/json");
return response;
}
return await base.SendAsync(request, cancellationToken);
}
}
通过以上步骤,我们成功地模拟了GetDiscoveryDocumentAsync方法的行为,使得在单元测试中可以对HttpClient进行测试,而无需实际调用远程的Discovery Endpoint。
领取专属 10元无门槛券
手把手带您无忧上云