MSTEST - Continuing after an Assert has failed

2019-05-07 20:44发布

问题:

I am wonder if there is an easy way to finish a test after an Assert has failed. We used to use Galileo for all of our automated tested, but we have moved the Visual Studio Test framework. We had a method that would allow a test to fail, but continue on.

        public static bool DoAssertAndContinue(Action assert)
    {
        try
        {
            assert();
            return true;
        }
        catch (AssertionException ae)
        {
            ConfigContext.WriteLine(ae.Message);
            return false;
        }
    }

This is what we used before...and it would be called like this:

assertionResults.Add(Automation.Utils.CommonMethods.DoAssertAndContinue(() => Assert.IsTrue(detail.ValidateName(boo, urns))));

I am just trying to figure out the best way to emulate what we had before without having to refactor all of our tests.

回答1:

Instead of AssertionException, you should now catch UnitTestAssertException which is the base exception for all mstest assert failures.



回答2:

You can use Try/Catch in MSTest as well. In Catch block you can catch the specific error and print it using Console.Write to know about the error. I would recommend you look into this thread for more details.

EDIT 1: Personally I don't use try/catch to sake of passing my test method. I write a test method to find defect in actual product. So if you are expecting that your calling method will give you some specific exception then I would suggest to use ExpectedException attribute. This is applicable if you are running your test method for single test data.

Now if you want to pass multiple test data into your test method. Then I would suggest go for Data driven test cases. Here you can keep all your test data inside a XML or XLS or in a DB. Then using that input file you can feed multiple test data into your test method. Try not to use try/catch here and for any test data if your calling method send you some exception then see if MSTest will handle it and move to the next test data or not. If it moves then in Test result window you will be able to see why for that specific test data your method get failed. For data driven concept see this link



回答3:

The MsTest framework throws an exception on a failed assertion. It's propagation out of the unit test method is what causes the test to fail. If you want to continue on a failed assertion you just need to handle that exception and prevent it from escaping the method.