11

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].

0

2 Answers 2

12

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.

2
  • That's right, but the code snippet gave me an error "TestContext must be of type TestContext, must be non-static, public and must not be read-only". So I changed the property to: public TestContext TestContext { get; set; } Commented Aug 23, 2017 at 10:55
  • @LambdaCruiser Correct, I've update the answer with that suggestion Commented Aug 23, 2017 at 13:50
11

Solution

if (TestContext.CurrentTestOutcome != UnitTestOutcome.Passed)
{
    // some code
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.