如何使用CSV文件中的数据运行XUnit测试 [英] How to run XUnit test using data from a CSV file
问题描述
是否有一种方法可以使用CSV
文件作为数据源来运行数据驱动的XUnit
测试?我已经尝试过Cavity.Data.XUnit
,但是它不再与XUnit
的最新版本兼容.到目前为止,我只能使用Excel文件实现此目的,但是我需要将其更改为CSV
.
Is there a way to run a data driven XUnit
test using a CSV
file as the data source? I've tried Cavity.Data.XUnit
, but it's no longer compatible with the newest version of XUnit
. So far, I've only been able to achieve this using Excel files, but I need to change them to CSV
instead.
非常感谢您的帮助.
一个例子:
[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.这是一个以这种形式读入数据的示例.
You'll need to create a custom xUnit.Sdk.DataAttribute. This is an example which will read in data in this form.
MyCsv.csv
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方法以执行更多操作.
It just parses strings and ints, but you can extend the ConvertParameter method to do more.
CsvDataAttribute.cs
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;
}
}
这篇关于如何使用CSV文件中的数据运行XUnit测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!