I need to inject mocked version of httpclient into my controller. I have read some topics like this Mocking HttpClient in unit tests but it does not solve my case.
[Fact]
public async Task given_invalid_user_should_return_bad_request()
{
User user = new User () { code ommited... };
var response = await Client.PostAsync("api/createuser", user);
response.StatusCode.Should().BeEquivalentTo(HttpStatusCode.BadRequest);
}
This is my controller
public class UserController : ControllerBase
{
private readonly IHttpClientFactory _httpClientFactory;
public U10Controller(IHttpClientFactory httpClientFactory)
{
_httpClientFactory = httpClientFactory;
}
[HttpPost]
public async Task<HttpResponseMessage> CreateUser([FromBody] User user)
{
var client = _httpClientFactory.CreateClient();
var result = await client.PostAsync(externalEndPointAddress, user);
if (task.StatusCode == HttpStatusCode.NotFound)
return new HttpResponseMessage(HttpStatusCode.BadRequest);
}
}
The thing is, my CreateUser() method calls an external system. I would like to inject mocked version of this service and because of that I am injecting IHttpClient through constructor, but don't know how to inject mocked version. A lot of code was ommited to increase readability.