微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如果已经验证了无效数字(通过调用另一种方法),则只能调用以下方法.如何在以下代码段中测试 – 覆盖投票线?我知道一种方法可以将VerifyThereAreInvalidiDigits和这种方法合并在一起.我正在寻找任何其他想法.
public int FirstInvalidDigitPosition {
    get {
        for (int index = 0; index < this.positions.Count; ++index) {
            if (!this.positions[index].Valid) return index;
        }
        throw new InvalidOperationException("Attempt to get invalid digit position whene there are no invalid digits.");
    }
}

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

解决方法

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

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

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

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

public int FirstInvalidDigitPosition 
{ 
    get 
    { 
        int index = 0;
        while(true) 
        {
            Debug.Assert(index < this.positions.Length,"Attempt to get invalid digit position but there are no invalid digits!");
            if (!this.positions[index].Valid) return index; 
            index++;
        } 
    }
}

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

public int? FirstInvalidDigitPosition { 
    get { 
        for (int index = 0; index < this.positions.Count; ++index) { 
            if (!this.positions[index].Valid) return index; 
        } 
        return null;
    } 
}

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

原文地址:https://www.jb51.cc/csharp/94832.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐