0

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.

justme
  • 316
  • 3
  • 13
  • I see no value in unit testing this type of boilerplate code. I personally think its a waste. If needed, you should unit test business logic. Purists will probably disagree with me, but whatever. – William Xifaras May 20 '19 at 13:52
  • Could you explain why this is waste? I am not personally convinced too. – justme May 20 '19 at 15:45
  • What is the point of unit testing the boilerplate HTTP code? What logic are you testing? HttpClientFactory is an implementation detail and it should be treated as such. With isolation. I've been down this road before. I personally think its a waste of time. I would focus on unit testing your business logic. – William Xifaras May 20 '19 at 17:09

0 Answers0