File tree Expand file tree Collapse file tree 6 files changed +90
-0
lines changed Expand file tree Collapse file tree 6 files changed +90
-0
lines changed Original file line number Diff line number Diff line change
1
+ cmake_minimum_required (VERSION 3.14 )
2
+ set (CMAKE_CXX_STANDARD 14 )
3
+
4
+ project (ExampleGtest LANGUAGES CXX )
5
+
6
+ include (FetchContent )
7
+ FetchContent_Declare (
8
+ googletest
9
+ GIT_REPOSITORY https://github.com/google/googletest.git
10
+ GIT_TAG bf66935e07825318ae519675d73d0f3e313b3ec6
11
+ )
12
+ FetchContent_MakeAvailable (googletest )
13
+
14
+ add_executable (${PROJECT_NAME} example_test.cpp MockData.cpp )
15
+
16
+ target_link_libraries (${PROJECT_NAME} gtest_main gmock_main )
17
+
18
+ include (GoogleTest )
19
+ gtest_discover_tests (${PROJECT_NAME} )
20
+
21
+ #include headers
22
+ include_directories (include )
Original file line number Diff line number Diff line change
1
+ #include " Data.h"
2
+ #include " MockData.h"
3
+ #include < memory>
4
+
5
+ MockData::Ptr global_mock_data_ptr = std::make_shared<MockData>();
6
+
7
+ #include < iostream>
8
+ int Data::call () {
9
+ std::cout<<__LINE__<<std::endl;
10
+ return global_mock_data_ptr->call ();
11
+ }
Original file line number Diff line number Diff line change
1
+ #include " Data.h"
2
+
3
+ class Example {
4
+ Data data;
5
+
6
+ public:
7
+ int foo () {
8
+ return data.call ();
9
+ }
10
+ };
Original file line number Diff line number Diff line change
1
+ #include < gtest/gtest.h>
2
+ #include < gmock/gmock.h>
3
+ #include " example.cpp"
4
+ #include " MockData.h"
5
+
6
+ extern std::shared_ptr<MockData> global_mock_data_ptr;
7
+
8
+ class testFixture : public testing ::Test
9
+ {
10
+ public:
11
+ testFixture ()
12
+ {
13
+ }
14
+ ~testFixture ()
15
+ {
16
+ std::move (global_mock_data_ptr).reset (); // delete the global mock
17
+ }
18
+ };
19
+
20
+
21
+ TEST_F (testFixture, FooReturnsMockedValue) {
22
+
23
+ EXPECT_CALL (*global_mock_data_ptr, call ()).WillOnce (::testing::Return (99 ));
24
+
25
+ Example ex;
26
+ ASSERT_EQ (99 , ex.foo ());
27
+ }
Original file line number Diff line number Diff line change
1
+ #pragma once
2
+
3
+ class Data {
4
+ public:
5
+ virtual int call ();
6
+ virtual ~Data () = default ; // Add a virtual destructor for good measure
7
+
8
+ };
Original file line number Diff line number Diff line change
1
+ #include " Data.h"
2
+ #include < gmock/gmock.h>
3
+
4
+
5
+ class MockData {
6
+ public:
7
+ MOCK_METHOD (int , call, ());
8
+ using Ptr = std::shared_ptr<MockData>;
9
+ };
10
+
11
+ // Declare the global pointer to MockData
12
+ extern MockData::Ptr global_mock_data_ptr;
You can’t perform that action at this time.
0 commit comments