【问题标题】:GoogleTest: Accessing the Environment from a TestGoogleTest:从测试中访问环境
【发布时间】:2010-03-12 19:32:03
【问题描述】:

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

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

我正在尝试对一些已经存在(非常复杂)的东西进行测试,因此设置非常繁重。

【问题讨论】:

    标签: c++ unit-testing googletest


    【解决方案1】:

    related question 针对创建 std::string 的特定情况处理此问题,并给出完整的响应,展示如何使用 google 的 ::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();
    }
    

    【讨论】:

    • 此答案未提供“如何访问环境对象”的信息。它显示静态函数调用。这不是答案。
    • 答案是如何设置它的完整演示,包括如何访问测试夹具中的 TestEnvironment 对象。显示的 TestEnvironment 是环境对象,getStartTime() 是它的属性之一。这个答案现在已经 3 岁了,我已经改用 Rust,所以跟不上 googletest。也许现在没有那么繁琐的方法了;如果是这样,您应该这样做并提供您自己的答案,@shs_sf。
    【解决方案2】:

    使用全局变量似乎是推荐的方式,根据Google Test Documentation

    ::testing::Environment* const foo_env = ::testing::AddGlobalTestEnvironment(new FooEnvironment);
    

    【讨论】:

    • 实际上他们似乎强烈建议不要这样做:“但是,我们强烈建议您编写自己的 main() 并在那里调用 AddGlobalTestEnvironment() ...” .
    猜你喜欢
    • 2020-06-26
    • 1970-01-01
    • 2019-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多