23

I'm trying to understand how the Google Test Fixtures work.

Say I have the following code:

class PhraseTest : public ::testing::Test
{
     protected:
     virtual void SetUp()
     {      
         phraseClass * myPhrase1 = new createPhrase("1234567890");
         phraseClass * myPhrase2 = new createPhrase("1234567890");  
     }

     virtual void TearDown()
    {
        delete *myPhrase1;
        delete *myPhrase2;  
     }
};



TEST_F(PhraseTest, OperatorTest)
{
    ASSERT_TRUE(*myPhrase1 == *myPhrase2);

}

When I compile, why does it say myPhrase1 and myPhrase2 are undeclared in the TEST_F?

Guy Avraham
  • 3,482
  • 3
  • 38
  • 50
bei
  • 933
  • 3
  • 9
  • 17
  • 4
    Another question:
    why you are using "delete *myPhrase1;"?
    I think the appropriate method to use delete is "delete myPhrase1;".
    – Zihan Oct 04 '13 at 15:03

2 Answers2

44

myPhrase1 and myPhrase2 are local to the setup method, not the test fixture.

What you wanted was:

class PhraseTest : public ::testing::Test
{
protected:
     phraseClass * myPhrase1;
     phraseClass * myPhrase2;
     virtual void SetUp()
     {      
         myPhrase1 = new createPhrase("1234567890");
         myPhrase2 = new createPhrase("1234567890");  
     }

     virtual void TearDown()
     {
        delete myPhrase1;
        delete myPhrase2;  
     }
};

TEST_F(PhraseTest, OperatorTest)
{
    ASSERT_TRUE(*myPhrase1 == *myPhrase2);

}
Billy ONeal
  • 104,103
  • 58
  • 317
  • 552
  • protected, says http://code.google.com/p/googletest/source/browse/trunk/samples/sample3_unittest.cc – Bill Aug 23 '10 at 16:40
  • @BillyONeal Is the implied assumption that the code in SetUp() works? That is, you should use a normal TEST() (not TEST_F() ) for everything (here, the constructor) you are going to use in SetUp()? – David Doria Feb 09 '16 at 15:25
  • @DavidDoria I assume SetUp is there for similarity with xunit. – Billy ONeal Feb 12 '16 at 14:59
3

myPhrase1 and myPhrase2 are declared as local variables in the SetUp function. You need to declare them as members of the class:

class PhraseTest : public ::testing::Test
{
  protected:

  virtual void SetUp()
  {      
    myPhrase1 = new createPhrase("1234567890");
    myPhrase2 = new createPhrase("1234567890");  
  }

  virtual void TearDown()
  {
    delete myPhrase1;
    delete myPhrase2;  
  }

  phraseClass* myPhrase1;
  phraseClass* myPhrase2;
};

TEST_F(PhraseTest, OperatorTest)
{
  ASSERT_TRUE(*myPhrase1 == *myPhrase2);
}
Bill
  • 14,257
  • 4
  • 43
  • 55