Google单元测试默认设置

时间:2017-03-02 20:45:23

标签: c++ c++11 googletest

我正在用C ++中的谷歌单元测试制作一个单元测试系统。而且我注意到我所有的单元测试设置都包含相同的一行,而我所有的泪水都包含其他行,等于所有。

我想知道是否有任何方法可以在实际设置任何单元测试之前默认创建一个设置。

#include <gtest.h>
class TestExample : ::testing::Test
{
    public:
        virtual void SetUp ()
        {
            //same line for all tests of my system
            my_system::clean_system();

            //code of specific setup
            //...
        }
        virtual void TearDown ()
        {
            //Code of specific teardown
            //...

            my_system::clean_system();
        }
};

1 个答案:

答案 0 :(得分:1)

您可以创建一个包装类,即TestWrapper,您可以在其中定义默认SetUp()并调用CustomSetUp()

#include <gtest.h>

class TestWrapper: public ::testing::Test
{
    public:
        virtual void CustomSetUp() {}
        virtual void SetUp ()
        {
            //same line for all tests of my system
            my_system::clean_system();

            CustomSetUp(); //code of specific setup
        }
};

然后在单元测试中使用TestWrapper课程代替::testing::Test并重载CustomSetUp()代替SetUp()

class TestExample : public TestWrapper
{
    public:
        virtual void CustomSetUp ()
        {
            //code of specific setup
            //...
        }
        virtual void TearDown ()
        {
            //Code of specific teardown
            //...

            my_system::clean_system();
        }
};