How to run gtest?

Viewed 1838

I'm new to using gtest (actually, C++ in general) I'm making an application where I need to have unit tests (using CLion IDE, in case if that matters).

The steps I followed:

  1. Download gtest from GitHub.
  2. Extracted the zip file into a new lib directory in my project.
  3. Modify CMakeLists.txt

    cmake_minimum_required(VERSION 3.13)
    project(my_project)
    
    set(CMAKE_CXX_STANDARD 14)
    
    add_subdirectory(lib/gtest) # I renamed googletest-master folder to gtest, so that should be fine.
    include_directories(lib/gtest/googletest/include)
    include_directories(lib/gtest/googlemock/include)
    
    add_executable(my_project main.cpp blablabla1.h blablabla1.cpp blabla2.h blabla2.cpp etc...)
    
    target_link_libraries(my_project gtest gtest_main)
    
  4. Created a new directory called Tests and added a cpp file in it with the following code:

    #include "gtest/gtest.h"
    #include "gmock/gmock.h"
    
    TEST(TrivialTest, Negative) {
        ASSERT_EQ(0, 1);
    }
    
  5. I'm stuck here, how should I run this test? If I put the following code in main function, then tests will start every time a normal run to the program is made. I want to somehow separate the normal program running, from the unit tests running.

    #include "gtest/gtest.h"
    #include "gmock/gmock.h"
    
    int main() {
        testing::InitGoogleTest();
        return RUN_ALL_TESTS();
    }
    
1 Answers

The test source files should be made an seperated executable file, it has its own main function.

Your main source code should not contain

    testing::InitGoogleTest();
    return RUN_ALL_TESTS();

This is what you want.

Related