Search code examples
c++unit-testinggoogletest

Unit testing a function which output depends on current environment


I've got a following function that returns a plugin filename depending on current environment:

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;
}

An output of this function depends on the following constexpr flags:

  • Config::isGcc whether the library was compiled using GCC or not
  • Config::isDebugConfiguration self explanatory

How could I unit test such function using GoogleTest if I'm not able to change mentioned flags?


Solution

  • You will have to decouple Plugin from (global) Config.

    Change Config into something that is not a singleton:
    class Config {
        bool isGcc;
        bool isDebugConfiguration;
        //...
    };
    

    Initialise a global Config somewhere (if you have to)

    Pass a Config to Plugin via constructor:
    Plugin::Plugin(const Config& config)
        : m_config {config}
    {}
    

    (default the parameter to the global Config if you have to)

    Use only your local Config in 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;
    }
    

    With this setup, you have decoupled logic of filename generation from the global Config and you can easily test the logic separate from any settings you are passing to your program.