我是C#和NUnit初学者,并尝试做一些简单的测试。
当我使用硬编码测试用例时,例如[TestCase(1,2)],一切正常。我想使用文本文件作为测试用例源,但不知道该怎么做。我在StackOverflow和其他地方找到了一些例子,但它不起作用。
// Code that works
namespace UnitTesting.GettingStarted.Tests
{
[TestFixture]
// this part works fine
public class CalculatorTestMultiplication
{
[TestCase(1, 2)]
[TestCase(2, 3)]
[TestCase(3, 8)]
[TestCase(1000, 1)]
public void MultiplierParZero(int lhs, int rhs)
{
var systemUnderTest = new Calculator();
Assert.NotZero(systemUnderTest.Multiply(lhs, rhs));
}
}
}
//Code with error
using System;
using System.Collections.Generic;
using System.IO;
using NUnit.Framework;
namespace UnitTesting.GettingStarted.Tests2
{
public class CalculatorTestMultiplicationFile
{
static object[] TestData()
{
var reader = new StreamReader(File.OpenRead(@"C:\Test\MultiplicationZero.txt"));
List<object[]> rows = new List<object[]>();
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
var values = line.Split(',');
rows.Add(values);
}
return rows.ToArray<object[]>(); // PROBLEM CODE
}
[TestCaseSource("TestCases")]
public void MultiplyByZero(int lhs, int rhs)
{
var systemUnderTest = new Calculator();
Assert.NotZero(systemUnderTest.Multiply(lhs, rhs));
}
}
}
与硬编码测试用例一样,如果参数不等于零,我希望测试通过,这就是我在测试文件中所拥有的。我甚至无法启动此测试,因为在代码行中:“return rows.ToArray();”,我看到以下错误:非泛型方法'List.ToArray()'不能与类型参数一起使用。显然,对象声明有问题,但我不知道如何解决它。
谢谢,
麦克风
作为初学者,使用简单类型和数组很有吸引力,而object[]
肯定非常简单。但是,对象的使用会使事情有点混淆,因为错误与参数的类型有关。如果你返回一个TestCaseData
项目数组会更容易,每个项目代表一个测试用例,并且一次处理一个sinngle参数。
例如...
static IEnumerable<TestCaseData> TestData()
{
var reader = new StreamReader(File.OpenRead(
@"C:\Test\MultiplicationZero.txt"));
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
var values = line.Split(',');
// Assume there are exactly two items, and they are ints
// If there are less than two or format is incorrect, then
// you'll get an exception and have to fix the file.
// Otherwise add error handling.
int lhs = Int32.Parse(values[0])
int rhs = Int32.Parse(values[1]);
yield return new TestCaseData(lhs, rhs);
}
}
与您的代码的差异:
yield
(再次,不要求但可能更清楚)注意:我只输入了这个,没有编译或运行。因人而异。