关闭

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

249人阅读 评论(0) 收藏 举报
分类:

转自: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,就是为了解决这种情况。

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

  2.     Create a fresh test fixture at runtime
  3.     Immediately initialize it via SetUp() ,
  4.     Run the test
  5.     Clean up by calling TearDown()
  6.     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. 

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

  8. template // E is the element type.
  9. class Queue {
  10.  public:
  11.   Queue();
  12.   void Enqueue(const E& element);
  13.   E* Dequeue(); // Returns NULL if the queue is empty.
  14.   size_t size() const;
  15.   ...
  16. };

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

  18. class QueueTest : public ::testing::Test {
  19.  protected:
  20.   virtual void SetUp() {
  21.     q1_.Enqueue(1);
  22.     q2_.Enqueue(2);
  23.     q2_.Enqueue(3);
  24.   }

  25.   // virtual void TearDown() {}

  26.   Queue q0_;
  27.   Queue q1_;
  28.   Queue q2_;
  29. };

  30. 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.

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

  32. TEST_F(QueueTest, IsEmptyInitially) {
  33.   EXPECT_EQ(0, q0_.size());
  34. }

  35. TEST_F(QueueTest, DequeueWorks) {
  36.   int* n = q0_.Dequeue();
  37.   EXPECT_EQ(NULL, n);

  38.   n = q1_.Dequeue();
  39.   ASSERT_TRUE(!= NULL);
  40.   EXPECT_EQ(1, *n);
  41.   EXPECT_EQ(0, q1_.size());
  42.   delete n;

  43.   n = q2_.Dequeue();
  44.   ASSERT_TRUE(!= NULL);
  45.   EXPECT_EQ(2, *n);
  46.   EXPECT_EQ(1, q2_.size());
  47.   delete n;
  48. }

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:61250次
    • 积分:1006
    • 等级:
    • 排名:千里之外
    • 原创:12篇
    • 转载:187篇
    • 译文:1篇
    • 评论:8条
    最新评论