tdd – 使用Assert.Inconclusive

前端之家收集整理的这篇文章主要介绍了tdd – 使用Assert.Inconclusive前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想知道有人应该使用Assert.Inconclusive()。

我正在使用它,如果我的单元测试将要失败的原因除了它是什么。
例如。我有一个类的方法来计算一个int数组的总和。在同一个类中,还有一种计算元素平均值的方法。它通过调用sum并将其除以数组的长度来实现。

为Sum()编写单元测试很简单。
但是,当我对Average()和Sum()进行测试失败时,Average()也可能会失败。

平均线的失败并不明确,因为它失败的原因,它失败的原因除了它应该测试。

这就是为什么我会检查Sum()返回正确的结果,否则我Assert.Inconclusive()。

这被认为是好的做法吗?什么是Assert.Inconclusive?还是应该通过隔离框架来解决前面的例子?

当我使用VS来生成单元测试时,我得到了Assert.Inclusive的生成测试方法,通常我更改断言,当我工作时,其他的东西。我在测试结果中使用Assert.Inconclusive的问号作为标记快速告诉我哪些测试还没有完成。

那么这只是我使用它的方式。从它的名字“不确定”,我想你可以用来表示你的不确定性的状态,只要你记录它的意思。

然而,从您的Average()方法的描述中,我认为您的单元测试可能不够原子,只能涵盖一个“单位”,一个具体的场景。有时候,我为单个方法编写2或3单元测试方法。或者您可以将Average()方法打破涵盖单一职责的较小方法。这样,您可以单元测试这些较小的方法,然后单元测试您的Average()1。

约翰尼斯

这是我如何实现Sum()和Average()方法

  1. public static class MyMath
  2. {
  3. private static void ValidateInput(ICollection<int> numbers)
  4. {
  5. if (numbers == null)
  6. throw new ArgumentNullException("numbers","Null input. Nothing to compute!");
  7. if (numbers.Count == 0)
  8. throw new ArgumentException("Input is empty. Nothing to compute!");
  9. }
  10.  
  11. public static int Sum(int[] numbers)
  12. {
  13. ValidateInput(numbers);
  14.  
  15. var total = 0;
  16. foreach (var number in numbers)
  17. total += number;
  18.  
  19. return total;
  20. }
  21.  
  22. public static double Average(int[] numbers)
  23. {
  24. ValidateInput(numbers);
  25. return Sum(numbers) / numbers.Length;
  26. }
  27. }

为了简单起见,我只是从ValidateInput(ICollection< int>)方法中抛出ArgumentException异常。您还可以检查在ValidateInput(ICollection< int>)方法中溢出的可能性并抛出OverflowException。

这就是说,我将如何测试Average(int [])函数

  1. [TestMethod]
  2. public void AverageTest_GoodInput()
  3. {
  4. int[] numbers = {1,2,3};
  5. const double expected = 2.0;
  6. var actual = MyMath.Average(numbers);
  7. Assert.AreEqual(expected,actual);
  8. }
  9.  
  10. [TestMethod]
  11. [ExpectedException(typeof(ArgumentNullException))]
  12. public void AverageTest_NullInput()
  13. {
  14. int[] numbers = null;
  15. MyMath.Average(numbers);
  16. }
  17.  
  18. [TestMethod]
  19. [ExpectedException(typeof(ArgumentException))]
  20. public void AverageTest_EmptyInput()
  21. {
  22. var numbers = new int[0];
  23. MyMath.Average(numbers);
  24. }

通过这些测试设置,我可以确定,当所有测试通过时,我的功能是正确的。那么,除了溢出的情况。现在我可以返回到ValidateInput(ICollection< int>)方法添加逻辑来检查溢出,然后再添加一个测试,期望OverflowException被抛出,导致溢出的那种输入。或者如果您喜欢使用TDD来进行相反的操作。

我希望这有助于澄清这个想法。

猜你在找的设计模式相关文章