Tuesday, December 28, 2010

Getting Started with Google Test and Google Mock

Writing unit test and mock frameworks in C++ is not an easy task. Fortunately, Google has created wonderful unit test and mock frameworks for us :) In this blog, I'm gonna show how to get started with Google Test and Google Mock frameworks.
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
#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
#include "HelloWorld.h"
#include "Messenger.h"

HelloWorld::HelloWorld()
{
}

HelloWorld::~HelloWorld()
{
}

string HelloWorld::getMessage(Messenger* messenger) const
{
    return messenger->getMessage();
}

Messenger.h
#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
#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
#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.

1 comment:

  1. Hello, Could you please tell how to link gtest_main.a and gmock_main.a while using eclipse, I tried including it general settings, but it still there are errors

    ReplyDelete