Mocking static methods

I’m working on a pretty old application with no unit tests whatsoever, and I’m trying to write some as I add features and fix bugs.

After successively finding out about MS Fakes, then that it’s only included in VS2012+ Premium/Ultimate and very hard to include in a continuous integration chain, I was pretty stumped until I found this, which works incredibly well.

Another option to transform the static method into a static Func or Action. For instance.

Original code:

You want to “mock” the Add method, but you can’t. Change the above code to this:

Existing client code doesn’t have to change (maybe recompile), but source stays the same.

Now, from the unit-test, to change the behavior of the method, just reassign an in-line function to it:

Put whatever logic you want in the method, or just return some hard-coded value, depending on what you’re trying to do.

This may not necessarily be something you can do each time, but in practice, I found this technique works just fine.