Reputation: 35
How can I use stub to mock HTTP client while unit testing in c# code?
I don't want to use Moq because I have a method to create http client instance which is static but not virtual.
Code:
public static class HttpClientFactory
{
public static IHttpClient httpClient;
public static IHttpClient CreateHttpClient()
{
if(httpClient == null)
httpClient = new HttpClient();
return httpClient;
}
}
Upvotes: 0
Views: 423
Reputation: 44
Why can't you just make your IHttpClient
non-static and get rid of factory ?
public interface IHttpClient {}
public class HttpClient : IHttpClient {}
And just mock IHttpClient
and implement methods, then inject it (in constructor or property)
public class SomeStuff
{
public IHttpClient Client { get; }
public SomeStuff(IHttpClient client)
{
Client = client;
}
}
Upvotes: 2