Question

I have a CodedUI test suite that runs as MSTest Unit tests. I have a method in the AssemblyCleanup that will email the results of the test run that is stored in an external database. How can a programmatically determine how many unit tests were executed during the last run session? I don't want to send the email if we are executing less than 10 tests. This way we only get emails when we run our whole CodedUI suite and not when we are debugging tests. We currently have a SendEmail flag that has to be manually set but I would like this to be programmatically determined.

Was it helpful?

Solution

Use a base test class which has a property that keeps the number of the executed tests. All other test classes inherit it and on TestInitialize increment that property.

Run the following code and see the results on the test output.

[TestClass]
public class BaseTestClass
{
    private static int _executedTests;
    private static int _passedTests;

    [AssemblyCleanup()]
    public static void AssemblyCleanup()
    {
        Console.WriteLine("Total tests executed: {0}", _executedTests );
        Console.WriteLine("Total passed tests: {0}", _passedTests);
    }

    protected void IncrementTests()
    {
        _executedTests++;
    }

    protected void IncrementPassedTests()
    {
        _passedTests++;
    }
}

[TestClass]
public class TestClass : BaseTestClass
{
    [TestInitialize]
    public void TestInitialize()
    {
        IncrementTests();
    }

    [TestCleanup]
    public void TestCleanup()
    {
        if (TestContext.CurrentTestOutcome == UnitTestOutcome.Passed)
        {
            IncrementPassedTests();
        }
    }

    [TestMethod]
    public void TestMethod1()
    {
    }

    [TestMethod]
    public void TestMethod2()
    {
        Assert.Fail();
    }

    public TestContext TestContext { get; set; }
}

Note: The same code can be used on CodedUITests

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top