【问题标题】:Problem unit testing functions that contain file I/O using Visual Studio Native cpp Unite Testing使用 Visual Studio Native c++ 单元测试包含文件 I/O 的问题单元测试函数
【发布时间】: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


【解决方案1】:

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

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

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

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

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2010-12-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-13
      • 1970-01-01
      • 1970-01-01
      • 2010-09-18
      相关资源
      最近更新 更多