views:

90

answers:

1

Hey! 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  A: 
// A convenient wrapper for adding an environment for the test
// program.
//
// You should call this before RUN_ALL_TESTS() is called, probably in
// main().  If you use gtest_main, you need to call this before main()
// starts for it to take effect.  For example, you can define a global
// variable like this:
//
//   testing::Environment* const foo_env =
//       testing::AddGlobalTestEnvironment(new FooEnvironment);
//
// However, we strongly recommend you to write your own main() and
// call AddGlobalTestEnvironment() there, as relying on initialization
// of global variables makes the code harder to read and may cause
// problems when you register multiple environments from different
// translation units and the environments have dependencies among them
// (remember that the compiler doesn't guarantee the order in which
// global variables from different translation units are initialized).
inline Environment* AddGlobalTestEnvironment(Environment* env) {
Pierre-Antoine LaFayette