Mocking is a technique where a dependency to a class is swapped out (mocked) with an alternate/fake equivalent to the functionality so that the class can be tested in isolation from it’s dependencies. For these examples, I’ll be using the mocking framework Moq.
Suppose we have a method that we wanted to mock:
public interface IPunctuation
We use the method like this:
var punctuation = new Punctuation();
Mocking this is fairly straighforward using Moq:
var punctuationMock = new Mock<IPunctuation>();
Once mocked, we use it in the exact same way as we use the real Punctuation class, but with the mocked result:
var s = punctuation.AddExclamationPoint("Hello");
That’s mocking. For more on mocking, see Moq’s documentation.
Extension methods in C# are static methods that provide some helpful syntax to make code that consumes them a little more readable (and chainable).
We can change the method above to an extension method by making the class and method static and by adding the
public static class PunctuationExtensions
And the usage of the extension method is a little cleaner:
var s = "Hello".AddExclamationPoint();
I love to mock things when testing, and I love using extension methods, because I find both to be very helpful in writing clean, maintainable code. But how can we mock an extension method?
In the example above, how would I mock out the
AddExclamationPoint() method from the
Well, you can’t.