MSTEST0006:避免
| Property | Value |
|---|---|
| 規則識別碼 | MSTEST0006 |
| Title | 避免 [ExpectedException] |
| Category | Design |
| 修正程式是中斷或非中斷 | Non-breaking |
| 預設為啟用 | Yes |
| 默認嚴重性 | 警告從 3.10 開始,資訊之前 |
| 在版本中引進 | 3.2.0 |
| 是否有程式修正 | 是,從 3.7.0 開始 |
備註
此分析器不再與MSTest 4相關,因為屬性已刪除。
Cause
會以 [ExpectedException] 屬性標記方法。
規則描述
建議使用 Assert.ThrowsException 或 Assert.ThrowsExceptionAsync(或者在使用 MSTest 3.8 和更高版本時使用 Assert.ThrowsExactly/Assert.Throws 或 Assert.ThrowsExactlyAsync/Assert.ThrowsAsync),而不是 [ExpectedException] 屬性,這樣可以確保只有預期的程式碼行會拋出預期的異常,而不是影響整個測試主體。 判斷提示 API 也提供更多彈性,可讓您判斷例外狀況的額外屬性。
[TestClass]
public class TestClass
{
[TestMethod]
[ExpectedException(typeof(InvalidOperationException))] // Violation
public void TestMethod()
{
// Arrange
var person = new Person
{
FirstName = "John",
LastName = "Doe",
};
person.SetAge(-1);
// Act
person.GrowOlder();
}
}
如何修正違規
使用 MSTest 3.8 和更新版本時,呼叫 [ExpectedException] 或 Assert.ThrowsException 或 Assert.ThrowsExceptionAsyncAssert.ThrowsExactly/ 或 Assert.ThrowsAssert.ThrowsExactlyAsync/ 來取代 Assert.ThrowsAsync 屬性的使用方式。
[TestClass]
public class TestClass
{
[TestMethod]
public void TestMethod()
{
// Arrange
var person = new Person
{
FirstName = "John",
LastName = "Doe",
};
person.SetAge(-1);
// Act
Assert.ThrowsExactly(() => person.GrowOlder());
}
}
隱藏警告的時機
當方法為單行程式時,隱藏此診斷是安全的。
[TestClass]
public class TestClass
{
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void TestMethod()
{
new Person(null);
}
}
隱藏警告
如果您只想要隱藏單一違規,請將預處理器指示詞新增至原始程式檔以停用,然後重新啟用規則。
#pragma warning disable MSTEST0006
// The code that's violating the rule is on this line.
#pragma warning restore MSTEST0006
若要停用檔案、資料夾或項目的規則,請在組態檔
[*.{cs,vb}]
dotnet_diagnostic.MSTEST0006.severity = none
如需詳細資訊,請參閱 如何抑制程式代碼分析警告。