1. Download Google Test and Google Mock
2. Extract them and build them by going to the make directory and type 'make'. This will create gtest_main.a and gmock_main.a static libraries.
HelloWorld.h
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | #ifndef HELLOWORLD_H_ #define HELLOWORLD_H_ #include <string> #include "Messenger.h" using namespace std; class HelloWorld { public : HelloWorld(); virtual ~HelloWorld(); string getMessage(Messenger* messenger) const ; }; #endif /* HELLOWORLD_H_ */ |
HelloWorld.cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | #include "HelloWorld.h" #include "Messenger.h" HelloWorld::HelloWorld() { } HelloWorld::~HelloWorld() { } string HelloWorld::getMessage(Messenger* messenger) const { return messenger->getMessage(); } |
Messenger.h
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | #ifndef MESSENGER_H_ #define MESSENGER_H_ #include <string> using namespace std; class Messenger { public : virtual ~Messenger() {} virtual string getMessage() = 0; }; #endif /* MESSENGER_H_ */ |
MockMessenger.h
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | #ifndef MOCKMESSENGER_H_ #define MOCKMESSENGER_H_ #include "Messenger.h" #include <string> #include <gmock/gmock.h> using namespace std; class MockMessenger : public Messenger { public : MOCK_METHOD0(getMessage, string()); }; #endif /* MOCKMESSENGER_H_ */ |
HelloWorldTest.cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | #include "HelloWorld.h" #include <gtest/gtest.h> #include <gmock/gmock.h> #include "MockMessenger.h" #include <string> #include <memory> using namespace testing; TEST(HelloWorldTest, getMessage) { MockMessenger messenger; std::string msg = "Hello World" ; EXPECT_CALL(messenger, getMessage()).WillRepeatedly(Return(ByRef(msg))); HelloWorld helloWorld; EXPECT_EQ( "Hello World" , helloWorld.getMessage(&messenger)); EXPECT_EQ( "Hello World" , helloWorld.getMessage(&messenger)); EXPECT_EQ( "Hello World" , helloWorld.getMessage(&messenger)); } |
With gtest_main.a and gmock_main.a linked, we don't need to manually create the main function.
For more information, go to Google Test and Google Mock.