我正在密集使用NUnit TestCase属性.对于我的一些测试,使用20多个TestCase属性进行注释,定义了20多个测试用例.但是,我想测试所有20个测试用例,并说出额外的值,可能是1或0.这对我来说意味着不同的测试用例.使用ValuesAttribute可以轻松实现:
我目前的状态:
[TestCase(10, "Hello", false)] // 1
[TestCase(33, "Bye", true)] // 2
// imagine 20+ testcase here)]
[TestCase(55, "CUL8R", true)] // 20+
public void MyTest(int number, string text, bool result)
Run Code Online (Sandbox Code Playgroud)
我想做类似的事情(我不能:)
[TestCase(10, "Hello", false)] // 1
[TestCase(33, "Bye", true)] // 2
// imagine 20+ testcase here)]
[TestCase(55, "CUL8R", true)] // 20+
public void MyTest([Values(0,1)] int anyName, int number, string text, bool result)
Run Code Online (Sandbox Code Playgroud)
我为什么要这样做?因为这40多个组合意味着不同的测试用例.不幸的是,NUnit不允许同时使用[TestCase]和[Values]属性,测试运行器需要与TestCaseAttribute中列出的参数数量完全相同的参数.(我可以理解建筑师,但仍然......)我唯一能想到的是:
[TestCase(1, 10, "Hello", false] // 1
[TestCase(1, 33, "Bye", true] // 2
// imagine 20+ testcase here]
[TestCase(1, 55, "CUL8R", true] // 20
[TestCase(0, 10, "Hello", false] // 21
[TestCase(0, 33, "Bye", true] // 22
// imagine 20+ testcase here]
[TestCase(0, 55, "CUL8R", true] // 40
public void MyTest(int anyName, int number, string text, bool result)
Run Code Online (Sandbox Code Playgroud)
所以我最终被迫犯了复制和粘贴的罪,我复制了TestCases,现在我有40+.必须有某种方式......如果不仅仅是(0,1)值的范围,而是0,1,2,3.我们以80多个复制的测试用例结束了吗?
错过了什么?
Thx提前
尽管它已经很老了,但它仍然是我的第一页搜索结果,但我想要比现有解决方案更轻的东西。
使用另一个ValuesAttribute或ValueSourceAttribute用于测试用例允许组合,但诀窍是在使用它们时将一组链接值作为单个案例获取 - 每个仅影响单个命名参数。
属性需要编译时常量输入。这允许你创建一个文字数组,但如果你的值是不同的类型,你必须使数组成为一个通用的基类型,比如object. 您还必须按索引访问项目。我喜欢简短、明显的单元测试;解析数组使测试看起来忙碌而混乱。
一种简洁的解决方案是将ValueSource属性与提供元组的静态方法一起使用。这个方法可以紧跟在测试方法之前,只是比使用TestCase属性稍微冗长一点。使用问题中的代码:
public static (int, string, bool)[] Mytest_TestCases()
{
return new[] {
(10, "Hello", false),
(33, "Bye", true),
(55, "CUL8R", true)
};
}
[Test]
public void Mytest(
[Values(0,1)] int anyName,
[ValueSource(nameof(Mytest_TestCases))] (int number, string text, bool result) testCase)
Run Code Online (Sandbox Code Playgroud)
后面的参数ValueSource是一个名为 的元组testCase,其内容被命名为匹配原始测试用例参数。要在测试中引用这些值,请在其前面加上元组的名称(例如,testCase.result而不仅仅是result)。
作为写到这里,六个测试将运行-一个用于每个可能的组合anyName和testCase。
我不介意像这个例子中的简单数据的元组,但我更进一步并定义了一个非常简单的类来代替元组。用法基本相同,只是您不在参数中命名成员。
public class Mytest_TestCase
{
public Mytest_TestCase(int number, string text, bool result)
{
Number = number;
Text = text;
Result = result;
}
public int Number;
public string Text;
public bool Result;
}
public static Mytest_TestCase[] Mytest_TestCases()
{
return new[] {
new Mytest_TestCase(10, "Hello", false),
new Mytest_TestCase(33, "Bye", true),
new Mytest_TestCase(55, "CUL8R", true)
};
}
[Test]
public void Mytest(
[Values(0,1)] int anyName,
[ValueSource(nameof(Mytest_TestCases))] Mytest_TestCase testCase)
Run Code Online (Sandbox Code Playgroud)
测试用例类定义可以移到测试类的底部,或者移到单独的文件中。就我个人而言,我更喜欢将两者都放在测试类的底部——当你想在测试旁边看到它时,你可以随时查看定义。
| 归档时间: |
|
| 查看次数: |
1111 次 |
| 最近记录: |