c# - 测试更多输入

标签 c# unit-testing testing mstest

我正在使用 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);
}

关于c# - 测试更多输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3635167/

相关文章:

c# - 如何将调试器附加到命令行 mstest

c# - 重建项目后清理基地

php - 有没有办法让 PHPUnit 确定 @method 声明的代码覆盖率?

php - 需要帮助编写 php 测试文件来测试我的 PHP Controller 类

c# - AspNet Core 中 UTC 的 Http 查询参数

c# - Facebook CSharp Api 使用图形 api 获取其他用户提要,问题

python - 皮西斯。在不同模块上使用Pysys的日志

ruby-on-rails - 测试method_defined? ActiveRecord 类在实例化之前不起作用

c++ - catch(...) 吞下 xcode llvm 3.0 中的所有其他捕获

testing - 我将如何以 BDD 风格在 Rhomobile 中测试 Controller ?