Search code examples
c#unit-testingservicemoqdotnet-httpclient

how to mock response from httpclient in c#, Azure functions, how to test


I have a static azure function that has an httpclient inside of a service.

public static void MyAzureFunction ()
{
    ........... 
    // inside run
    var service = new Service(...)

    var result = service.DoSomething(....);
}

on the other hand, I have the following:

public class Service
{
    ...//my properties
    public Service(...) {...}
    ...
    public Result DoSomething(...)
    {
        var httpClient = new HttpClient();
        //configuring httpClient
        var result = await httpClient.GetAsync(...);
    }    
}

How do I test this?

What I know:

  1. the service object is not injected into the Azure function, so I can't send a mock. It is created instead.
  2. the Azure function must belong to a static class, therefore I can't use virtual or override on methods to bypass anything and then mock them.

Solution

  • You can test this like any other program. In comparison, consider a console application. You typically don't test Main, because this is where you compose everything. The same goes for an ASP.NET application, where you rarely directly test Startup. Rather, you treat these as Humble Objects. While you don't test them, you also drain them of logic.

    Start-up code like that MyAzureFunction belongs to that category. While you may not be able to directly unit test that function, you can treat it as your function's Composition Root:

    public static void MyAzureFunction()
    {
       var service = new Service(new Dependency())
       var result = service.Dosomething(...);
    }
    

    The only thing the Composition Root should do is to compose an object graph and delegate to a single method that does all the work.

    This means that you can now test everything else, if you design it accordingly.

    Here, for example, we've changed Service so that it takes a dependency in its constructor. If you design that dependency so that it is properly polymorphic, you can now test Service with Test Doubles.