使用 NUnit 我想測驗給定的字串是否短于 200 個字符。我的目標不是對這個字串進行硬編碼,因為在另一個測驗中我將有一個包含 201 個字符的字串作為對應部分。
讓我們看看測驗簽名:
[TestCase("GetTooLongName")]
public void If_NameIsTooLong_ReturnError(string name)
我試圖使用一個字串建構式,它需要 2 個引數、一個字符和它被連接的次數。我試圖從欄位和函式中獲取它:
private static readonly string GetTooLongName = new('x', 201);
private static string LongNameStillOk => new('x', 200);
最后我得到一個錯誤:
An attribute must be a constant expression...
有沒有一種漂亮而干凈的方法來提供如此長的字串來測驗屬性?
uj5u.com熱心網友回復:
最后我使用TestCaseSource了 NUnit 的屬性。
代碼如下所示:
private const int MAX_ALLOWED_STRING_LENGTH = 200;
private static string[] _nameTooLongSource= {new('x', MAX_ALLOWED_STRING_LENGTH 1)};
[TestCaseSource(nameof(_nameTooLongSource))]
public void If_NameIsTooLong_ReturnError(string name)
然后為_nameTooLongSource陣列的每個元素創建一個場景。它只有一個元素,即長字串。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/404668.html
標籤:
