0

我有这段代码可以计算文本文件中存在的短语的实例数量。当我从 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>

关于我的问题来自哪里以及如何解决它的任何想法?谢谢。

4

2 回答 2

0

尽管在单元测试中具有文件系统依赖关系并不理想,但您可以简单地在包含测试数据文件的文件夹中创建单元测试 DLL。

在此处输入图像描述

于 2019-06-19T02:37:01.317 回答
0

您的测试依赖于文件系统中存在的某些文件这一事实使您的测试难以维护和理解,因为每个测试用例的信息都是分布式的。如果您稍后更改目录布局,则测试可能会再次失败。

对代码进行单元测试的更好方法是将读取的文件内容提取到它自己的函数中,例如,返回带有文件内容的字符串。首先,将该函数放在一个单独的文件中。

然后,在您的测试中,您可以用模拟替换该函数:模拟返回一个字符串,但不会从文件中读取它 - 相反,您的测试代码提供该函数随后应返回的字符串。由于原始函数被放入单独的文件中,因此您可以通过不链接原始函数而是模拟函数来创建测试可执行文件。

这样,您的测试不依赖于文件系统。您可以轻松创建大量测试用例,并从测试代码中控制一切。

有更先进的方法可以实现这一点,但这个答案只是为了给你一个起点。如果您想了解更多信息,请搜索依赖注入、模拟、控制反转。

于 2019-04-17T22:39:12.223 回答