Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Example Analysis of how to Mock HttpClient.GetStringAsync () in ASP.NET Core Unit Test

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

ASP.NET Core unit test how to Mock HttpClient.GetStringAsync () example analysis, many novices are not very clear about this, in order to help you solve this problem, the following editor will explain in detail for you, people with this need can come to learn, I hope you can get something.

Techniques for simulating HttpClient.GetStringAsync () in ASP.NET Core unit tests.

problem

The following code

Var html = await _ httpClient.GetStringAsync (sourceUrl)

If you follow the normal way of thinking to Mock HttpClient.GetStringAsync () like this.

Var httpClientMock = new Mock (); httpClientMock .setup (p = > p.GetStringAsync (It.IsAny () .Retreat (Task.FromResult ("...")); the Moq frame will explode

Exception

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

We need the HttpMessageHandler used at the bottom of Mock HttpClient instead of HttpClient

Var handlerMock = new Mock (); var magicHttpClient = new HttpClient (handlerMock.Object)

Then I spent 9.96 minutes studying the source code of HttpClient.GetStringAsync () and found that it ended up calling the SendAsync () method.

Private async Task GetStringAsyncCore (HttpRequestMessage request, CancellationToken cancellationToken) {/ /. Response = await base.SendAsync (request, cts.Token) .ConfigureAwait (false); / /...}

Source code location: https://source.dot.net/#System.Net.Http/System/Net/Http/HttpClient.cs,170

Therefore, our Mock Setup is as follows:

HandlerMock .protected () .setup ("SendAsync", ItExpr.IsAny (), ItExpr.IsAny ()) .ReturnsAsync (new HttpResponseMessage {StatusCode = HttpStatusCode.OK, Content = new StringContent ("the string you want to return")}) .Veriforth ()

Now Mock can run successfully!

Finally, the complete UT code is attached for reference:

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 _ mockLogger; private Mock _ handlerMock; private HttpClient _ magicHttpClient [SetUp] public void SetUp () {_ mockRepository = new (MockBehavior.Default); _ mockLogger = _ mockRepository.Create (); _ handlerMock = _ mockRepository.Create ();} 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 ("SendAsync", ItExpr.IsAny (), ItExpr.IsAny ()) .ReturnsAsync (new HttpResponseMessage {StatusCode = HttpStatusCode.OK) Content = new StringContent ($"" + $"+ $" Programmer's Gift "+ $" + $"Work 996 and have a green hat!" + $"")}) .Verified () 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) } is it helpful for you to read the above content? If you want to know more about the relevant knowledge or read more related articles, please follow the industry information channel, thank you for your support.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report