Last active
August 4, 2023 13:37
-
-
Save Meir017/fb2041398416d3b821884cdcb71222d0 to your computer and use it in GitHub Desktop.
MSTest flaky test
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
namespace Playground.Tests | |
{ | |
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)] | |
public class FlakyTestMethodAttribute : TestMethodAttribute | |
{ | |
public int RetryCount { get; set; } | |
public override TestResult[] Execute(ITestMethod testMethod) | |
{ | |
TestResult result = testMethod.Invoke(new object[0]); | |
var output = new StringBuilder(); | |
for (int i = 0; i < RetryCount; i++) | |
{ | |
if (result.Outcome == UnitTestOutcome.Passed) break; | |
output.AppendLine($"Run #{i + 1} completed with status {result.Outcome}. exception: {result.TestFailureException}"); | |
result = testMethod.Invoke(new object[0]); | |
} | |
if (output.Length > 0) | |
{ | |
result.LogOutput += "[Failures]" + Environment.NewLine + output; | |
} | |
return new[] { result }; | |
} | |
} | |
[TestClass] | |
public class TestClass | |
{ | |
[FalkyTestMethod(RetryCount = 6)] | |
public void FlakyTest() | |
{ | |
Assert.IsTrue(new Random().NextDouble() > 0.8); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment