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:

Comments

1.
Nats Wells Nats Wells United States says:

Lovely good post. I just stumbled upon your blog and wanted to say that I have actually enjoyed reading your blog posts. Any way, I will be signing up to receive your feed and I hope you post very soon.

2.
Olivia Gautreaux Olivia Gautreaux United Kingdom says:

Easily, the post is actually the best on this deserving topic. I fit in with your conclusions and will thirstily look forward to your approaching updates. Saying thanks will not just be enough, for the great clarity in your writing. I will right away grab your rss feed to stay privy of any updates. Solid work and much success in your business dealings!

3.
Brooklynn Brooklynn United States says:

Wonder full writing skills you got mate.

Comments are closed