gpt4 book ai didi

c# - NUnit 3.x - 后代测试类的 TestCaseSource

转载 作者:行者123 更新时间:2023-11-30 14:47:24 25 4
gpt4 key购买 nike

我目前有一组单元测试,它们对于许多 Rest API 端点都是一致的。假设类是这样定义的。

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

实现的测试夹具如下所示:

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

这使我能够在所有 GET all/list 路由上运行许多常见测试。这也意味着我有直接链接到被测试模块的类,以及 Resharper/Visual Studio/CI 中测试和代码之间的链接“正常工作”。

挑战在于一些路由需要查询参数来通过路由代码测试其他路径;

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

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

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
}
}

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

我正在寻找实现此目标的更好方法。似乎在 NUnit 3.x 中删除了非静态 TestCaseSource 源,所以就这样了。

提前致谢。

注意事项:

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

最佳答案

我解决类似问题的方法是使用一个实现 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
}

关于c# - NUnit 3.x - 后代测试类的 TestCaseSource,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45318698/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com