Member-only story
Creating a library to unit test classes that use HttpClient
Unit testing classes that use HttpClient can be a pain. Along the years I’ve seen various ways of dealing with this pain: varying from the creation of custom wrappers over HttpClient to not testing these classes at all.
In this course I will show you there’s a pretty easy way to achieve this by gaining an understanding of how HttpClient was created and how to make use of that.
Let’s very briefly start with the basics of unit testing: in order to effectively write unit tests, we want our classes to be loosely coupled. To achieve loose coupling, we make use of dependency injection.
To learn more about writing testable code, make sure to read my post Learn how to write testable code in C# in only 15 minutes.
An abstraction over the declaration of HttpClient
Because we want to prevent tight coupling to HttpClient, we will need an abstraction over it. This way we can inject the abstraction in the constructor, which allows us to replace it with a mock for our unit tests.
If you will be working with .NET Core 2.1 or a newer version of .NET Core, it is not required to create a custom abstraction. The IHttpClientFactory is perfectly suited:
Creating a custom HttpClient factory
If you do not use .NET Core or if you use an older version than 2.1, you are required create your own…