GoogleTest:从测试中访问环境

jco*_*jco 8 c++ unit-testing googletest

我正在尝试gtest for C++(Google的单元测试框架),并且我已经创建了一个:: testing :: Environment子类来初始化并跟踪我的大多数测试所需的一些东西(并且不想要设置不止一次).

我的问题是:我如何实际访问Environment对象的内容?我想我理论上可以在我的测试项目中将环境保存在全局变量中,但是有更好的方法吗?

我正在尝试为一些已经存在的(非常纠结的)东西进行测试,因此设置非常繁重.

thc*_*ark 5

一个相关的问题针对创建 a 的特定情况处理此问题std::string,给出完整的响应,显示如何使用谷歌的 ::testing::Environment 然后从单元测试内部访问结果。

从那里转载(如果你赞成我,请也赞成他们):

class TestEnvironment : public ::testing::Environment {
public:
    // Assume there's only going to be a single instance of this class, so we can just
    // hold the timestamp as a const static local variable and expose it through a
    // static member function
    static std::string getStartTime() {
        static const std::string timestamp = currentDateTime();
        return timestamp;
    }

    // Initialise the timestamp in the environment setup.
    virtual void SetUp() { getStartTime(); }
};

class CnFirstTest : public ::testing::Test {
protected:
    virtual void SetUp() { m_string = currentDateTime(); }
    std::string m_string;
};

TEST_F(CnFirstTest, Test1) {
    std::cout << TestEnvironment::getStartTime() << std::endl;
    std::cout << m_string << std::endl;
}

TEST_F(CnFirstTest, Test2) {
    std::cout << TestEnvironment::getStartTime() << std::endl;
    std::cout << m_string << std::endl;
}

int main(int argc, char* argv[]) {
    ::testing::InitGoogleTest(&argc, argv);
    // gtest takes ownership of the TestEnvironment ptr - we don't delete it.
    ::testing::AddGlobalTestEnvironment(new TestEnvironment);
    return RUN_ALL_TESTS();
}
Run Code Online (Sandbox Code Playgroud)


Mar*_*vin 4

根据Google 测试文档,使用全局变量似乎是推荐的方式:

::testing::Environment* const foo_env = ::testing::AddGlobalTestEnvironment(new FooEnvironment);
Run Code Online (Sandbox Code Playgroud)

  • 实际上,他们似乎强烈建议不要这样做:_“但是,我们强烈建议您编写自己的 main() 并在那里调用 AddGlobalTestEnvironment() ...”_。 (5认同)