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:
12345678 class Math{public static int Add(int x, int y){return x + y;}}You want to “mock” the Add method, but you can’t. Change the above code to this:
12345 public static Func<int, int, int> Add = (x, y) =>{return x + y;};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:
123456789 [TestMethod]public static void MyTest(){Math.Add = (x, y) =>{return 11;};}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.