0

I am trying to write unit tests for the following code:

m_Client.SendAsync(request).ContinueWith(responseTask =>
{
    HttpResponseMessage response = responseTask.Result;

    try
    {
        string str = response.Content.ReadAsStringAsync().Result;

        // ...
    }
    catch
    {
        // process exception here
    }
}

Is it possible to emulate exception of any kind during the ReadAsStringAsync execution?

walruz
  • 1,135
  • 1
  • 13
  • 33
  • U could use dependency injection. Here is a example : https://www.c-sharpcorner.com/UploadFile/dacca2/unit-test-using-mock-object-in-dependency-injection/ – Connor Stoop Mar 30 '21 at 07:39
  • 5
    If you are writing tests, it would make sense to write them for the modern C# language using the async and await pattern, not calling Result and not using ContinueWith unless you have a specific need to do so – TheGeneral Mar 30 '21 at 07:43
  • @ConnorStoop I am already using Mock of HttpMessageHandler to substitute SendAsync call – walruz Mar 30 '21 at 07:45
  • @TheGeneral Problem is that I am testing legacy code and I have been told to avoid making changes to it (if it aint't broke - don't fix it, you know) – walruz Mar 30 '21 at 07:50
  • 1
    @walruz a) It _is_ broken. b) _what_ do you want to test here? Whether `ReadAsStringAsync` gets called or its implementation? The former makes sense, the latter not so much. – Fildor Mar 30 '21 at 08:48
  • @Fildor I want to test that object is able to properly handle exception caused by ReadAsStringAsync – walruz Mar 30 '21 at 09:24

0 Answers0