c# - 如何重试 NUnit 测试用例?

标签 c# nunit

我想实现一个设置,我可以在其中为每个测试设置所需的重试次数,这样我就可以在实际失败之前重试所有失败的测试一次。我以这种方式构建了我的测试:

    [TestCase(“Some parameter”, Category = “Test category”, TestName = “Name of test”, Description = “Description of test”)]
    public void SomeTestName(string browser) {
    //Test script
    }

如果我使用 [Test] 而不是 [TestCase],我可以只添加一个 [Retry(1)] 属性,但是如何使用 [TestCase] 实现相同的行为?我已经看过 NUnit retry dynamic attribute它有一个非常简洁的解决方案,但不幸的是,当我尝试将它应用于 [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);
    }
  }
}

您将按如下方式使用它

[RetryTestCase("some parameter", MaxTries=3)]
public void SomeTestName(string browser)
{
  // Your test code
}

关于上面的一些注意事项:

  1. 我已经编译了这段代码,但还没有测试过。如果您尝试过,请发表评论,尤其是需要修改时。

  2. 该代码依赖于 NUnit 内部的一些知识,将来可能会中断。需要更全面的实现才能使其永不过时。特别是,我使用了 IRepeatTest 基于 ICommandWrapper 但未添加任何方法这一事实。我相信这两个接口(interface)中的每一个在我放置它们的地方都是需要的,因为 NUnit 在其代码的不同点检查它们。

  3. 与将重试计数添加到 TestCaseAttribute 所需的代码行数相比,这段代码的行数大约是行数的三倍!如果您想要该功能,请咨询 NUnit 项目 - 或者您自己贡献!

关于c# - 如何重试 NUnit 测试用例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60301860/

相关文章:

c# - AppDomain.UnhandledException 处理程序不会在单元测试中触发

c# - C#Theora编码器?

c# - 从 JavaScript 引用 C# 方法而不调用它

c# 对象初始化 - 可以通过非文字名称引用属性吗?

.net - NUnit 多个 TestFixture 等效于 MsTest

c# - 我如何对缓存等实现细节进行单元测试

c# - Oracle 自定义类向导无法从 Oracle 用户定义的数据类型生成自定义 c# 类

c# - 是否有像Unity这样的东西可以用于不需要界面的简单事物?

macos - 如何从终端在 Mac 上运行 fsharp 测试?

c# - NUnit 顺序/组合问题