Search code examples
seleniummstestwebdriver

In MSTest how to check if last test passed (in TestCleanup)


I'm creating web tests in Selenium using MSTest and want to take a screenshot everytime a test fails but I don't want to take one every time a test passes.

What I wanted to do is put a screenshot function inside the [TestCleanup] method and run it if test failed but not if test passed. But how do I figure out if a last test passed?

Currently I'm doing bool = false on [TestInitialize] and bool = true if test runs through.

But I don't think that's a very good solution.

So basically I'm looking for a way to detect if last test true/false when doing [TestCleanup].


Solution

  • The answer by @MartinMussmann is correct, but incomplete. To access the "TestContext" object you need to make sure to declare it as a property in your TestClass:

    [TestClass]
    public class BaseTest
    {
        public TestContext TestContext { get; set; }
    
        [TestCleanup]
        public void TestCleanup()
        {
            if (TestContext.CurrentTestOutcome != UnitTestOutcome.Passed)
            {
                // some code
            }
        }
    }
    

    This is also mentioned in the following post.