如果需要测试,则C 将常数变量放在CC文件中
c++ where to put constant variables private to cc file if I need them for testing
我的标头文件看起来像:
// 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 ,然后比较哈希。但这可能比值得更多的麻烦。
相关文章:
- 如何创建一个CMake变量,除非显式重写,否则使用默认值
- 将成员变量添加到共享库中的类中,不会破坏二进制兼容性吗
- 将数组的地址分配给变量并删除
- 为"adjacent"变量赋值时出现问题
- enum是C++中的宏变量还是整数变量
- 在全局变量中保存类的实例以重新创建类(创建"backup")
- 用C++中的一个变量定义一个常量
- 具有奇怪重复模板模式的派生类中的成员变量已损坏
- 你能重载对象变量名本身返回的内容吗
- 内置函数可查看CPP中的成员变量
- 是否可以初始化不可复制类型的成员变量(或基类)
- 尝试通过多个向量访问变量时,向量下标超出范围
- 试图让变量检查数组中的某些内容
- Cpp-Tuple使用带有变量的get
- 将包含C样式数组的对象初始化为成员变量(C++)
- 如何使用CMake编译.proto文件来生成.grpcp.pb.cc和.grpc.pb.h文件
- 当vector是tje全局变量时,c++中vector的内存管理
- 通过多个头文件使用常量变量
- 如果需要测试,则C 将常数变量放在CC文件中
- make/cc 找不到头文件,即使它的目录存在于 PATH 变量中