Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

When I mock IHttpClientFactory and create a HttpClient, HttpClient is null

I would like to unit test a factory in which I inject IHttpClientFactory and this factory create a class that uses a HttpClient.

This is the code:

public class ClientFactory : IClientFactory
{
    private readonly IHttpClientFactory _httpClientFactory;



    public ClientFactory(IHttpClientFactory paramHttpClientFactory)
    {
        _httpClientFactory = paramHttpClientFactory;
    }



    public CLient CreateClient(ClientCofiguron paramConfiguration)
    {
        HttpClient httpClient = _httpClientFactory.Create();

        //Configure httpClient
    }
}

And this is how I try to test using xUint:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[Fact]
public async Task Create_Client()
{
    var httpClientFactory = new Mock<IHttpClientFactory>();

    IClientFactory ClientFactory = new FactoriaSolicitanteFichero(httpClientFactory.Object);
    Client = clientFactory.CreateCLient(...);
}

The problem is that in the mthod ClientFactory.CreateClient, the httpClient that is created i null, so I can use the HttpClient to create the client.

I guess that I using Moq in an incorrect way. How should I mock the HttpClientFactory?

Thank.

>Solution :

You have mocked IHttpClientFactory but not told it what to return when CreateClient is called, so it is going to return null.

You need to do this:

var httpClientFactory = new Mock<IHttpClientFactory>();
httpClientFactory
    .Setup(f => f.CreateClient(It.IsAny<string>()))
    .Returns(...<your code to create a client>...);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading