您的位置:首页 > 其它

TEST_F:多个测试使用同样的配置

2015-07-07 22:27 316 查看
转自:http://blog.chinaunix.net/uid-24709751-id-4358266.html
https://code.google.com/p/googletest/wiki/V1_7_Primer 场景:
1. 准备数据A,TEST测试a
2. 准备数据A,TEST测试b
....
3. 准备数据A,TEST测试n

问题:
准备数据A太多次,,,可以使用TEST_F,就是为了解决这种情况。

For each test defined with TEST_F(), Google Test will:

    Create a fresh test fixture at runtime

    Immediately initialize it via SetUp() ,

    Run the test

    Clean up by calling TearDown()

    Delete the test fixture. Note that different tests in the same test case
have different test fixture objects, and Google Test always
deletes a test fixture before it creates the next one. Google Test does not reuse
the same test fixture for multiple tests. Any changes one test makes
to the fixture donot affect other tests. 

As an example, let's write tests for a FIFO queue class named Queue, which has the following interface:

template // E is the element type.

class Queue {

 public:

  Queue();

  void Enqueue(const E& element);

  E* Dequeue(); // Returns NULL if the queue is empty.

  size_t size() const;

  ...

};

First, define a fixture class. By convention, you should give it the name FooTest where Foo is the class being tested.

class QueueTest : public ::testing::Test {

 protected:

  virtual void SetUp() {

    q1_.Enqueue(1);

    q2_.Enqueue(2);

    q2_.Enqueue(3);

  }

  // virtual void TearDown() {}

  Queue q0_;

  Queue q1_;

  Queue q2_;

};

In this case, TearDown() is not needed since we don't have to clean up after each test, other than what's
already done by the destructor.

Now we'll write tests using TEST_F() and this fixture.

TEST_F(QueueTest, IsEmptyInitially) {

  EXPECT_EQ(0, q0_.size());

}

TEST_F(QueueTest, DequeueWorks) {

  int* n = q0_.Dequeue();

  EXPECT_EQ(NULL, n);

  n = q1_.Dequeue();

  ASSERT_TRUE(n != NULL);

  EXPECT_EQ(1, *n);

  EXPECT_EQ(0, q1_.size());

  delete n;

  n = q2_.Dequeue();

  ASSERT_TRUE(n != NULL);

  EXPECT_EQ(2, *n);

  EXPECT_EQ(1, q2_.size());

  delete n;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: