MSTest之数据驱动的单元测试

定义一个类Maths,有一个循环添加两个整数的方法:

public int AddInt(int first, int second)
{
    int sum = first;
    for (int i = 0; i < second; i++)
    {
        sum += 1;
    }

    return sum;
}

内联数据驱动测试

MSTest 使用 DataRow 指定数据驱动测试使用的值,连续对每个数据化进行运行测试

[DataTestMethod]
[DataRow(1, 1, 2)]
[DataRow(2, 2, 4)]
[DataRow(3, 3, 6)]
[DataRow(0, 0, 1)] // The test run with this row fails
public void AddInt_DataRowTest(int x, int y, int expected)
{
    var target = new Maths();
    int actual = target.AddInt(x, y);
    Assert.AreEqual(expected, actual,
        "x:<{0}> y:<{1}>",
        new object[] {x, y});
}

成员数据驱动测试

MSTest 使用 DynamicData 属性来指定将提供数据驱动测试所用数据的成员的名称、种类(属性、默认值或方法)和定义类型(默认情况下使用当前类型)

public static IEnumerable<object[]> AdditionData
{
    get
    {
        return new[]
        { 
            new object[] { 1, 1, 2 },
            new object[] { 2, 2, 4 },
            new object[] { 3, 3, 6 },
            new object[] { 0, 0, 1 }, // The test run with this row fails
        };
    }
}

[TestMethod]
[DynamicData(nameof(AdditionData))]
public void AddIntegers_FromDynamicDataTest(int x, int y, int expected)
{
    var target = new Maths();
    int actual = target.AddIntegers(x, y);
    Assert.AreEqual(expected, actual,
        "x:<{0}> y:<{1}>",
        new object[] {x, y});
}

源提供程序数据驱动测试

  1. 创建测试方法中使用的值的数据源
  2. 将TestContext类型的公共TestContext属性添加到测试类
  3. 创建单元测试方法
  4. 向其添加DataSourceAttribute属性
  5. 使用DataRow索引器属性检索测试方法中使用的值

创建数据源

创建名为 MathsData 的 Sql Compact 数据库和包含以下列名和值的名为 AddIntegersData 的表

FirstNumberSecondNumberSum
0 1 1
1 1 2
2 -3 -1

向测试类添加TestContext

 [TestClass()]
    public class AddIntTest{
    public TestContext TestContext{get; set;}
}

创建测试方法

 [TestClass()]
    public class AddIntTest{
    public TestContext TestContext{get; set;}
    
      [TestMethod]
// 添加DataSourceAttribute     [DataSource(
@"Provider=Microsoft.SqlServerCe.Client.4.0; Data Source=C:\Data\MathsData.sdf;", "AddIntegersData")] public void AddIntegers_FromDataSourceTest() { var target = new Maths(); // Access the data int x = Convert.ToInt32(TestContext.DataRow["FirstNumber"]);

          // 使用DataRow索引器属性检索测试方法中使用的值

int y = Convert.ToInt32(TestContext.DataRow["SecondNumber"]);
         int expected = Convert.ToInt32(TestContext.DataRow["Sum"]);
         int actual = target.AddIntegers(x, y);
         Assert.AreEqual(expected, actual, "x:<{0}> y:<{1}>", new object[] {x, y});
}
            
} 
} 

 

posted @ 2023-05-08 18:45  ttwx  阅读(210)  评论(0)    收藏  举报