Skip to main content
 首页 » 编程设计

c#之测试更多输入

2024年02月24日23mayingbao

我正在使用 MSTest 进行测试,当我想应用更多输入时,测试如下所示:

[TestMethod] 
public void SumTest() 
{ 
  // data to test 
  var items = new [] { 
    new { First = 1, Second = 1, Expected = 2 }, 
    new { First = -1, Second = 1, Expected = 0 }, 
    new { First = 1, Second = 2, Expected = 3 }, 
    new { First = 1, Second = -1, Expected = 0 }, 
  }; 
 
  ICalculator target = GetSum(); // can be in the loop body 
 
  foreach(var item in items) 
  { 
    var actual = target.Sum(item.First, item.Second); 
    Assert.AreEqual(item.Expected, actual); 
  } 
} 

我觉得这种测试方式不太对。 IE。我想将测试数据生成和测试本身分开。

我知道,MSTest 中有“数据驱动测试”支持,但对我来说还不够:

  1. 无法使用某些算法生成 items 集合。
  2. 我不能使用非原始类型。

那么您对此类测试有何建议?

我想要这样的东西,但我不确定这是否是正确的方式,以及某些测试框架是否支持这种情况。

[TestData] 
public IEnumerable<object> SumTestData() 
{ 
  yield return new { First = 1, Second = 1, Expected = 2 }; 
  yield return new { First = -1, Second = 1, Expected = 0 }; 
  yield return new { First = 1, Second = 2, Expected = 3 }; 
  yield return new { First = 1, Second = -1, Expected = 0 }; 
} 
 
[TestMethod(DataSource="method:SumTestData")] 
public void SumTest(int first, int second, int expected) 
{ 
  // this test is runned for each item that is got from SumTestData method 
  // (property -> parameter mapping is no problem) 
  ICalculator target = GetSum(); 
  var actual = target.Sum(first, second); 
  Assert.AreEqual(expected, actual); 
} 

请您参考如下方法:

NUnit 支持这种情况:

public static IEnumerable SumTestData() { 
    return new List<TestCaseData> { 
        new TestCaseData( 1,  1,  2), 
        new TestCaseData(-1,  1,  0), 
        new TestCaseData( 1,  2,  3), 
        new TestCaseData( 1, -1,  0) 
    }; 
} 
 
[Test] 
[TestCaseSource("SumTestData")] 
public void SumTest(int first, int second, int expected) { 
} 

参数可以是任何类型。 TestCaseData 构造函数采用对象的参数数组,因此您只需确保您的测试值可转换为实际的测试方法参数类型。

非空参数化测试方法(@RobertKoritnik)

通过使用非无效测试方法并提供测试数据结果,可以进一步增强上层代码。我还提供了另一种创建测试数据的方法。

public static IEnumerable SumTestData() { 
    yield return new TestCaseData( 1,  1).Returns(2); 
    yield return new TestCaseData(-1,  1).Returns(0); 
    yield return new TestCaseData( 1,  2).Returns(3); 
    yield return new TestCaseData( 1, -1).Returns(0); 
} 
 
[Test] 
[TestCaseSource("SumTestData")] 
public int SumTest(int first, int second) 
{ 
    return Sum(first, second); 
}