有没有一种方法可以使用CSV文件作为数据源来运行数据驱动的XUnit测试?我已经尝试过Cavity.Data.XUnit,但是它不再与最新版本的XUnit兼容.到目前为止,我只能使用Excel文件实现此目的,但是我需要将其更改为CSV.
任何帮助是极大的赞赏.
一个例子:
[Theory]
[ExcelData(@"Settings\TestFileParam.xls", "Select url, username, password, from TestData")]
//^Replace with a CSV file instead
public void Tester_Method(string url, string username, string password)
{
//Code reading the data from CSV
Assert.True(something);
}
解决方法:
您需要创建一个自定义xUnit.Sdk.DataAttribute.这是一个以这种形式读入数据的示例.
MyCsv.csv
sep=,
csvRowOne,csvRowTwo,csvRowThree
15,"Just A Test","Apples are Red"
然后,您将这样称呼它:
[Theory]
[CsvData(@"C:\MyCsv.csv")]
public void TestWithCSVData(int csvRowOne, string csvRowTwo, string csvRowThree)
它只是解析字符串和整数,但是您可以扩展ConvertParameter方法以执行更多操作.
CsvDataAttribute.cs
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
public class CsvDataAttribute : DataAttribute
{
private readonly string _fileName;
public CsvDataAttribute(string fileName)
{
_fileName = fileName;
}
public override IEnumerable<object[]> GetData(MethodInfo testMethod)
{
var pars = testMethod.GetParameters();
var parameterTypes = pars.Select(par => par.ParameterType).ToArray();
using (var csvFile = new StreamReader(_fileName))
{
csvFile.ReadLine();// Delimiter Row: "sep=,". Comment out if not used
csvFile.ReadLine(); // Headings Row. Comment out if not used
string line;
while ((line = csvFile.ReadLine()) != null)
{
var row = line.Split(',');
yield return ConvertParameters((object[])row, parameterTypes);
}
}
}
private static object[] ConvertParameters(IReadOnlyList<object> values, IReadOnlyList<Type> parameterTypes)
{
var result = new object[parameterTypes.Count];
for (var idx = 0; idx < parameterTypes.Count; idx++)
{
result[idx] = ConvertParameter(values[idx], parameterTypes[idx]);
}
return result;
}
private static object ConvertParameter(object parameter, Type parameterType)
{
return parameterType == typeof(int) ? Convert.ToInt32(parameter) : parameter;
}
}