首页 > 解决方案 > 如何在 MSTest 中强制将测试状态设置为“通过”?

问题描述

您能否建议如何在 MSTest 中强制将测试状态设置为“通过”?假设我重新运行了 2 次相同的测试——一次失败,第二次通过,但结果还是“失败”……我需要让它“通过”。这是重新运行测试的代码示例。但是如果第一次运行失败并且第二次运行通过,它仍然在最终输出中显示测试结果为“失败”

protected void BaseTestCleanup(TestContext testContext, UITestBase type)
{ 
    if (testContext.CurrentTestOutcome != UnitTestOutcome.Passed)
    {
        if (!typeof(UnitTestAssertException).IsAssignableFrom(LastException.InnerException.GetType()))
        {
            var instanceType = type.GetType();
            var testMethod = instanceType.GetMethod(testContext.TestName);
            testMethod.Invoke(type, null);                    
        }
    }                
}

标签: c#mstest

解决方案


TestCleanup方法来不及检查UnitTestOutcome。如果出于某种原因您想运行两次测试,则必须在其中创建自己的TestMethodAttribute覆盖Execute方法。这是一个示例,您可以如何做到这一点:

using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace UnitTestProject1
{
    public class MyTestMethodAttribute : TestMethodAttribute
    {
        public override TestResult[] Execute(ITestMethod testMethod)
        {
            TestResult[] results = base.Execute(testMethod);

            bool runTestsAgain = false;

            foreach (TestResult result in results)
            {
                if (result.Outcome == UnitTestOutcome.Failed)
                {
                    result.Outcome = UnitTestOutcome.Passed;
                    runTestsAgain = true;
                }
            }

            if (runTestsAgain)
            {
                // Run them again I guess...
            }

            return results;
        }
    }

    [TestClass]
    public class UnitTest1
    {
        [MyTestMethod]
        public void TestMethod1()
        {
            Assert.IsTrue(false);
        }
    }
}

使用此解决方案,您的测试将始终是绿色的。


推荐阅读