I have this piece of code that counts the amount of instances a phrase exists within a text file. When I call this from a main() function, it works as expected.
When I try to write a Unit Test for it, it fails upon opening the file, returning -1 (see code below).
Here is the code for my countInstances function:
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;
}
}
My Unit Test looks like:
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);
}
};
}
For the CountInstance Test I get the following message:
Message: Assert failed. Expected:<3> Actual:<-1>
Any ideas on where my issue comes from and how I could go about fixing it? Thanks.