不幸的是,MStest / VStest没有本机测试重新运行逻辑
我试图实现这样的自定义逻辑:
试验部分:
static int testNum = 1;
[TestMethod]
public void RerunTestOnce_Test()
{
testNum = testNum + 1;
Console.WriteLine("Test started");
Assert.IsTrue(testNum == 3, $"Test Failed with number {testNum}");
}当testNum达到3时,这个测试应该第一次失败,第二次通过。
这是一个综合的例子,可以在第一次运行时模拟失败。真正的测试是复杂的,有用户界面搜索方法和系统和网络的其他工作,并且没有信心在一个大而长的测试套件中一切都会好起来。
对此有一个特殊的方法- RerunTestOnce(),在TestCleanup中调用:
[TestCleanup]
public void TestCleanup()
{
TestHelper.RerunTestOnce(TestContext, this);
}下面是测试助手类中RerunTestOnce的实现。在它中,使用反射和TestContext获取测试方法和初始化方法的名称,并再次运行它们:
public static void RerunTestOnce(TestContext testContext, object testInstance)
{
if (testContext.CurrentTestOutcome == UnitTestOutcome.Failed)
{
var type = testInstance.GetType();
if (type != null)
{
var testMethod = type.GetMethod(testContext.TestName);
var initMethod = type.GetMethods().SingleOrDefault(m=>m.CustomAttributes.SingleOrDefault(a=>a.AttributeType.Name == "TestInitializeAttribute")!= null);
var cleanupMethod = type.GetMethods().SingleOrDefault(m => m.CustomAttributes.SingleOrDefault(a => a.AttributeType.Name == "TestCleanupAttribute") != null);
Console.WriteLine($"[WARNING] Method [{testMethod}] was failed in first attempt. Trying to rerun...");
try
{
initMethod.Invoke(testInstance, null);
testMethod.Invoke(testInstance, null);
}
catch
{
Console.WriteLine($"[ERROR] Method [{testMethod}] was failed in second attempt. Rerun finished.");
}
}
}
}一切正常,第二次尝试测试方法通过,但最后我看到第一次尝试失败的结果和断言错误消息:
Test Failed - RerunTestOnce_Test
Message: Assert.IsTrue failed. Test Failed with number 2MSTest如何以及何时创建测试结果--在第二次尝试最后结果之后是否有可能更新测试结果?
发布于 2019-12-19 07:36:51
我想出了以下解决方案
public static void Retry(Action test, int retry = 10, int sleep = 0, [CallerMemberName] string testName = null)
{
int current = 1;
retry = Math.Max(1, Math.Min(retry, 10));
while (current <= retry)
{
try
{
test();
break;
}
catch (Exception ex) when (current < retry)
{
Debug.WriteLine("Test {0} failed ({1}. try): {2}", testName, current, ex);
}
if (sleep > 0)
{
Thread.Sleep(sleep);
}
current++;
}
}用法
[TestMethod]
public void CanRollbackTransaction()
{
Helpers.Retry(() =>
{
var even = DateTime.Now.Second % 2 == 0;
Assert.IsTrue(even);
}, 3, 1000);
}发布于 2019-06-12 10:41:47
MSTest测试框架本身不支持本机测试-重新运行逻辑。
请考虑使用MSTestEx,这是对MSTest测试框架的一组扩展,它支持测试-重新运行逻辑:https://www.nuget.org/packages/MSTestEx/
https://stackoverflow.com/questions/53430550
复制相似问题