Jan 25 2008

Is this a Unit Test you are running?

Category: Tips and TricksJoeGeeky @ 12:00

From time-to-time you need to determine whether your application is running within a Unit Test Context. For example, when you are testing classes the inherit from ProviderBase, they require an HttpContext to initialize. Unfortunetally, Mocking such things is next to impossible, and Dependency Injection is of little use.  In cases such as these, you could modify your initializer to skip certain initialization steps to allow basic Unit Testing to continue.  While not perfect, it does allow you to build Unit Tests for classes that would otherwise required Web Tests.  Here is an example which can be adapted for other test tools like MbUnit, NUnit, etc:

/// <summary>
/// Flag indicating if the current 
/// execution stack was called from 
/// the Unit Test Foundation supplied 
/// by Visual Studio and Team 
/// Foundation Server
/// </summary>
/// <returns>True if the call stack 
/// was initiated by a unit engine; 
/// otherwise false</returns>
/// <remarks>This is used to help 
/// adapt behavior to limitations in 
/// the execution environment 
/// generally associated with unit 
/// testing.  For Example: <example>
/// No HttpContext, HttpStream, 
/// SoapStream, etc...</example>
/// </remarks>
public static bool IsRunningInUnitTestContext
{
    get
    {
        bool isInTestContext = false;
        string callStack = Environment.StackTrace;
        if (callStack.Contains(@"Microsoft.VisualStudio.TestTools" + ".TestTypes.Unit.UnitTestRunner" + ".Run"))
            isInTestContext = true;        
        return isInTestContext;
    }
}

Tags: