Я пытаюсь реализовать такую собственную логику:
Test часть:
Код: Выделить всё
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}");
}
UP: это синтетический пример для имитации неудачи при первом запуске. Реальные тесты сложны и включают в себя методы поиска по пользовательскому интерфейсу и другую работу с системой и сетью, и нет уверенности, что во время большого и длительного набора тестов все будет хорошо.
Для этого существует специальный метод — RerunTestOnce(), вызываемый в TestCleanup:
Код: Выделить всё
[TestCleanup]
public void TestCleanup()
{
TestHelper.RerunTestOnce(TestContext, this);
}
В нем, используя Reflection и 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 2
Подробнее здесь: https://stackoverflow.com/questions/534 ... erun-logic