共用方式為


MSTEST0057:在自訂測試方法屬性中傳播來源資訊

房產 價值觀
規則識別碼 MSTEST0057
標題 在自訂測試方法屬性中傳遞來源資訊
類別 Usage
修正是破壞性或非破壞性 Non-breaking
預設啟用 Yes
默認嚴重性 警告
在版本 中引進 4.0.0
是否有程序代碼修正 Yes

原因

自訂 TestMethodAttribute 類別不會將呼叫者資訊傳播到基底類別建構子。

規則描述

在建立由 TestMethodAttribute衍生的自訂測試方法屬性時,應利用呼叫者資訊屬性傳播來源資訊。 這讓 MSTest 能正確追蹤測試方法的原始檔案與行號,改善診斷、測試結果報告及測試總管的行為。

public class MyTestMethodAttribute : TestMethodAttribute
{
    public MyTestMethodAttribute() // Violation
        : base()
    {
    }
}

如何修正違規

在建構子中加入 CallerFilePath 參數 CallerLineNumber ,並傳給基底類別。

using System.Runtime.CompilerServices;

public class MyTestMethodAttribute : TestMethodAttribute
{
    public MyTestMethodAttribute(
        [CallerFilePath] string callerFilePath = "", 
        [CallerLineNumber] int callerLineNumber = -1)
        : base(callerFilePath, callerLineNumber)
    {
    }
}

隱藏警告的時機

請勿隱藏來自此規則的警告。 傳播來源資訊對於正確的測試報告與診斷至關重要。

隱藏警告

如果您只想要隱藏單一違規,請將預處理器指示詞新增至原始程式檔以停用,然後重新啟用規則。

#pragma warning disable MSTEST0057
// The code that's violating the rule is on this line.
#pragma warning restore MSTEST0057

若要停用檔案、資料夾或項目的規則,請在none中將其嚴重性設為

[*.{cs,vb}]
dotnet_diagnostic.MSTEST0057.severity = none

如需詳細資訊,請參閱 如何隱藏程式碼分析警告