【发布时间】:2019-09-02 10:34:58
【问题描述】:
我有这段代码可以计算一个短语在文本文件中存在的实例数量。当我从 main() 函数调用它时,它按预期工作。
当我尝试为其编写单元测试时,它在打开文件时失败,返回 -1(参见下面的代码)。
这是我的 countInstances 函数的代码:
int countInstances(string phrase, string filename) {
ifstream file;
file.open(filename);
if (file.is_open) {
stringstream buffer;
buffer << file.rdbuf();
file.close();
string contents = buffer.str();
int fileLength = contents.length();
int phraseLength = phrase.length();
int instances = 0;
// Goes through entire contents
for(int i = 0; i < fileLength - phraseLength; i++){
int j;
// Now checks to see if the phrase is in contents
for (j = 0; j < phraseLength; j++) {
if (contents[i + j] != phrase[j])
break;
}
// Checks to see if the entire phrase existed
if (j == phraseLength) {
instances++;
j = 0;
}
}
return instances;
}
else {
return -1;
}
}
我的单元测试看起来像:
namespace Tests
{
TEST_CLASS(UnitTests)
{
public:
TEST_METHOD(CountInstances) {
/*
countInstances(string, string) :
countInstances should simply check the amount of times that
the passed phrase / word appears within the given filename
*/
int expected = 3;
int actual = countInstances("word", "../smudger/test.txt");
Assert::AreEqual(expected, actual);
}
};
}
对于 CountInstance 测试,我收到以下消息:
消息:断言失败。预期: 实际:
关于我的问题来自何处以及如何解决它的任何想法? 谢谢。
【问题讨论】:
-
测试二进制文件可能不是从可以找到您使用相对路径打开的数据内文件的目录中执行的:
"../smudger/test.txt"。 -
好的,感谢您的回复。您能否详细说明如何解决此问题?
-
最简单的方法是找到测试二进制文件的位置,并从中计算出到
text.txt的相对路径以使用它。
标签: c++ visual-studio unit-testing microsoft-cpp-unit-test