Paul Stanley
Paul Stanley

Reputation: 2161

How To Mock A HttpClient By Wraping HttpClient In A Interface

I would like to use Moq to mock my HttpClient calls. I would like to do this by using an Interface to wrap the HttpClient. My Interface:

public interface IMyHttpClient
{
    Task<T> GetJsonAsync<T>(string url);
}

And my class:

 public class MyHttpClient : IMyHttpClient
 {
    private HttpClient http;
    public MyHttpClient(HttpClient _http)
    {
        http = _http;
    }
    public Task<T> GetJsonAsync<T>(string url)
    {
        return http.GetFromJsonAsync<T>(url);
    }
}

FYI: Just showing the one method.

My test is:

 var myObj = new MyObj();
 Mock moc = new Mock<IMyHttpClient>().Setup(a => a.GetJsonAsync<MyObj> 
 ("url")).Returns(Task.FromResult(myObj));

I am getting a compiler error:

System.InvalidCastException : Unable to cast object of type 
'Moq.Language.Flow.NonVoidSetupPhrase`2[IMyHttpClient,
System.Threading.Tasks.Task`1[MyObject]]' to type 'Moq.Mock'.

I do not understand where I have gone wrong.

Upvotes: 0

Views: 764

Answers (1)

GWLlosa
GWLlosa

Reputation: 24403

.Returns() does not return a Mock as the error indicates. Separate the declaration and the setup:

var myObj = new MyObj();
Mock<IMyHttpClient> moc = new Mock<IMyHttpClient>();
moc.Setup(a => a.GetJsonAsync<MyObj>("url"))
    .ReturnsAsync(myObj);

Reference Moq Quickstart to get a better understanding of the mocking framework.

Upvotes: 1

Related Questions