如何在NUnit的TestCaseSource中使用三元元组作为测试参数?
问题原因
你的问题由两个写法错误共同导致:
- 测试方法同时标注了
[Test]和[TestCaseSource]特性:[Test]会让NUnit额外生成一个无参数的测试实例,而你的测试方法需要两个入参,这个无参数实例无法执行,就是你看到的「1条测试未运行」的来源。 - 数据源返回类型不符合NUnit参数化测试约定:当前返回三元元组数组的写法属于匹配巧合,极易出现解析异常。
修复代码
1. 测试方法修正(删除多余的[Test]特性)
[TestCaseSource(nameof(TestGetTimeLeftData))] public void TestGetTimeLeft((int, int, int) alarmTime, (int, int, int) clockTime) { (int, int, int) expectedTime = (3, 0, 0); (int, int, int) result = Helper.GetTimeLeft(alarmTime, clockTime); Assert.AreEqual(expectedTime, result); }
2. 数据源修正(两种可选写法)
通用object数组写法
private static IEnumerable<object[]> TestGetTimeLeftData { get { // 数组内元素顺序、类型和测试方法入参一一对应 yield return new object[] { (2, 0, 0), (23, 0, 0) }; } }
强类型写法(更推荐,编译期即可校验类型匹配)
private static IEnumerable<((int, int, int) alarm, (int, int, int) clock)> TestGetTimeLeftData { get { yield return ((2, 0, 0), (23, 0, 0)); } }
内容的提问来源于stack exchange,提问作者MikeG
相关产品推荐
相关产品推荐

