I’ve done a few unit test blog posts, but this time I’m going to demonstrate how to detect if a method is running under a unit test. This flag can be used to break dependencies in an object or run a test database instance instead of the production instance.
The first article I stumbled across was this stack overflow article on just such a problem:
determine-if-code-is-running-as-part-of-a-unit-test
Answer #22 had my solution, using reflection to determine if one of the included DLL’s was the UnitTestFramework.
public static class UnitTestDetector { public static bool IsInUnitTest() { string assemblyName = "Microsoft.VisualStudio.QualityTools.UnitTestFramework"; return AppDomain.CurrentDomain.GetAssemblies().Any(a => a.FullName.StartsWith(assemblyName)); } }
So what’s the point? The purpose of this class/method is to embed this into your context code and force your ORM to use a test database when you are running unit tests, but run your production database when the calling assembly is not a unit test assembly. By using this code to switch your database at the context level, you no longer have to worry about breaking dependencies of your objects that will be under unit test.
Another advantage is that this can be used in multiple ORM’s (such as EF, NHibernate, etc.). It can even be used in direct queries if you have a SqlConnection wrapper that feeds the connection string in one place.
In a future post, I’ll demonstrate how to use this class/method in Entity Framework and show how to connect EF to SQLLocalDB for unit testing purposes.