我有一个以下函数,根据当前环境返回插件文件名:
std::string Plugin::createFilename(std::string_view name, std::string_view extension) {
constexpr auto compilerPrefix = (Config::isGcc ? "lib" : "");
constexpr auto configurationPostfix = (Config::isDebugConfiguration ? "-d" : "");
std::string result;
result += compilerPrefix;
result += name;
result += configurationPostfix;
result += '.';
result += extension;
return result;
}
此函数的输出取决于以下
constexpr
标志:
Config::isGcc
库是否是使用 GCC 编译的Config::isDebugConfiguration
不言自明如果我无法更改提到的标志,我如何使用 GoogleTest 对此类功能进行单元测试?
Plugin
与(全局)Config
分离。Config
更改为非单例:class Config {
bool isGcc;
bool isDebugConfiguration;
//...
};
在某个地方初始化一个全局
Config
(如果必须的话)
Config
传递给 Plugin
:Plugin::Plugin(const Config& config)
: m_config {config}
{}
(如果需要的话,默认参数为全局
Config
)
Config
中使用您本地的
Plugin
std::string Plugin::createFilename(std::string_view name, std::string_view extension) {
const auto compilerPrefix = (m_config.isGcc ? "lib" : "");
const auto configurationPostfix = (m_config.isDebugConfiguration ? "-d" : "");
std::string result;
result += compilerPrefix;
result += name;
result += configurationPostfix;
result += '.';
result += extension;
return result;
}
通过此设置,您可以将
filename
生成逻辑与全局 Config
解耦,并且您可以轻松地测试与传递给程序的任何设置分开的逻辑。