我有这段代码可以计算文本文件中存在的短语的实例数量。当我从 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 测试,我收到以下消息:
消息:断言失败。预期:<3> 实际:<-1>
关于我的问题来自哪里以及如何解决它的任何想法?谢谢。