共用方式為


MSTEST0061:使用 OSCondition 屬性代替執行時檢查

房產 價值觀
規則識別碼 MSTEST0061
標題 使用 OSCondition 屬性代替執行時檢查
類別 Usage
修正是破壞性或非破壞性 Non-breaking
預設啟用 Yes
默認嚴重性 Info
在版本 中引進 4.1.0
是否有程序代碼修正 Yes

原因

測試方法使用IsOSPlatform(OSPlatform)檢查進行早期回傳,而非OSConditionAttribute屬性。

規則描述

如果你想根據作業系統跳過測試,請使用 OSConditionAttribute 屬性而非手動執行時檢查。 屬性方法提供更好的測試可發現性與更明確的測試意圖,並能與測試框架妥善整合,將測試標記為跳過而非通過。

using System.Runtime.InteropServices;

[TestClass]
public class TestClass
{
    [TestMethod]
    public void TestMethod()
    {
        if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) // Violation
        {
            return;
        }
        
        // Test code that requires Windows
    }
}

如何修正違規

將執行時檢查換成屬性 [OSCondition]

using Microsoft.VisualStudio.TestTools.UnitTesting;

[TestClass]
public class TestClass
{
    [TestMethod]
    [OSCondition(OperatingSystems.Windows)]
    public void TestMethod()
    {
        // Test code that requires Windows
    }
}

[OSCondition] 屬性支援以下作業系統:

  • OperatingSystems.Linux
  • OperatingSystems.OSX (macOS)
  • OperatingSystems.Windows
  • OperatingSystems.FreeBSD

你也可以用 bitwise OR組合多個作業系統:

[TestMethod]
[OSCondition(OperatingSystems.Windows | OperatingSystems.Linux)]
public void TestMethod()
{
    // Test code that requires Windows or Linux
}

隱藏警告的時機

如果你的執行時檢查比簡單的早期回傳模式更複雜,或你需要執行無法用 [OSCondition] 屬性表達的條件邏輯,你可以抑制此警告。

隱藏警告

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

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

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

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

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