
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...
For further actions, you may consider blocking this person and/or reporting abuse
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.
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
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.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 littleif (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.
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);
Could you please post complete code :)
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.
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.
This simple solution is really helpful :) Thanks!
Thanks for this, good answer