Reputation: 19396
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:
[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.
Upvotes: 1
Views: 263
Reputation: 119116
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>...);
Upvotes: 5