| 房產 | 價值觀 |
|---|---|
| 規則識別碼 | MSTEST0062 |
| 標題 | 在測試方法中避免使用出參數與參考參數 |
| 類別 | Usage |
| 修正是破壞性或非破壞性 | Non-breaking |
| 預設啟用 | Yes |
| 默認嚴重性 | Info |
| 在版本 中引進 | 4.1.0 |
| 是否有程序代碼修正 | Yes |
原因
測試方法的參數標示為 out 或 ref 修飾符。
規則描述
測試方法不應有 out 或 參數 ref 。 MSTest 負責呼叫測試方法,且在測試方法結束後,它從不讀取參考傳遞的值。 這些修飾符具有誤導性,因為它們暗示測試方法會回傳將使用的數值,但 MSTest 在測試完成後從未使用過。
[TestClass]
public class TestClass
{
[TestMethod]
public void TestMethod(out string s, ref string s2) // Violation
{
s = "test";
}
}
如何修正違規
將測試方法參數中的 out 和 ref 修飾符移除。
[TestClass]
public class TestClass
{
[TestMethod]
public void TestMethod()
{
// Test code
}
}
如果你需要測試帶有 out 或 ref 參數的方法,請在你的測試方法內呼叫它們:
[TestClass]
public class TestClass
{
[TestMethod]
public void TestMethodWithOutParameter()
{
// Arrange
string result;
string passedByRef = "some value";
var instance = new MyClass();
// Act
bool success = instance.TryGetValue(out result, ref passedByRef);
// Assert
Assert.IsTrue(success);
Assert.AreEqual("expected", result);
}
}
針對資料驅動測試:
[TestClass]
public class TestClass
{
[TestMethod]
[DataRow("input1", "expected1")]
[DataRow("input2", "expected2")]
public void TestMethod(string input, string expected)
{
// Arrange
string result;
var instance = new MyClass();
// Act
bool success = instance.TryParse(input, out result);
// Assert
Assert.IsTrue(success);
Assert.AreEqual(expected, result);
}
}
隱藏警告的時機
請勿隱藏來自此規則的警告。 目前沒有有效的情境,測試方法應該使用out或ref參數。
隱藏警告
如果您只想要隱藏單一違規,請將預處理器指示詞新增至原始程式檔以停用,然後重新啟用規則。
#pragma warning disable MSTEST0062
// The code that's violating the rule is on this line.
#pragma warning restore MSTEST0062
若要停用檔案、資料夾或項目的規則,請在none中將其嚴重性設為。
[*.{cs,vb}]
dotnet_diagnostic.MSTEST0062.severity = none
如需詳細資訊,請參閱 如何隱藏程式碼分析警告。