Mocking an Asp.Net Core HttpClient for Unit Tests with Moq

Georg Dangl by Georg Dangl in Web Development Saturday, June 03, 2017

Saturday, June 03, 2017

Posted in DotNet Asp.Net Core

When you design services around Http requests, you should really just inject your HttpClient as a dependency instead of wrapping it in a using statement in-place. This has the nice effect of making your code both easier to maintain and test. While doing a project recently, I decided to give Moq a try and use it to generate a HttpMessageHandler (that's the class the HttpClient uses internally for sending the network requests) for the HttpClient instead of providing my own HttpClient implementation. It's a really awesome mocking framework, but it took me a bit to set it up correctly. That's why I hope this snippet might save some of you a few minutes:

Happy mocking!


Share this post


comments powered by Disqus

About me

Hi, my name's George! I love coding and blogging about it. I focus on all things around .Net, Web Development and DevOps.

DanglIT

Need a consultant for BIM, GAEB or Software Development?

Contact me at [email protected], +49 (173) 56 45 689 or visit my professional page!

Dangl.Blog();
// Just 💗 Coding

Social Links