Skip to content

Instantly share code, notes, and snippets.

@Meir017
Last active August 4, 2023 13:37
Show Gist options
  • Save Meir017/fb2041398416d3b821884cdcb71222d0 to your computer and use it in GitHub Desktop.
Save Meir017/fb2041398416d3b821884cdcb71222d0 to your computer and use it in GitHub Desktop.
MSTest flaky test
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