DEV Community

Cover image for Mocking the HttpClient in .NET Core (with NSubstitute)

Mocking the HttpClient in .NET Core (with NSubstitute)

Lars Richter on June 16, 2019

The problem I was writing a client library for a webservice. Inside of the client I used the Microsoft HttpClient class to call the webs...
Collapse
 
yadurajshakti profile image
Yaduraj Shakti

This was really helpful. Thanks Lars!

Just want to add:-

If your implementation does not accepts HttpClient in constructor and creates HttpClient directly, then you may use IHttpClientFactory.CreateClient() in your code. Now mock this IHttpClientFactory.CreateClient() to return your HttpClient in test.

Collapse
 
francescoreviso profile image
FrancescoReviso

Thanks Lars, this have been really useful for me. Just a remark for a more general context, in your implementation Input = await request.Content.ReadAsStringAsync(); works for SendAsync but it will throw an exception in the case we use GetAsync, since the request will be null

Collapse
 
n_develop profile image
Lars Richter

Hi Francesco,
you are totally right. There is still a lot of room for improvement. But I'm happy that the post helped you. :-)
I just realized, that codemaker asked for the complete code 2 months ago. Shame on me. I will make a GitHub repo soon und I will take care for the GetAsync case as well.

Collapse
 
n_develop profile image
Lars Richter

Hi Francesco,
I finally had time to create a little sample app. You can check it out on my GitHub profile under github.com/n-develop/HttpClientMock

I also checked the problem with GetAsync and found the reason. Of course, in a GET request, we don't have a body. So I added a little if (request.Content != null) in the mock class. I also updated the code in the post.
Thanks again for pointing it out. Now it should work even better.

Collapse
 
rosesap028 profile image
A

Do you an example for

//Mock mockHandler = new Mock();
//mockHandler
//.Protected()
//.Setup>(
//"SendAsync",
//ItExpr.IsAny(),
//ItExpr.IsAny()
//)
//.Returns(() =>
//{
// throw new Exception("Http Client Exception Error");
//});

//return new HttpClient(mockHandler.Object);

Collapse
 
codemaker profile image
codemaker

Could you please post complete code :)

Collapse
 
n_develop profile image
Lars Richter

Hi codemaker,

I'm so sorry, that I missed your comment on this. I will create a public GitHub repo with the entire code and post the link in here.

Collapse
 
n_develop profile image
Lars Richter

So, sorry for the long delay.
You can check out a full, yet short, example here: github.com/n-develop/HttpClientMock
I hope it helps.

Collapse
 
morensya93 profile image
Faisal Morensya

This simple solution is really helpful :) Thanks!

Collapse
 
mogoli_51412bde64e72f3c72 profile image
Mogoli

Thanks for this, good answer