Posts about Moq

Mock methods with out parameters

April 26th 2024 Moq Unit Testing .NET

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 unit tests

December 22nd 2023 Moq Unit Testing .NET

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.

Exclude setup from verifying in Moq

September 29th 2023 Moq Unit Testing .NET

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.

Ignored failing assertions in mock callbacks

June 17th 2022 Moq Unit Testing .NET

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.

Matching Generic Type Arguments with Moq

June 5th 2020 Moq Unit Testing Xamarin

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.