gtest和gmock入門實例

jopen 8年前發布 | 39K 次閱讀 單元測試

對于 c++ 來說寫單元測試和 mock 框架不是一件容易的事情。還好, Google 為我們搭建了一個出色的單元測試和 mock 框架。網上的例子很多都過多強調概念,本文用一個簡單的例子讓大家對于什么是 gtest 和 gmock 讓大家有一個直觀的了解,讓大家很快上手,就像寫 hello word 一樣容易。

gtest&gmock 的 1.6 版本的使用 make 編譯,新版的已經已經遷移到 github 上使用 cmake 編譯,安裝過程很多,這里不在重復,如果大家有需要再單獨寫。

1.下載安裝 Google Test and  Google Mock

2. 編譯生成靜態庫gtest_main.a gmock_main.a (包含main庫后不需要自己寫main函數)

gmock用來對與為實現對象的接口模擬。

我們有一個Messgener.h接口,它的getMessage目前還沒有實現,可以使用mock類提供的宏來模擬,這樣就可以調試客戶端程序,屏蔽Messgener.h的具體實現

#ifndef SRC_MESSENGER_H_
#define SRC_MESSENGER_H_

#include <string>
using namespace std;

class Messenger
{
public:
    virtual ~Messenger() {}
    virtual string getMessage() = 0;
};

#endif /* SRC_MESSENGER_H_ */

Messenger.h 的 mock 類

#ifndef SRC_MOCKMESSENGER_H_
#define SRC_MOCKMESSENGER_H_

#include "Messenger.h"
#include <string>
#include <gmock/gmock.h>
using namespace std;

class MockMessenger : public Messenger
{
public:
    MOCK_METHOD0(getMessage, string());
};

#endif /* SRC_MOCKMESSENGER_H_ */

調用Messenger.h的客戶端程序

HelloWorld.h

#ifndef SRC_HELLOWORLD_H_
#define SRC_HELLOWORLD_H_

#include <string>
#include "Messenger.h"
using namespace std;

class HelloWorld
{
public:
    HelloWorld();
    virtual ~HelloWorld();
    string getMessage(Messenger* messenger) const;
};

#endif /* SRC_HELLOWORLD_H_ */

HelloWorld.cpp

#include "HelloWorld.h"
#include "Messenger.h"

HelloWorld::HelloWorld()
{
}

HelloWorld::~HelloWorld()
{
}

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

有了要測試的代碼和依賴的接口的mock模擬類,下面是gtest的單元測試寫法:

#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));
}

單元測試結果

來自: http://www.nginx.cn/4297.html

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!