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;只要使其随时调用方法合法.这似乎是更安全的事情.当您不做昂贵的检查以验证它们是否安全可靠时,爆炸的方法是脆弱的,危险的方法.

相关文章

在要实现单例模式的类当中添加如下代码:实例化的时候:frmC...
1、如果制作圆角窗体,窗体先继承DOTNETBAR的:public parti...
根据网上资料,自己很粗略的实现了一个winform搜索提示,但是...
近期在做DSOFramer这个控件,打算自己弄一个自定义控件来封装...
今天玩了一把WMI,查询了一下电脑的硬件信息,感觉很多代码都...
最近在研究WinWordControl这个控件,因为上级要求在系统里,...