Monday, August 22, 2016

Mocking HttpClient in your ASP.NET Web API Unit Tests

If you use HttpClient in your Unit Tests, you may encounter a great deal of difficulty with using this object since this object is not easily mocked using a Mocking Framework such as Moq.  In fact, you may encounter an error message such as the following:

There are a great number of solutions posted on the Internet on how to resolve this issue by creating a custom HttpMessageHandler and then passing this in the constructor of the HttpClient to create the HttpClient object for Unit Testing.

However, a clever developer has already provided a very handy NuGet package to allow you to do just that!

MockHttp is just one particular NuGet package that supports Unit Testing of the HttpClient.  There are other such as HttpClient.Helpers

However, the use of MockHttp is very intuitive and I highly prefer using it in my Unit Tests.

One of the things that I like to do, however, is use frameworks such as NBuilder or AutoFixture to help me generate test data rather than manually type this information into my Unit Tests myself.  But, one of the problems with using an object such as HttpResponseMessage is that it does not lend itself well to generating all of the properties needed to pass a Unit Test such as setting the Content of the HttpResponseMessage.

Therefore, I had to use a solution such as the following to get my entire Unit Test to work:

No comments:

Post a Comment