GoogleTest: Accessing the Environment from a Test

2020-08-23 01:09发布

问题:

I'm trying out gtest for C++ (Google's unit testing framework), and I've created a ::testing::Environment subclass to initialize and keep track of some things that I need for most of my tests (and don't want to setup more than once).

My question is: How do I actually access the contents of the Environment object? I guess I could theoretically save the Environment in a global variable in my test project, but is there a better way?

I'm trying to make tests for some already existing (very tangled) stuff, so the setup is pretty heavy.

回答1:

Using a global variable seems to be the recommended way, according to the Google Test Documentation:

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


回答2:

A related question deals with this for the specific case of creating a std::string, giving a full response showing how to use google's ::testing::Environment and then access the results from inside a unit test.

Reproduced from there (if you upvote me, please upvote them too):

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