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
  • 10,331
  • 15
  • 20
  • 47
Polina F.
  • 629
  • 12
  • 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

0 Answers0