xUnit Extension之DataTheories

通过为测试添加[Theory]属性,我们可以进行数据驱动的测试。测试数据分为以下几种:

1. InlineData, 由InlineDataAttribute提供

//Provides a data source for a data theory, with the data coming from inline values.
[Theory]
[InlineData("a", "b", "ab")]
[InlineData("1", "2", "12")]
public void TestViaInlineData(string a, string b, string result)
{
Assert.Equal(result, a+b);
}

2.Property Data
public static IEnumerable<object[]> MyTestData
{
get { yield return new object[] { new[]{1,2,3}, "hello world", 2.3 }; }
}

// Provides a data source for a data theory, with the data coming from a public static property on the test class.
// The property must return IEnumerable<object[]> with the test data.
[Theory, PropertyData("MyTestData")]
public void PropertyPassingTestData(object foo, string bar, double baz)
{
Assert.Equal(new[] { 1, 2, 3 }, foo);
Assert.Equal("hello world", bar);
Assert.Equal(2.3, baz);
}
3. ClassData Attribute
public class StubData : IEnumerable<object[]>
{
public IEnumerator<object[]> GetEnumerator()
{
yield return new object[] { new[] { 1, 2, 3 }, "hello world", 2.3 };
}

IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}

//Provides a data source for a data theory, with the data coming from a class
// which must implement IEnumerable<objec[]>.
[Theory, ClassData(typeof(StubData))]
public void ClassPassingTestData(object foo, string bar, double baz)
{
Assert.Equal(new[] { 1, 2, 3 }, foo);
Assert.Equal("hello world", bar);
Assert.Equal(2.3, baz);
}
 
4.ExcelData, 数据从Excel中获得
// Provides a data source for a data theory, with the data coming a Microsoft Excel (.xls) spreadsheet.
[Theory]
[ExcelData(@"UnitTestData.xls", "SELECT x, y, z FROM Data")]
public void TestViaXls(double x,string y,string z)
{
//Data in excel
//x y z
//1 Foo Bar
//14 Biff Baz
Console.WriteLine("{0},{1},{2}", x, y, z);
}

5. OleDbData
// Provides a data source for a data theory, with the data coming from an OLEDB connection.
[Theory, OleDbData(
@"Provider=Microsoft.Jet.OleDb.4.0; Data Source=UnitTestData.xls; Extended Properties=Excel 8.0",
"SELECT x, y, z FROM Data")]
public void TestViaOleDb(double x,string y,string z)
{
//Data in excel
//x y z
//1 Foo Bar
//14 Biff Baz
Console.WriteLine("{0},{1},{2}", x, y, z);
}
还有一个属性叫做SqlServerDataAttribute,派生自OleDbDataAttribute,可以提供sqlserver来源的数据。
OleDb ConnectionString 可参见:http://www.connectionstrings.com/

posted on 2011-11-27 00:49  蚂蚁蚂蚁  阅读(404)  评论(0编辑  收藏  举报

导航