Public
Snippet $4 authored by Christian Gerdes

Unit Test Think Time and Transactions example

unittestthinktimetransactionsexample.cs
Raw
// Define the TestContext property
public TestContext TestContext { get; set; }

// Use TestInitialize to run code before running each test 
private bool inLoadTest = false;
private bool dontKnow = true;
[TestInitialize()]
public void CheckTestContextType() {
    if (dontKnow)
    {
        // Check if the TestContext type is the one that a loadtest provides
        if (TestContext.GetType().ToString().Equals("Microsoft.VisualStudio.TestTools.TestTypes.Unit.UnitTestAdapterContext"))
            inLoadTest = true;
        else
            inLoadTest = false;
        dontKnow = false;
        TestContext.WriteLine("We have a loadtest TestContext: " + inLoadTest);
    }
}

[TestMethod]
public void TestMethod1()
{
    // Local ThinkTime Parameter with default value 5 seconds, used if no ThinkTime is set in TestContext
    int myThinkTime = 5;

    // Get think time from test context if set
    if (TestContext.Properties.Contains("ThinkTime"))
    {
        myThinkTime = int.Parse(TestContext.Properties["ThinkTime"].ToString());
        TestContext.WriteLine("Using thinktime " + myThinkTime + " from test context");
    }

    // Dummy transaction, only use BeginTimer if we are running in a loadtest
    TestContext.WriteLine("Starting transaction UnitTestTransaction1");
    if (inLoadTest) TestContext.BeginTimer("UnitTestTransaction1");

    // Think time
    System.Threading.Thread.Sleep(myThinkTime * 1000);

    // End transaction, only use EndTimer if we are running in a loadtest
    TestContext.WriteLine("Ending transaction UnitTestTransaction1");
    if (inLoadTest) TestContext.EndTimer("UnitTestTransaction1");
}