c ++如果我需要它们进行测试,将常量变量私有放到cc文件中

时间:2016-06-28 01:08:08

标签: c++ testing namespaces constants

我的头文件如下所示:

// 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在测试文件中可见的最佳方法,并且在尽可能多的其他地方不可见?

1 个答案:

答案 0 :(得分:0)

您可以在头文件中添加extern声明,例如

extern const char kImportantString[];

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

如果你想将它完全从标题中删除,而不是将其复制到测试文件中,你也可以只创建一个特殊的头文件,如kImportantString.h并将extern声明放入那里。

另一种选择是在测试文件中计算字符串的哈希,然后只比较哈希值。但这可能比它的价值更麻烦。