访问TestCaseSource中的NUnit测试名称

20 c# nunit unit-testing

我有一系列测试,我想在一堆不同的测试中使用相同的测试用例数据.

例如:

[Test, TestCaseSource("TestData")] 
public void Test1(Foo foo)
{
    // test 1
}

[Test, TestCaseSource("TestData")] 
public void Test2(Foo foo)
{
    // test 2
}

private static IEnumerable TestData() 
{
   TestCaseData data; 

   data = new TestCaseData(new Foo("aaa"));
   yield return data; 

   data = new TestCaseData(new Foo("bbb"));
   yield return data; 
}
Run Code Online (Sandbox Code Playgroud)

这会导致一系列测试报告如下:

Namespace.That.Is.Very.Long.TestClass.Test1(Namespace.That.Is.Very.Long.Foo)  
Namespace.That.Is.Very.Long.TestClass.Test1(Namespace.That.Is.Very.Long.Foo)  
Namespace.That.Is.Very.Long.TestClass.Test2(Namespace.That.Is.Very.Long.Foo)  
Namespace.That.Is.Very.Long.TestClass.Test2(Namespace.That.Is.Very.Long.Foo)  
Run Code Online (Sandbox Code Playgroud)

......当你不知道'foo'失败时,这并没有多大意义..

如果在这个SO问题中建议我设置如下名称:

   data = new TestCaseData(new Foo("aaa"));
   data.SetName("foo=aaa");
   yield return data; 
Run Code Online (Sandbox Code Playgroud)

...然后我所有的测试看起来像这样:

foo=aaa   
foo=bbb  
foo=aaa  
foo=bbb 
Run Code Online (Sandbox Code Playgroud)

所以我想弄清楚如何获得当前的测试方法名称.这将出现,如其他SO问题所述,可以通过TestContext完成.

但是,当TestContext.Current.Test存在时,所有属性(如Name)在尝试访问它们时都会抛出NullReferenceException.

是否有其他方法可以实现在测试名称中提供更多有用信息的目标?

Old*_*Fox 30

该属性TestName在NUnit 3中支持字符串格式.

这是一个示例用法:

private static IEnumerable TestData()
{
    TestCaseData data;

    data = new TestCaseData(new Foo("aaa"))
                            .SetName("case 1 {m}");
    yield return data;

    data = new TestCaseData(new Foo("bbb"));
    yield return data;
}
Run Code Online (Sandbox Code Playgroud)

将生成以下输出:

在此输入图像描述

如您所见,第一个案例的测试名称包含自定义前缀+方法名称.

有关NUnit字符串格式化功能的更多信息,请使用此链接.

对于此操作NUnitTestCaseBuilder(第83行)TestNameGenerator方法,有2个类是可重复使用的.GetDisplayName().

  • 注意“.SetArgDisplay”可能是更好(而且可能更新?)的替代方案。您不必更改整个测试名称,而只需更改生成的测试参数的名称。 (4认同)
  • 我不知道NUnit有格式名称的令牌概念.感谢您的链接,很高兴知道! (3认同)
  • 使用“.SetName”为我提供了测试方法的孤立测试以及我返回的“TestCaseData”的数量。而且,它们不像使用“TestCase”时那样分组。`.SetArgDisplayNames` 解决了这一切。NUnit版本:3.13.3 (2认同)

Bor*_*sky -1

这个怎么样?

[TestCase("aaa")] 
[TestCase("bbb")] 
public void MainTest(string str)
{
  Assert.DoesNotThrow(()=> Test1(new Foo(str)));
  Assert.DoesNotThrow(()=> Test2(new Foo(str)));
}

public void Test1(Foo foo)
{
    // test 1
}

public void Test2(Foo foo)
{
    // test 2
}
Run Code Online (Sandbox Code Playgroud)

更新:

[TestCase("aaa")] 
[TestCase("bbb")] 
public void Test1(string str)
{
    var foo = new Foo(str);
    // rest of the test
}

[TestCase("aaa")] 
[TestCase("bbb")] 
public void Test2(string str)
{
    var foo = new Foo(str);
    // rest of the test
}
Run Code Online (Sandbox Code Playgroud)