温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

ASP.NET Core单元测试中如何Mock HttpClient.GetStringAsync()的示例分析

发布时间:2021-09-17 09:50:36 来源:亿速云 阅读:113 作者:柒染 栏目:web开发

ASP.NET Core单元测试中如何Mock HttpClient.GetStringAsync()的示例分析,很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。

在 ASP.NET Core 单元测试中模拟HttpClient.GetStringAsync() 的技巧。

问题

下面这个代码

var html = await _httpClient.GetStringAsync(sourceUrl);

如果按正常思路像这样去 Mock HttpClient.GetStringAsync()

var httpClientMock = new Mock<HttpClient>(); httpClientMock     .Setup(p => p.GetStringAsync(It.IsAny<string>()))     .Returns(Task.FromResult("..."));

Moq 框架就会爆

Exception

System.NotSupportedException : Unsupported expression: p => p.GetStringAsync(It.IsAny())Non-overridable members (here: HttpClient.GetStringAsync) may not be used in setup / verification expressions.

解决方法

我们需要 Mock HttpClient 底层使用的 HttpMessageHandler 而不是 HttpClient

var handlerMock = new Mock<HttpMessageHandler>(); var magicHttpClient = new HttpClient(handlerMock.Object);

然后我花了 9.96 分钟研究了 HttpClient.GetStringAsync() 的源代码,发现它最终调用的是 SendAsync()  方法

private async Task<string> GetStringAsyncCore(HttpRequestMessage request, CancellationToken cancellationToken) {     // ...     response = await base.SendAsync(request, cts.Token).ConfigureAwait(false);     // ... }

源代码位置:https://source.dot.net/#System.Net.Http/System/Net/Http/HttpClient.cs,170

因此,我们的 Mock Setup 如下:

handlerMock     .Protected()     .Setup<Task<HttpResponseMessage>>(         "SendAsync",         ItExpr.IsAny<HttpRequestMessage>(),         ItExpr.IsAny<CancellationToken>()     )     .ReturnsAsync(new HttpResponseMessage     {         StatusCode = HttpStatusCode.OK,         Content = new StringContent("the string you want to return")     })     .Verifiable();

现在 Mock 就能运行成功了!

最后附上完整的 UT 代码供参考:

using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Moq; using Moq.Protected; using NUnit.Framework;  namespace Moonglade.Pingback.Tests {     [TestFixture]     public class PingSourceInspectorTests     {         private MockRepository _mockRepository;          private Mock<ILogger<PingSourceInspector>> _mockLogger;         private Mock<HttpMessageHandler> _handlerMock;         private HttpClient _magicHttpClient;          [SetUp]         public void SetUp()         {             _mockRepository = new(MockBehavior.Default);             _mockLogger = _mockRepository.Create<ILogger<PingSourceInspector>>();             _handlerMock = _mockRepository.Create<HttpMessageHandler>();         }          private PingSourceInspector CreatePingSourceInspector()         {             _magicHttpClient = new(_handlerMock.Object);             return new(_mockLogger.Object, _magicHttpClient);         }          [Test]         public async Task ExamineSourceAsync_StateUnderTest_ExpectedBehavior()         {             string sourceUrl = "https://996.icu/work-996-sick-icu";             string targetUrl = "https://greenhat.today/programmers-special-gift";              _handlerMock                 .Protected()                 .Setup<Task<HttpResponseMessage>>(                     "SendAsync",                     ItExpr.IsAny<HttpRequestMessage>(),                     ItExpr.IsAny<CancellationToken>()                 )                 .ReturnsAsync(new HttpResponseMessage                 {                     StatusCode = HttpStatusCode.OK,                     Content = new StringContent($"<html>" +                                                 $"<head>" +                                                 $"<title>Programmer's Gift</title>" +                                                 $"</head>" +                                                 $"<body>Work 996 and have a <a href=\"{targetUrl}\">green hat</a>!</body>" +                                                 $"</html>")                 })                 .Verifiable();             var pingSourceInspector = CreatePingSourceInspector();              var result = await pingSourceInspector.ExamineSourceAsync(sourceUrl, targetUrl);             Assert.IsFalse(result.ContainsHtml);             Assert.IsTrue(result.SourceHasLink);             Assert.AreEqual("Programmer's Gift", result.Title);             Assert.AreEqual(targetUrl, result.TargetUrl);             Assert.AreEqual(sourceUrl, result.SourceUrl);         }     } }

看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注亿速云行业资讯频道,感谢您对亿速云的支持。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI