Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@GeorgDangl
Last active October 6, 2021 13:47
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save GeorgDangl/c0a85589616cf3ddffff054ee7cb585d to your computer and use it in GitHub Desktop.
Save GeorgDangl/c0a85589616cf3ddffff054ee7cb585d to your computer and use it in GitHub Desktop.
Mock an Asp.Net Core HttpClient with a custom HttpMessageHandler using Moq
using System;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Moq;
using Moq.Protected;
namespace Tests
{
public class MockHttpClient
{
public HttpClient GetMockClient()
{
var mockHttpMessageHandler = new Mock<HttpMessageHandler>();
mockHttpMessageHandler.Protected()
.Setup<Task<HttpResponseMessage>>("SendAsync", ItExpr.IsAny<HttpRequestMessage>(), ItExpr.IsAny<CancellationToken>())
.Returns((HttpRequestMessage request, CancellationToken cancellationToken) => GetMockResponse(request, cancellationToken));
return new HttpClient(mockHttpMessageHandler.Object);
}
private Task<HttpResponseMessage> GetMockResponse(HttpRequestMessage request, CancellationToken cancellationToken)
{
if (request.RequestUri.LocalPath == "/expectedPath")
{
var response = new HttpResponseMessage(System.Net.HttpStatusCode.OK);
response.Content = new StringContent(GetAuthJson(), Encoding.UTF8, "application/json");
return Task.FromResult(response);
}
throw new NotImplementedException();
}
private string GetAuthJson()
{
return "{ \"isAuthenticated\": true }";
}
}
}
@spencerdavis2000
Copy link

is there a dependency needed for GetAuthJson() ?

@GeorgDangl
Copy link
Author

Hi @spencerdavis2000, I'v just added GetAuthJson(). This gist only shows a minimal example of what's required to get it working, so there's not much of an actual implementation there.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment