如果需要测试,则C 将常数变量放在CC文件中

c++ where to put constant variables private to cc file if I need them for testing

本文关键字:变量 CC 文件 常数 测试 如果      更新时间:2023-10-16

我的标头文件看起来像:

// method.h
class Class {
    public:
        string Method(const int number);
};

我的CC文件看起来像

// method.cc
#include "method.h"
namespace {
    const char kImportantString[] = "Very long and important string";
}
string Class::Method(const int number) {
    [... computation which depends on kImportantString ...] 
    return some_string;
}

现在,对于某些输入,Method()应返回kImportantString,但是对于其他输入,它不得返回kImportantString

因此,我想创建一个测试文件,看起来像这样:

// method_test.cc
#include "method.h"
void Test() {
    assert(Method(1) == kImportantString);  // kImportantString is not visible
    assert(Method(2) != kImportantString);  // in this file, how to fix this?
}

但是目前的问题是kImportantString不在method_test.cc文件的范围内。

  • kImportantString添加到method.h并不理想,因为标题文件中不需要它。
  • 创建一个单独的文件" utils.h",然后仅放一个字符串似乎是个过分的(尽管可能是最好的选择)。
  • kImportantString复制到测试文件中不是理想的,因为字符串很长,后来有人可能会意外地将其更改为一个文件,而不是另一个文件。

因此,我的问题是:

在测试文件中可见kimportantstring的最佳方法是什么,并且在尽可能多的其他地方看不见?

您可以将extern声明放在标题文件中,例如

extern const char kImportantString[];

,然后将实际定义留在.c文件中。这将允许测试程序访问字符串,而无需将整个内容复制到标题中。

如果要完全将其完全排除在标题之外,但不要将其复制到测试文件中,您也可以将其制作一个特殊的标题文件,例如kImportantString.h,然后将extern声明放入其中。

另一个选项是计算测试文件中字符串的A hash ,然后比较哈希。但这可能比值得更多的麻烦。