在多个测试中创建并保持状态

时间:2019-02-22 14:37:02

标签: c++ googletest

在Microsoft的cpp单元测试框架中,有可能一次完成几次测试的初始化(清理):

using namespace Microsoft::VisualStudio::CppUnitTestFramework;
TEST_CLASS(MyTestClass)
{
public:
    TEST_CLASS_INITIALIZE(InitForAllTests)
    {
         // Do something exactly one time for all tests in this class.
         // This is run before the first test starts.
    }
    TEST_CLASS_CLEANUP(CleanupForAllTests)
    {
        // This is run after the last test of the class has finished executing.
    }
    // Contains a lot of tests.
};

Google测试中是否内置类似功能?

测试夹具类不合适,因为将为每个测试重新创建对象,因此将为每个测试运行构造函数/析构函数和SetUp() / TearDown()(例如TEST_METHOD_INITIALIZETEST_METHOD_CLEANUP(MS cpp单元测试框架)。

2 个答案:

答案 0 :(得分:1)

您可以使用test environment进行全局设置和拆卸。

答案 1 :(得分:1)

您正在寻找SetUpTestSuite() and TearDownTestSuite()(以前 googletest SetUpTestCase()和TearDownTestCase())。对于 例如:

gtester.cpp

#include <gtest/gtest.h>
#include <iostream>

struct test_suite_one : public ::testing::Test {
    static void SetUpTestSuite() {
        ++suite_resource;
        std::cout << "suite_resource=" << suite_resource << std::endl;
    }

    static void TearDownTestSuite() {
        suite_resource = 0;
        std::cout << "suite_resource=" << suite_resource << std::endl;
    }
    void SetUp() override {
        ++test_resource;
        std::cout << "test_resource=" << test_resource << std::endl;
    }
    void TearDown(){}
protected:
    unsigned test_resource = 0;
    static unsigned suite_resource;
};

unsigned test_suite_one::suite_resource;

TEST_F(test_suite_one,test_one) {
    ASSERT_EQ(test_resource,1);
    ASSERT_TRUE(suite_resource == test_resource);
    ++suite_resource;
    std::cout << "suite_resource=" << suite_resource << std::endl;
}

TEST_F(test_suite_one,test_two) {
    ASSERT_EQ(test_resource,1);
    ASSERT_TRUE(suite_resource > test_resource);
    std::cout << "suite_resource=" << suite_resource << std::endl;
}

int main(int argc, char **argv) {
  ::testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}

运行方式:

$ g++ -Wall -Wextra -o gtester gtester.cpp -lgtest -pthread
$ ./gtester 
[==========] Running 2 tests from 1 test suite.
[----------] Global test environment set-up.
[----------] 2 tests from test_suite_one
suite_resource=1
[ RUN      ] test_suite_one.test_one
test_resource=1
suite_resource=2
[       OK ] test_suite_one.test_one (0 ms)
[ RUN      ] test_suite_one.test_two
test_resource=1
suite_resource=2
[       OK ] test_suite_one.test_two (0 ms)
suite_resource=0
[----------] 2 tests from test_suite_one (1 ms total)

[----------] Global test environment tear-down
[==========] 2 tests from 1 test suite ran. (1 ms total)
[  PASSED  ] 2 tests.