對于測驗專案中的錯誤,在 Visual Studio C 測驗專案中使用 Assert() 函式是否合適?C 的 Visual Studio 測驗專案使用命名空間 Microsoft::VisualStudio::CppUnitTestFramework
例如,我有一個函式可以構建一個充滿隨機字符值字串的向量,我應該如何處理類的用戶使用錯誤引數使用它的情況?添加 Assert::IsTrue(myVec.size() > 0) 然后測驗專案有可能自己導致測驗失敗是否合適?
一個例子:
/// <summary>
/// Returns a vector of std::string with randomized content.
/// count is the number of entries in the returned vector, length is the max length of the strings.
/// </summary>
/// <returns> a vector of std::string with randomized content. Empty vector on error. </returns>
std::vector<std::string> BuildRandomStringVector(const int count, const int length, const int minLength = 3)
{
//arg error checking, returns empty vector as per description
if (minLength >= length || (length <= 0) || (count <=0) || (minLength <=0))
{
return std::vector<std::string>();
}
//Test all kinds of random character possibilities.
std::uniform_int_distribution<int> distCharPossibility
(std::numeric_limits<char>::min(),
std::numeric_limits<char>::max());
std::uniform_int_distribution<int> distLengthPossibility(minLength, length);
std::random_device rd;
std::mt19937 stringGenerator(rd());
std::vector<std::string> ret;
//the distribution uses the generator engine to get the value
for (int i = 0; i < count; i )
{
const int tLength = distLengthPossibility(stringGenerator);
std::string currentBuiltString = "";
for (int j = 0; j < tLength; j )
{
char currentBuiltChar = distCharPossibility(stringGenerator);
currentBuiltString = currentBuiltChar;
}
ret.push_back(currentBuiltString);
}
return ret;
}
uj5u.com熱心網友回復:
我不建議在測驗中使用任何形式的斷言。理由如下。斷言是一種診斷代碼,通常在“除錯”模式下執行并在“發布”中跳過。您不打算以兩種不同的模式運行測驗,對嗎?而且您不會進行測驗。代碼中條件的驗證不應對測驗執行時間產生任何可測量的影響。在這種情況下,更喜歡可靠性:始終執行測驗健全性,因為您當然可以承受幾微秒長的測驗。如果違反條件應被視為錯誤,則不要回傳空向量:您每次都會在呼叫者處檢查其大小嗎?拋出例外。簡而言之,而不是斷言、使用std::invalid_argument或類似的東西。火了就忘了。
從另一個角度來看:原則上我們可以在生產代碼中嵌入很多自測驗,但我們更喜歡外部測驗,這樣生產代碼真的很苗條和快速。這個問題對于測驗來說不是那么重要:如果你擔心它們會被不正確地使用,那么明確和無條件地測驗它們使用的正確性。使用常識判斷開銷何時仍然可以接受。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/322336.html
上一篇:在VisualStudio中將本地專案重新同步到GitHub存盤庫
下一篇:C語言中變數的范圍
