Test Fixtures

Google Test makes us available fixtures, that make our life easier when we would like to use the same data configuration for a number of tests.

A fixture requires us to create a class derived from ::testing::Test that defines all the variables we plan to use in our tests. The declarations of such variables should not be in private section and could be initialized in the class constructor or in the SetUp() method. Then we could do any cleanup job in the destructor (if no exceptions are involved) or in the TearDown() method.

As an example consider the class Squirrel:

#include <string>

class Squirrel
std::string name_;
int nuts_;

Squirrel(const char* const name, int nuts =0) : name_(name), nuts_(nuts) {}

void setNuts(int nuts) { nuts_ += nuts; }
int getNuts() { return nuts_; }
std::string getName() { return name_; }

Since we plan to do many different tests on a couple of squirrels, we create a class derived from ::testing::Test, ChipNDaleTest, in this way:

class ChipNDaleTest : public ::testing::Test {
Squirrel chip_;
Squirrel dale_;

ChipNDaleTest() : chip_("Chip"), dale_("Dale") {}

Now we can write as many text fixture we need, based on that test class:

TEST_F(ChipNDaleTest, Empty) {
EXPECT_EQ(0, chip_.getNuts());
EXPECT_EQ(0, dale_.getNuts());

TEST_F(ChipNDaleTest, Names) {
EXPECT_EQ("Chip", chip_.getName()); // 1.
EXPECT_STREQ("Dale", dale_.getName().c_str()); // 2.

1. The name is tested as a std::string, so we can use operator == and then the EXPECT_EQ test macro.
2. Testing the name as a c-string require the usage of a c-string comparison test macro.

No comments:

Post a Comment