Posts about Moq
When testing code that depends on HTTP calls, it's most common to mock the unit of the code that does the HTTP calls. In integration tests, however, you don't want to modify the application code. So you need to mock the server responding to the HTTP calls. WireMock.Net is a convenient tool to do that directly from test code.
Verifying whether a call to ILogger has been made from a unit test is somewhat tricky because we're more often calling extension methods than instance methods, and those can't be directly verified. We need to verify the call to the underlying instance method.
Moq is my preferred mocking tool for .NET. Although it has rather good documentation, it doesn't include an example for what I needed, so it took me a while to actually get it working.
Mocking HttpClient in .NET isn't difficult. But if you haven't done it before, it's not obvious how to approach it, since the class has no interface or virtual methods. What you should mock, is the protected abstract SendAsync method of the HttpMessageHandler class, which can be passed to HttpClient as a constructor parameter.
Mocking frameworks can be used not only to mock methods, but also to verify whether those mocked methods have actually been called. The latter is sometimes called interaction testing and is particularly useful when you want to test that specific calls to an external API have been called. Of course, Moq also supports such setup verification.
When you write unit tests, make sure not only that they succeed if the tested code works as expected, but also that they fail if the code does not work as expected. Otherwise, these tests will give you a false sense of confidence in your code.
The Moq mocking library in version 4.13.0 added support for matching generic type arguments when mocking generic methods. The documentation doesn't go into much detail but thanks to additional information in IntelliSense tooltips and the originating GitHub issue I managed to quickly resolve the no implicit reference conversion error which I encountered at first.