1

I am writing unit test for a simple function

public async Task<HttpResponseMessage> MakeRestCallAsync(Uri uri, string input)
{
    using (httpClient = new HttpClient())
    {
        using (var formData = new MultipartFormDataContent())
        {
            //add content to form data
            formData.Add(new StringContent(input), "Input");
            return await httpClient.PostAsync(uri, formData);          
        }
    }
}

I would like to test that httpClient fired the PostAsync I am using Microsoft.VisualStudio.TestTools.UnitTesting for the test project Can't find a proper way to do that Also if possible I would like to test that the call was actually made with the passed URI and passed input

Peter Csala
  • 17,736
  • 16
  • 35
  • 75
Polina F.
  • 629
  • 13
  • 32
  • 3
    Tight coupling is working against you here. Consider refactoring to either explicitly have the client injected or inject a factory that creates the client. From there it is simple to mock a handler to verify expected behavior. Check a similar answer I gave here https://stackoverflow.com/a/54227679/5233410 – Nkosi Nov 13 '21 at 21:29
  • 1
    Not related to unit testing, but please try to avoid to Dispose HttpClients in your code. Please read this old but gold article: [YOU'RE USING HTTPCLIENT WRONG AND IT IS DESTABILIZING YOUR SOFTWARE](https://www.aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong/) – Peter Csala Nov 15 '21 at 08:11
  • 1
    Alternative approach to start a server which can receive such post request, or use "mock" version of web server. – Fabio Nov 15 '21 at 08:11
  • @Fabio That would be more appropriate for a integration / bdd test than a unit test: for unit testing mocking a HttpClientHandler as Nkosi suggested is the way to go – auburg Nov 15 '21 at 09:59
  • @auburg any sample about it? Generally, How-to do unit testing for external API (like Fake API ) api.chucknorris.io ? **[simple-example-of-calling-rest-api-with-httpclient-in-net5.0](https://adamstorr.azurewebsites.net/blog/simple-example-of-calling-rest-api-with-httpclient-in-net5.0)** – Kiquenet Aug 31 '22 at 07:39

0 Answers0