2017-07-26 62 views
2

我目前有一组单元测试,它们对于一些Rest API端点是一致的。说这个类是这样定义的。NUnit 3.x - 用于后代测试类的TestCaseSource

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

有了实现的测试夹具看起来像:

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

这使我能够在所有运行一些常用的测试获得所有/列表中的路由。这也意味着我有直接链接到正在测试的模块的类,以及Resharper/Visual Studio/CI中的测试和代码之间的链接“正常工作”。

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

例如/ API /路径 - 测试?类别=大。

由于[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源,所以没有了。

在此先感谢。

NOTES:

  • GetAllRouteTests <>实现了许多试验,而不是仅仅示出的一个。
  • 在一次测试中迭代所有路线将“隐藏”所涵盖的内容,所以想避免这种情况。

回答

4

我解决了类似的问题的方法是通过实现IEnumerable(用于NUnit的其他可接受的源)碱源类,认为如果这样的设计适合您的用例:

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

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

正如我们预期。 :-)另外,将数据放在单独的类中,与将其放入测试类中相比,它要干净得多。 – Charlie

+0

哦,整洁 - 没有得到比框架的领导开发支持更好:) – j4nw

+0

那么是否需要在实施的夹具上定义[TestCaseSource *]属性?有没有一种方法可以在父装置上定义它,以便通用测试可以在基础/父装置中实现? – Jason