【问题标题】:How to force set test status to 'Passed' in MSTest?如何在 MSTest 中强制将测试状态设置为“通过”?
【发布时间】:2020-04-29 01:43:35
【问题描述】:

您能否建议如何在 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);                    
        }
    }                
}

【问题讨论】:

  • “强制”?在什么时候?为什么你需要对测试发生的事情撒谎?为什么你不能 A) 返回实际测试的失败状态 B) 不要将你的清理操作基于当前的测试结果。
  • 不,这是测试流程的特殊性。一些测试在低资源上运行,有时会失败(这没关系,我只需要重新运行它们)。一般的输出,即使失败了一次,最后也要通过。
  • 不。您的测试有时会因资源不足而需要重新运行,这是不行的。

标签: c# mstest


【解决方案1】:

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);
        }
    }
}

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

【讨论】:

  • 非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多