我想实现一个设置,我可以为每个测试设置所需的重试次数,例如,我可以在实际失败之前重试所有失败的测试一次。我以这种方式构建了我的测试:
[TestCase(“Some parameter”, Category = “Test category”, TestName = “Name of test”, Description = “Description of test”)]
public void SomeTestName(string browser) {
//Test script
}
Run Code Online (Sandbox Code Playgroud)
如果我使用 [Test] 而不是 [TestCase],我可以添加一个 [Retry(1)] 属性,但是如何使用 [TestCase] 实现相同的行为?我已经看过NUnit retry 动态属性,它有一个非常简洁的解决方案,但不幸的是,当我尝试将它应用于 [TestCase] 时它没有效果
根据文档:“RetryAttribute 用于测试方法,以指定如果失败则应重新运行,最多可达最大次数。”
也就是说,参数不是您可能认为的重试次数,而是运行测试的总尝试次数[Retry(1)],无论您在哪里使用它都没有任何影响。由于这可能是一个混淆点,我只是编辑了该页面以给出明确的警告。
如果您尝试RetryAttribute在类上使用,则会收到编译器警告,因为它只能用于方法。但是,在 NUnit 中,一个方法可以表示单个测试或一组参数化测试。在参数化测试的情况下,该属性当前无效。
NUnit 团队可以决定将此属性应用于每个单独的测试用例并相应地修改 nunit。还可以TestCaseAttribute采用指定重试计数的可选参数。对于长期解决方案,您可能需要向他们询问这些选项中的一个。
在短期内,作为一种解决方法,您可以考虑从TestCaseAttribute. 这是一些(未经测试的)代码,可帮助您入门...
using System;
using NUnit.Framework.Interfaces;
using NUnit.Framework.Internal.Commands;
namespace NUnit.Framework
{
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true, Inherited = false)]
public class RetryTestCaseAttribute : TestCaseAttribute, IRepeatTest
{
// You may not need all these constructors, but use at least the first two
public RetryTestCaseAttribute(params object[] arguments) : base(arguments) { }
public RetryTestCaseAttribute(object arg) : base(arg) { }
public RetryTestCaseAttribute(object arg1, object arg2) : base(arg1, arg2) { }
public RetryTestCaseAttribute(object arg1, object arg2, object arg3) : base(arg1, arg2, arg3) { }
public int MaxTries { get; set; }
// Should work, because NUnit only calls through the interface
// Otherwise, you would delegate to a `new` non-interface `Wrap` method.
TestCommand ICommandWrapper.Wrap(TestCommand command)
{
return new RetryAttribute.RetryCommand(command, MaxTries);
}
}
}
Run Code Online (Sandbox Code Playgroud)
您将按如下方式使用它
[RetryTestCase("some parameter", MaxTries=3)]
public void SomeTestName(string browser)
{
// Your test code
}
Run Code Online (Sandbox Code Playgroud)
关于上述的一些注意事项:
我已经编译了这段代码,但还没有测试过。如果您尝试一下,请发表评论,特别是如果它需要修改。
该代码依赖于 NUnit 内部的一些知识,将来可能会中断。需要更全面的实施才能使其面向未来。特别是,我使用了IRepeatTest基于ICommandWrapper但不添加任何方法的事实。我相信这两个接口中的每一个都需要我放置它们,因为 NUnit 在其代码中的不同点检查它们。
与将重试计数添加到TestCaseAttribute! 如果您想要该功能,请询问 NUnit 项目 - 或者自己贡献!