我正在尝试构建一个与 Reqnroll(较新的 Specflow)一起使用的自定义重试挂钩,但重新运行测试时遇到一些困难。我很好奇如何在失败时实际重新运行相同的测试最多 n 次。这是我现在所拥有的:
namespace Hooks.SharedHooks
{
[Binding]
public class RetryHook
{
private int _retryCount;
private const int DefaultMaxRetries = 2;
private static readonly Regex RetryTag = new Regex(@"^Retry");
private static readonly Regex RetryTagNumbereRegex = new Regex(@"^Retry\(\d+)\)$");
[BeforeScenario("Retry","Retry*")]
public void BeforeScenario()
{
_retryCount = 0;
}
[AfterScenario("Retry", "Retry*", Order = 0)]
public void AfterScenario(ScenarioContext scenarioContext, ITestRunnerManager testRunnerManager)
{
var maxRetries = GetMaxRetriesFromScenario(scenarioContext) ?? DefaultMaxRetries;
while (_retryCount < maxRetries && scenarioContext.TestError != null)
{
_retryCount++;
Console.WriteLine($"Attempting scenario '{scenarioContext.ScenarioInfo.Title}' try {_retryCount} of {maxRetries}");
ScenarioExecutionRetryAsync(scenarioContext, testRunnerManager);
}
}
private int? GetMaxRetriesFromScenario(ScenarioContext scenarioContext)
{
foreach (var tag in scenarioContext.ScenarioInfo.Tags)
{
var match = RetryTagNumbereRegex.Match(tag);
if (match.Success && int.TryParse(match.Groups[1].Value, out int retries))
{
return retries;
}
}
return null;
}
private void ScenarioExecutionRetry(ScenarioContext scenarioContext,ITestRunnerManager manager)
{
// Logic to re-run the failed scenario
}
}
知道如何编写 ScenarioExecutionRetry 方法吗?
正如评论中所指出的,这是测试运行者所做的事情。
长答案涉及使用 NUnit 并为其创建自定义插件。简单的答案是使用另一个 [Retry] 包,例如 Databindings.Reqnroll.NUnit.Retry