[英]NCover: Exclude unexecutable line of code from coverage
以下代碼中的switch語句具有編譯器所需的default
子句和一個很好的安全措施,但從未執行過。 在為其他一切編寫測試之后,我無法(或應該)測試那一行。 我不在乎我沒有用測試覆蓋那一行,但是我的TestDriven.net NCover代碼覆蓋率報告確實顯示了未經測試的行,這導致類覆蓋率降至86%。 有沒有辦法讓NCover排除這一行?
public static class OperandTypeExtensions
{
public static string ToShortName(this OperandType type)
{
#region Contract
Contract.Requires<InvalidEnumArgumentException>(Enum.IsDefined(typeof(OperandType), type));
#endregion
switch (type)
{
case OperandType.None: return "<none>";
case OperandType.Int32: return "i32";
case OperandType.Int64: return "i64";
default:
throw new NotSupportedException();
}
}
}
我的問題類似於這個問題 ,但沒有一個答案有助於我的具體情況。
您可以通過將OperandType枚舉中不存在的整數值轉換為OperandType來執行它:
Assert.Throws<InvalidEnumArgumentException>(delegate { ((OperandType)Int32.MaxValue).ToShortName(); } );
順便說一句,我發現86%的報道並沒有什么不好
更新:在此處使用Contract
沒有任何好處。 如果您的方法不支持值,您將獲得異常。
public static class OperandTypeExtensions
{
public static string ToShortName(this OperandType type)
{
switch (type)
{
case OperandType.None: return "<none>";
case OperandType.Int32: return "i32";
case OperandType.Int64: return "i64";
default:
throw new NotSupportedException();
}
}
}
你應該在這里有default
選項,因為如果將新值添加到OperandType
枚舉,你的Contract
將允許該值,但是switch不支持新選項。
UPDATE2:如果您確實需要100%覆蓋率和此方法的合同,則使用OperandType.None作為默認選項:
public static class OperandTypeExtensions
{
public static string ToShortName(this OperandType type)
{
Contract.Requires<InvalidEnumArgumentException>(Enum.IsDefined(typeof(OperandType), type));
switch (type)
{
case OperandType.Int32: return "i32";
case OperandType.Int64: return "i64";
default:
return "<none>";
}
}
}
並添加到關於枚舉的測試斷言:
CollectionAssert.AreEquivalent(Enum.GetValues(typeof(OperandType)),
new OperandType[] { OperandType.Int32,
OperandType.Int64,
OperandType.None });
我還希望我的所有源文件都達到100%,而不是%,但是為了避免每次運行代碼覆蓋率工具誤報時對每個類進行雙重檢查。
在這種情況下和IMO,如果函數是公共的,這意味着你應該用類似的東西測試它 :
Assert.Throws<NotSupportedException>( OperandTypeExtensions.ToShortName() );
可能發生的其他情況
通常,當throws
或Debug.Assert
為private的函數時會出現更大的問題。 在這種情況下,有時測試無法到達線條。 或者不能封裝在Assert.Throws
。
我發現確保每一行都被執行的唯一方法。 遠非理想和非常丑陋 ,我會喜歡這樣的評論注釋來禁用它。 雖然沒有在C#中工作。
private string ToShortName(this OperandType type)
{
var result = "";
switch (type)
{
case OperandType.Int32: result = "i32";
case OperandType.Int64: result = "i64";
}
Debug.Assert(result != "", "Invalid type.");
return result;
}
使用此解決方案,在源代碼中,它將在返回空字符串之前中斷(在Debug中),並且Code Coverage將看到Debug.Assert行已執行。
PS雖然,我想知道是否有更好的解決方案,如注釋或某些東西來禁用特定的代碼塊。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.