如何在 MSTest 中强制将测试状态设置为 'Passed'?



您能建议如何在MSTest中将测试状态强制设置为"通过"吗?假设我有两次相同测试的重播——一次失败,第二次通过,但结果无论如何都是"失败"。。。我需要让它"通过"。以下是重新运行测试的代码示例。但如果第一次运行失败,第二次运行通过,它仍然在最终输出中显示测试结果为"失败">

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

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

有了这个解决方案,您的测试将始终是绿色的。

最新更新