How to stop MsTest tests execution after *n* failed tests

橙三吉。 提交于 2019-12-01 11:16:37

Create a BaseTestClass which contains a method responsible for killing the process that runs the tests.

using System.Diagnostics;

namespace UnitTestProject1
{
    public class BaseTestClass
    {
        private readonly int _threshold = 1;
        private static int _failedTests;

        protected void IncrementFailedTests()
        {
            if (++_failedTests >= _threshold)
                Process.GetCurrentProcess().Kill();
        }
    }
}

Your must inherit all your test classes from BaseTestClass and use the [TestCleanup] attribute. The TestCleanup() method is evaluated when a test defined in the DemoTests class has finished running. Is in that method where we evaluate the output of the test that has just finished. If it failed, we kill the process responsible for running the tests.

In the following example we have defined three tests. The second test, Test_Substracting_Operation(), is intended to fail intentionally, so the third test will never be run.

using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace UnitTestProject1
{
    [TestClass]
    public class DemoTests : BaseTestClass
    {
        public TestContext TestContext { get; set; }

        [TestCleanup]
        public void TestCleanup()
        {
            if (TestContext.CurrentTestOutcome == UnitTestOutcome.Failed)
            {
                IncrementFailedTests();
            }
        }
        [TestMethod]
        public void Test_Adding_Operation()
        {
            // Arrange
            int x = 1;
            int y = 2;

            // Act
            int result = x + y;

            // Assert
            Assert.AreEqual(3, result);
        }

        [TestMethod]
        public void Test_Substracting_Operation()
        {
            // Arrange
            int x = 1;
            int y = 2;

            // Act
            int result = x - y;

            // Assert
            Assert.AreEqual(100, result);
        }

        [TestMethod]
        public void Test_Multiplication_Operation()
        {
            // Arrange
            int x = 1;
            int y = 2;

            // Act
            int result = x * y;

            // Assert
            Assert.AreEqual(2, result);
        }
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!