共用方式為


MSTEST0058:避免在 catch 區塊中斷言

房產 價值觀
規則識別碼 MSTEST0058
標題 避免在接球區塊中出現斷言
類別 Usage
修正是破壞性或非破壞性 Non-breaking
預設啟用 Yes
默認嚴重性 Info
在版本 中引進 4.1.0
是否有程序代碼修正

原因

測試方法在區 catch 塊內包含斷言陳述句。

規則描述

將斷言置於 catch 區塊中是一種反模式,可能導致測驗結果混亂,並使測驗更難理解。 當拋出例外時,執行catch區塊,並執行斷言。 然而,若未拋出例外, catch 該區塊永遠不會執行,可能導致錯誤的信心以為測試通過。

相反地,請使用 Assert.Throws 或類似的方法來驗證預期的例外是否被拋出。 這使測試意圖更明確,並確保測試行為正確。

[TestClass]
public class TestClass
{
    [TestMethod]
    public void TestMethod()
    {
        try
        {
            // Code that might throw.
            DoSomethingThatMightThrow();
        }
        catch (Exception ex)
        {
            Assert.AreEqual("Expected error message", ex.Message); // Violation
        }
    }
}

如何修正違規

使用 Assert.ThrowsAssert.ThrowsExactly 或相關的斷言方法來測試例外。

[TestClass]
public class TestClass
{
    [TestMethod]
    public void TestMethod_ThrowsExceptionWithExpectedMessage()
    {
        InvalidOperationException exception = Assert.Throws<InvalidOperationException>(() => DoSomethingThatMightThrow());
        Assert.AreEqual("Expected error message", exception.Message);
    }
}

隱藏警告的時機

如果你有正當需求需要捕捉例外並執行無法用標準斷言方法表達的複雜驗證,可能會抑制此警告。 不過,建議先考慮重構你的測試,使用更明確的例外斷言。

隱藏警告

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

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

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

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

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