Separate test cases across multiple files in google test

后端 未结 4 1285
自闭症患者
自闭症患者 2020-12-17 07:53

I\'m new in google test C++ framework. It\'s quite easy to use but I\'m wondering how to separate the cases into multiple test files. What is the best way?

Include t

4条回答
  •  鱼传尺愫
    2020-12-17 08:37

    I think the main missing point in the other answer is that you need to #include the test files.

    Here is my way to split the tests:

    1. Put the tests in .h files potentially with header guards, although not needed if you take care.
    2. Have one main program as defined below that includes the test headers
    3. A Makefile that compiles + links the main test program.

    Do not use the same name for a test twice across all files!

    // main_test.cc
    #include 
    
    #include "test_a.h"
    #include "test_b.h"
    #include "test_c.h"
    
    int main(int argc, char **argv) {
        testing::InitGoogleTest(&argc, argv);
        return RUN_ALL_TESTS();
    }
    

    Use the Makefile from googletest and add the rules:

    #  compiles main test program
    main_test.o : main_test.cc test_a.h test_b.h test_c.h $(GTEST_HEADERS)
        $(CXX) $(CPPFLAGS) $(CXXFLAGS) -c $< -o $@
    # links test program
    main_test : main_test.o
        $(CXX) $(LDFLAGS) -L$(GTEST_LIB_DIR) $^ -lgtest_main -lpthread -o $@
    
    

    I use a naming convention to order the tests by alphabetic letters:

    // test_a.h
    #include "some_class.h"
    
    TEST(SomeClass, aName)
    {
      library::SomeClass a("v", {5,4});
      EXPECT_EQ(a.name(), "v");
    }
    
    TEST(SomeClass, bSize)
    {
      library::SomeClass a("v", {5,4});
      EXPECT_EQ(a.size(0), 5);
      EXPECT_EQ(a.size(1), 4);
    }
    

    Then you can run individual tests with

    ./main_test --gtest_filter=SomeClass.a*
    

提交回复
热议问题