IEnumerable <t>作为数据驱动测试的DataSource

时间:2015-04-22 16:06:55

标签: .net datasource ienumerable mstest data-driven-tests

.Net是否可以创建使用IEnumerable<T>作为DataSource的数据驱动测试?

问题是:
有一个我想测试的课程。它的行为略有不同,具体取决于它作为构造函数参数接收的int值 并且有一个静态方法返回该构造函数参数的所有可能值的IEnumerable<int>

1 个答案:

答案 0 :(得分:0)

找到了解决方案。不是很满意,但它确实有效。

[DataSourceGenerator("source.csv")]
public class DataDrivenTests
{
    public TestContext TestContext { get; set; }

    [TestMethod]
    [DataSource("Microsoft.VisualStudio.TestTools.DataSource.CSV", "source.csv", "source#csv", DataAccessMethod.Sequential)]
    //The source is generated automatically by DataSourceGenerator attribute
    public void DataDrivenTest()
    {
        //Here you can implement a data driven test of your own
    }
}

[AttributeUsage(AttributeTargets.Class)]
internal sealed class DataSourceGeneratorAttribute : Attribute
{
    public DataSourceGeneratorAttribute(string fileName)
    {
        var csvContent = GenerateCsvContent();

        File.WriteAllText(fileName, csvContent);
    }
    private string GenerateCsvContent()
    {
        //Here you can generate content for your csv
    }
}