我可以在google test中启动代码时初始化静态值吗?

时间:2016-10-25 07:42:26

标签: c++ googletest

我正在创建一个模板类,它是id生成器类的接口。 我可以用google test编译和运行代码。我可以在下面的代码中确认staticInitializer()将变量generator_初始化为非空值。但是,它在谷歌测试中将为空值。 虽然我可以在SetUp()函数中初始化它并且它运行良好,但如果可能的话,我不想仅为谷歌测试修改我的代码。

如何使用google test初始化在启动代码中初始化一次的静态变量?

#include <memory>

template<typename Generator>
class IdGenerator {
public:
    using GeneratorType = Generator;
    using ShareGeneratorType = std::shared_ptr<GeneratorType>;

    IdGenerator() {
        staticInitializer();
    };

    static void staticInitializer(void) {
        // This function runs at booting code once. At the time,
        // the following generator_ is non-null value, but it will
        // be null value in google test.
        ShareGeneratorType new_generator = ShareGeneratorType(new Generator());
        generator_ = new_generator;
    }

    template <typename ObjectType>
    static int nextId(void) {
        return generator_->nextId<ObjectType>();
    }

private:
    static ShareGeneratorType generator_;

};

class IdGeneratorImpl {
public:
    template <typename ObjectType>
    int nextId(void) {
        // ObjectSelector<ObjectType> is a traits class which gives index of ObjectType
        static auto object_index = ObjectSelector<ObjectType>::index;
        return ++id_counters_[object_index];
    }
private:
    static constexpr int no_of_types_ = 4;
    std::array<int, no_of_types_> id_counters_;
};

IdGenerator从static_initialization.hpp文件运行并初始化其静态成员generator_。

//static_initialization.hpp
IdGenerator<IdGeneratorImpl> for_static_initializatoin;

0 个答案:

没有答案