Monday, 5 December 2011

Mocking out Environment.Exit

Question I came across recently on Twitter.

"How do I write a test when there's an Environment.Exit?! :("

Very good question... My answer was basically rewrite the code! A really quick way to do this is create a static action that will allow you to mock it out. What if I created a class called MyEnvironment with this Action:


public class MyEnvironment
{
public static Action Exit = exitCode => Environment.Exit(exitCode);
}


In code I can just replace the call with this:


MyEnvironment.Exit(0);


And now, in my testing I can do something like this:


MyEnvironment.Exit = exitCode => { };


Voila! No more interrupted tests :)