有时候在测试的时候,我们会在测试前做一些初始化活动,和测试后做一些清理工作,gtest提供了多种事件机制,非常方便我们在案例之前或之后做一些操作。总结一下gtest的事件一共有3种:

  1. 全局的,所有案例执行前后。
  2. TestSuite级别的,在某一批案例中第一个案例前,最后一个案例执行后。
  3. TestCase级别的,每个TestCase前后。

接下来按照倒叙3→2→1介绍如何使用事件机制

TestCase事件 

TestCase事件是挂在每个案例执行前后的,实现方式和上面的几乎一样,不过需要实现的是SetUp方法和TearDown方法:

1. SetUp()方法在每个TestCase之前执行

2. TearDown()方法在每个TestCase之后执行

演示代码(Linux环境)

main.cpp

#include "sample-inl.h"
#include "gtest/gtest.h"
namespace {
    class QueueTestSmpl : public testing::Test {
    protected:

        virtual void SetUp() {
            //q0_.Enqueue(1);
            q1_.Enqueue(1);
            q1_.Enqueue(2);
            q2_.Enqueue(3);
        }

        virtual void TearDown() {
        }

        static int Double(int n) {
            return 2 * n;
        }

        // A helper function for testing Queue::Map().
        void MapTester(const Queue<int> * q) {
            // Creates a new queue, where each element is twice as big as the
            // corresponding one in q.
            const Queue<int> * const new_q = q->Map(Double);

            // Verifies that the new queue has the same size as q.
            ASSERT_EQ(q->Size(), new_q->Size());

            // Verifies the relationship between the elements of the two queues.
            for (const QueueNode<int>*n1 = q->Head(), *n2 = new_q->Head();
                n1 != nullptr; n1 = n1->next(), n2 = n2->next()) {
                EXPECT_EQ(2 * n1->element(), n2->element());
            }

            delete new_q;
        }

        // Declares the variables your tests want to use.
        Queue<int> q0_;
        Queue<int> q1_;
        Queue<int> q2_;
    };

    // Tests Dequeue().
    TEST_F(QueueTestSmpl, Dequeue) {
        int * n = q0_.Dequeue();
        EXPECT_TRUE(n == nullptr);

        n = q1_.Dequeue();
        ASSERT_TRUE(n != nullptr);
        EXPECT_EQ(1, *n);
        EXPECT_EQ(1u, q1_.Size());
        delete n;

        n = q1_.Dequeue();
        ASSERT_TRUE(n != nullptr);
        EXPECT_EQ(2, *n);
        EXPECT_EQ(0u, q1_.Size());
        delete n;

        n = q2_.Dequeue();
        ASSERT_TRUE(n != nullptr);
        EXPECT_EQ(3, *n);
        EXPECT_EQ(0u, q2_.Size());
        delete n;
    }
}  // namespace
View Code

相关文章:

  • 2021-12-05
  • 2021-04-29
  • 2022-02-10
  • 2022-12-23
  • 2021-09-17
  • 2021-08-08
  • 2021-09-25
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-02-10
相关资源
相似解决方案