As the title suggests, I have some code that calls IHttpClientFactory.CreateClient() to create an HttpClient instance.
I'm doing this in .Net Core 3.1
I need to mock this. According to this question"C# Mock IHttpclient & CreateClient" the following should work...
[Test]
public void Mytest() {
var httpClientFactory = new Mock<IHttpClientFactory>(MockBehavior.Strict);
httpMessageHandler = new Mock<HttpMessageHandler>(MockBehavior.Strict);
httpMessageHandler.Protected()
// Setup the PROTECTED method to mock
.Setup<Task<HttpResponseMessage>>(
"SendAsync",
ItExpr.IsAny<HttpRequestMessage>(),
ItExpr.IsAny<CancellationToken>()
)
// prepare the expected response of the mocked http call
.ReturnsAsync(new HttpResponseMessage()
{
StatusCode = HttpStatusCode.BadRequest,
})
.Verifiable();
var httpClient = new HttpClient(httpMessageHandler.Object);
httpClientFactory.Setup(_ => _.CreateClient()) // This fails
.Returns(httpClient).Verifiable();
systemUnderTest = new MyService(httpClientFactory.Object);
var result = systemUnderTest.MyMethod()
// Assert Stuff
}
However, when I run it, the following is reported...
System.NotSupportedException : Unsupported expression: _ => _.CreateClient() Extension methods (here: HttpClientFactoryExtensions.CreateClient) may not be used in setup / verification expressions.
I'm clearly doing something wrong, but I can't see what it is.
Can anyone offer any pointers?