在我的情况下,我想从CSV文件中加载数据,但是我无法将文件名传递给“datasource”。
经过一番努力,我得到了这个两分钱的解决方案。
首先,我继承了TestCaseSourceAttirbute。
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public class TestCaseCsvAttribute : TestCaseSourceAttribute
{
public TestCaseCsvAttribute(Type mapped, Type config) : base(typeof(TestCsvReader<,>).MakeGenericType(mapped, config), "Data")
{ }
}
然后我创建了数据层,这里使用的是CSV读取器。
public sealed class TestCsvReader<T, C>
{
public TestCsvReader()
{
this.Config = (C)Activator.CreateInstance<C>();
}
private C Config { get; set; }
private string Filename
{
get
{
try
{
string result = Convert.ToString(typeof(C).GetProperty(string.Format("{0}Filename", typeof(T).Name)).GetValue(this.Config));
if (!File.Exists(result))
throw new Exception(string.Format("Unable to find file '{0}' specified in property '{1}Filename' in class '{1}'", result, typeof(C).Name));
return result;
}
catch
{
throw new Exception(string.Format("Unable to find property '{0}Filename' in class '{1}'", typeof(T).Name, typeof(C).Name));
}
}
}
public IEnumerable Data()
{
string file = this.Filename;
T[] result = null;
using (StreamReader reader = File.OpenText(file))
{
}
yield return new TestCaseData(result);
}
}
然后我创建了一个类,其唯一的作用是包含文件路径属性。有一个关于属性的命名约定,即ClassTypeName +“Filename”。
public class Configurations
{
public string ConflictDataFilename
{
get
{
return @"C:\test.csv";
}
}
}
此时只需要根据数据映射的类别和包含文件路径的类别进行相应的装饰即可。
[Test(Description="Try this one")]
[TestCaseCsv(typeof(ClassMappedToData), typeof(Configurations))]
public void Infinite(ClassMappedToData[] data)
{
}
希望这能有所帮助。