c# – 如何测试不应该执行的代码?

前端之家收集整理的这篇文章主要介绍了c# – 如何测试不应该执行的代码?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
如果已经验证了无效数字(通过调用另一种方法),则只能调用以下方法.如何在以下代码段中测试 – 覆盖投票线?我知道一种方法可以将VerifyThereAreInvalidiDigits和这种方法合并在一起.我正在寻找任何其他想法.
  1. public int FirstInvalidDigitPosition {
  2. get {
  3. for (int index = 0; index < this.positions.Count; ++index) {
  4. if (!this.positions[index].Valid) return index;
  5. }
  6. throw new InvalidOperationException("Attempt to get invalid digit position whene there are no invalid digits.");
  7. }
  8. }

我也不想写一个单元测试来执行不应该执行的代码.

解决方法

如果有关的“抛出”声明在任何可能的情况下是真正无法访问的,那么它应该被删除并替换为:
  1. Debug.Fail("This should be unreachable; please find and fix the bug that caused this to be reached.");

如果代码可达,则编写测试该方案的单元测试.公共可访问方法错误报告方案是完全有效的方案.您必须正确处理所有输入,即使输入不良.如果正确的做法是抛出一个异常,然后测试你正在抛出异常.

更新:根据评论,实际上不可能打错误,因此代码无法访问.但是现在Debug.Fail也不可见,并且它不会编译,因为编译器会注意到一个返回值的方法具有可达到的终点.

第一个问题不应该是一个问题;当然,代码覆盖工具应该是可配置的,以忽略不可访问的调试代码.但是这两个问题可以通过重写循环来解决

  1. public int FirstInvalidDigitPosition
  2. {
  3. get
  4. {
  5. int index = 0;
  6. while(true)
  7. {
  8. Debug.Assert(index < this.positions.Length,"Attempt to get invalid digit position but there are no invalid digits!");
  9. if (!this.positions[index].Valid) return index;
  10. index++;
  11. }
  12. }
  13. }

另一种方法是重新组织代码,以便您首先没有问题:

  1. public int? FirstInvalidDigitPosition {
  2. get {
  3. for (int index = 0; index < this.positions.Count; ++index) {
  4. if (!this.positions[index].Valid) return index;
  5. }
  6. return null;
  7. }
  8. }

现在你不需要限制呼叫者首先调用AreThereInvalidDigits;只要使其随时调用方法合法.这似乎是更安全的事情.当您不做昂贵的检查以验证它们是否安全可靠时,爆炸的方法是脆弱的,危险的方法.

猜你在找的C#相关文章