Created
May 25, 2023 11:53
-
-
Save mocella/e9ff52986ed93876d0ef574d4259cd31 to your computer and use it in GitHub Desktop.
.NET6 HttpClient Test Helper
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Net; | |
using System.Net.Http.Headers; | |
using Moq; | |
using Moq.Protected; | |
using Newtonsoft.Json; | |
namespace Example.Test.Helpers; | |
public class HttpClientTestHelper | |
{ | |
private readonly Mock<HttpMessageHandler> _mockHandler; | |
public HttpClientTestHelper() | |
{ | |
_mockHandler = new Mock<HttpMessageHandler>(); | |
} | |
public HttpClientTestHelper WithResult<T>(T response, Uri requestUri) | |
{ | |
var mockResponse = new HttpResponseMessage() | |
{ | |
Content = new StringContent(JsonConvert.SerializeObject(response)), | |
StatusCode = HttpStatusCode.OK | |
}; | |
mockResponse.Content.Headers.ContentType = | |
new MediaTypeHeaderValue("application/json"); | |
_mockHandler | |
.Protected() | |
.Setup<Task<HttpResponseMessage>>( | |
"SendAsync", | |
ItExpr.Is<HttpRequestMessage>(m => m.RequestUri.OriginalString.Equals(requestUri.OriginalString)), | |
ItExpr.IsAny<CancellationToken>()) | |
.ReturnsAsync(mockResponse) | |
.Verifiable(); | |
return this; | |
} | |
public Mock<HttpMessageHandler> Build() | |
{ | |
return _mockHandler; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[Fact] | |
public async Task Should_Mock_HttpTraffic() | |
{ | |
// Arrange | |
var uri1 = new Uri("https://www.example.com/route1"); | |
var response = BuildExampleRoute1Response(); | |
var httpMockBuilder = new HttpClientTestHelper() | |
.WithResult(response, uri1); | |
if(conditionalThing) | |
{ | |
var uri2 = new Uri("https://www.example.com/route2"); | |
var response2 = BuildExampleRoute2Response(); | |
httpMockBuilder.WithResult(response2, uri2); | |
} | |
var httpMock = httpMockBuilder.Build(); | |
var mockedHttpClient = new HttpClient(secureCloudHttpMock.Object); | |
var someService = new SomeService( | |
mockedHttpClient, | |
_logger); | |
// Act | |
var result = await someService.GetInfo(); | |
// Assert | |
Assert.NotNull(result); | |
httpMockBuilder.VerifyAll(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment