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

后端 未结 1 1387
孤独总比滥情好
孤独总比滥情好 2021-01-15 05:36

I want to run unit tests via MS Test (from windows console) in a way that I can stop/kill the test execution whenever the failed tests count exceeds certain thresho

相关标签:
1条回答
  • 2021-01-15 06:04

    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);
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题