Get the App
SLTechnology News&Howtos  ›  Development  › 

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

Shulou Source: shulou.com Published: 2022-06-03 12:28:18 09月23日 Update

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.

Tags: Units tests code methods source code help examples analysis clarity success location content to this underlying ideas techniques articles novices more framework Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno macOS NVidia Xiaomi OPPO Reno Shulou Tech Info