对输出取决于当前环境的函数进行单元测试

问题描述 投票:0回答:1

我有一个以下函数,根据当前环境返回插件文件名:

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 对此类功能进行单元测试?

c++ unit-testing googletest
1个回答
0
投票

您必须将
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
解耦,并且您可以轻松地测试与传递给程序的任何设置分开的逻辑。

© www.soinside.com 2019 - 2024. All rights reserved.