NUnit 3.x-用于后代测试类的TestCaseSource

Jas*_*son 3 c# nunit unit-testing

我目前有一组单元测试,这些单元测试与多个Rest API端点一致。像这样定义类。

public abstract class GetAllRouteTests<TModel, TModule>
{
  [Test]
  public void HasModels_ReturnsPagedModel()
  {
     // Implemented test
  }
}
Run Code Online (Sandbox Code Playgroud)

实施的测试夹具看起来像:

[TestFixture(Category = "/api/route-to-test")]
public GetAllTheThings : GetAllRouteTests<TheThing, ModuleTheThings> { }
Run Code Online (Sandbox Code Playgroud)

这使我能够跨所有GET all / list路由运行许多通用测试。这也意味着我拥有直接链接到要测试的模块的类,以及Resharper / Visual Studio / CI中“测试正常”的测试与代码之间的链接。

挑战在于某些路线需要查询参数来测试通过路线代码的其他路径。

例如/ api / route-to-test?category = big。

由于[TestCaseSource]需要静态字段,属性或方法,因此似乎没有很好的方法来覆盖要传递的查询字符串列表。我想出的最接近的东西似乎是hack。即:

public abstract class GetAllRouteTests<TModel, TModule>
{
  [TestCaseSource("StaticToDefineLater")]
  public void HasModels_ReturnsPagedModel(dynamic args)
  {
     // Implemented test
  }
}

[TestFixture(Category = "/api/route-to-test")]
public GetAllTheThings : GetAllRouteTests<TheThing, ModuleTheThings> 
{
    static IEnumerable<dynamic> StaticToDefineLater() 
    {
       // yield return all the query things
    }
}
Run Code Online (Sandbox Code Playgroud)

这是可行的,因为为实现的测试类定义了静态方法,并且该方法由NUnit找到。巨大的骇客。对于其他使用抽象类的人来说也是个问题,因为他们需要“知道”将“ StaticToDefineLater”实现为静态对象。

我正在寻找一种更好的方法来实现这一目标。似乎非静态TestCaseSource源已在NUnit 3.x中删除,因此可以了。

提前致谢。

笔记:

  • GetAllRouteTests <>实现了许多测试,而不仅仅是显示的测试。
  • 在一个测试中遍历所有路径将“隐藏”所涵盖的内容,因此希望避免这种情况。

j4n*_*4nw 5

我解决类似问题的方法是拥有一个实现IEnumerable的基类(NUnit的另一个可接受源),请考虑这种设计是否适合您的用例:

// in the parent fixture...
public abstract class TestCases : IEnumerable
{
    protected abstract List<List<object>> Cases { get; }

    public IEnumerator GetEnumerator()
    {
        return Cases.GetEnumerator();
    }
}

// in tests
private class TestCasesForTestFoobar : TestCases
{
    protected override List<List<object>> Cases => /* sets of args */
}

[TestCaseSource(typeof(TestCasesForTestFoobar))]
public void TestFoobar(List<object> args)
{
    // implemented test
}
Run Code Online (Sandbox Code Playgroud)

  • 正如我们的预期。:-)而且,像在此处那样将数据放在单独的类中比将其放入测试类要干净得多。 (3认同)