【发布时间】:2021-12-02 02:16:31
【问题描述】:
是否适合在 Visual Studio C++ 测试项目中使用 Assert() 函数来解决测试项目中的错误?用于 C++ 的 Visual Studio 测试项目 命名空间 Microsoft::VisualStudio::CppUnitTestFramework
例如,我有一个函数可以构建一个充满随机 char 值字符串的向量,我应该如何处理该类的用户使用错误参数的情况?添加 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;
}
【问题讨论】:
-
示例中没有
Assert? -
苹果,假装有“Assert::IsTrue(minLength >= length);”等在函数顶部的错误检查中,而不是返回一个空向量。但就此而言,Assert 可以在测试项目中的任何位置,问题是测试项目代码是否应该导致正在测试的项目的测试失败?
-
@woofdiggy 添加Assert没有错,只是语义不同。
标签: c++ visual-studio unit-testing