Later today I’ll be speaking at the C# Corner 2022 .NET Conference. This is a 3-day FREE online conference with a great set of speakers. I’ve been really impressed with the quality of production and how the C# Corner team is really building a community with their articles, events and how they are encouraging people to get involved.
I’ll be speaking on unit testing strategies with my “Coding Naked – Unit Testing those hard to reach places” talk. I need to update the slides on SlideShare, these ones are a bit dated by now, if you watch the live steam or recording, you’ll see I’ve updated this talk quite a bit since I first put it together (in 2012!).
In addition to TDD fundamentals, I dig into a few strategies for better TDD and test coverage.
One area I address is working with extension methods. Extension methods can be hard to mock, or at least, they often get in the way. Extension methods that are “functionally pure” (input, output, no side effects) are pretty easy to unit test, the challenge are extension methods that return void, or that do a lot of work under the hood.
The three strategies I discuss for dealing with extension methods are:
- Wrapping Extensions with an Interface (my preferred approach)
- Mocking around Extension Methods (creates dev cognitive load, and leaky abstractions)
- Using Fakes, Pose or Isolator (I don’t recommend these)
You can download or fork the sample code on githuib.
One thing I recently added to the sample code, is a new method for mocking around a common extension method. The Microsoft.Logging.Extensions! I’m really glad that Microsoft has created a common logging interface. There are a lot of great .NET loggers.. but often moving from project to project the nuanced api differences can be really annoying. I’ve used the Common.Logging interface several times, but it never really took off the way I hoped it would. I think the Microsoft logging abstractions will have a much higher adoption. 🤞
Here’s the thing though. There is only 1 logging method in the Microsoft.Logg Interface, and you’ll likely never use it! Instead, you’ll end up using one of the many logging extension methods. So now you might try and mock around it since the source code is all available. This will lead you to a massive deep dive where you finally realize that all of the Microsoft Extensions, end up using a method call that takes an internal class as a parameter! Ugh. That makes it really hard to mock around!
That being said, MOQ recently added a parameter option for It.IsAnyType – huzzah! Adam Storr has a much more extensive write up on this challenge and the solution that he came up with (go read it!) to Mock Around the Microsoft Logging Abstractions. I extended his solution in my code, and am planning on publishing this as a reusable nuget package soon.
Happy Coding!