SEAME-pt / Team05_SEA-ME-warm-up

1 stars 0 forks source link

Gtest #31

Closed matde-je closed 6 days ago

matde-je commented 6 days ago

Download and configure gtest

matde-je commented 6 days ago
git clone https://github.com/google/googletest.git
cd googletest
sudo mkdir build
cd build
sudo cmake ..
sudo make
sudo cp ~/googletest/build/lib/*.a /usr/lib

Example CMakeLists.txt:

cmake_minimum_required(VERSION 3.10)

project(Car)

enable_testing()

include(FetchContent) // Include FetchContent for Google Test
FetchContent_Declare(
  googletest
  URL https://github.com/google/googletest/archive/release-1.12.1.zip
)

FetchContent_MakeAvailable(googletest)

set(SOURCE_FILES
  Brake.cpp
  Wheel.cpp
  Car.cpp
  Transmission.cpp
  Engine.cpp
  Part.cpp
  Main.cpp
)

add_executable(${PROJECT_NAME} ${SOURCE_FILES} test/test.cpp)

target_link_libraries(Car PRIVATE gtest) // Link Google Test libraries to the test executable

add_test(NAME MyTests COMMAND Car) // Add tests to CTest

Gtest Options:

EXPECT_EQ(val1, val2): Checks if val1 == val2.
EXPECT_NE(val1, val2): Checks if val1 != val2.
EXPECT_TRUE(condition): Checks if condition is true.
EXPECT_FALSE(condition): Checks if condition is false.
ASSERT_*: Similar to EXPECT_*, but aborts the test if it fails.
EXPECT_LT(a, b) Checks if a < b
EXPECT_GT(a, b) Checks if a > b

Example test/test.cpp:

#include "../Car.hpp"
#include <gtest/gtest.h>

TEST(CarTest, Model)
{
    Car myCar;
    myCar.set_model("BMW E90 318d");

    EXPECT_EQ(myCar.get_model(), "BMW E90 318d");
}

Example Main.cpp:

#include "Car.hpp"
#include <gtest/gtest.h>

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

    return result;
}

Dont forget to include the headers!