Mock,更確切地說應該是Mock Object。當我們在單元測試、模塊的接口測試時,當這個模塊需要依賴另外一個/幾個類,而這時這些類還沒有開發好,這時我們就可以定義Mock對象來模擬那些類的行爲。
mock工具的其中一個非常重要的作用是指定函數的行爲(模擬函數的行爲)。可以對入參進行校驗,對出參進行設定,還可以指定函數的返回值。
Google's framework for writing and using C++ mock classes on a variety of platforms (Linux, Mac OS X, Windows, Windows CE, Symbian, etc). Inspired by jMock, EasyMock, and Hamcrest, and designed with C++'s specifics in mind, it can help you derive better designs of your system and write better tests.
Google Mock:
-
provides a declarative syntax for defining mocks,
-
can easily define partial (hybrid) mocks, which are a cross of real and mock objects,
-
handles functions of arbitrary types and overloaded functions,
-
comes with a rich set of matchers for validating function arguments,
-
uses an intuitive syntax for controlling the behavior of a mock,
-
does automatic verification of expectations (no record-and-replay needed),
-
allows arbitrary (partial) ordering constraints on function calls to be expressed,
-
lets a user extend it by defining new matchers and actions.
-
does not use exceptions, and
-
is easy to learn and use.
Google Mock is not a testing framework itself. Instead, it needs a testing framework for writing tests. Google Mock works seamlessly with Google Test, but you can also use it with any C++ testing framework.
參考:
1. 代碼 mock_test.cc
#include <gtest/gtest.h>
#include <gmock/gmock.h>
using namespace testing;
class A {
public:
int set(int num) {
value = num;
return num;
}
int get() {
return value;
}
int value;
};
class MockA : public A {
public:
MOCK_METHOD1(set, int(int num));
MOCK_METHOD0(get, int());
};
TEST(Atest, getnum)
{
MockA m_A;
int a = 10;
EXPECT_CALL(m_A, set(_)).WillRepeatedly(Return(a));
int k = m_A.set(200);
EXPECT_EQ(10, k);
}
int main(int argc, char *argv[]) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
2. 編譯
g++ mock_test.cc -lgtest -lgmock -lpthread -std=c++11
3. 測試執行
baoli@ubuntu:~/tools/gtest/mytest$ ./a.out
[==========] Running 1 test from 1 test suite.
[----------] Global test environment set-up.
[----------] 1 test from Atest
[ RUN ] Atest.getnum
[ OK ] Atest.getnum (0 ms)
[----------] 1 test from Atest (0 ms total)
[----------] Global test environment tear-down
[==========] 1 test from 1 test suite ran. (0 ms total)
[ PASSED ] 1 test.
4. 說明
4.1 MOCK_METHOD
MOCK_METHOD1(set, int(int num)); //調用set方法,一個參數(int num),返回int型
MOCK_METHOD0(get, int()); //調用get方法,無參數,返回int型
4.2 EXPECT_CALL
This means EXPECT_CALL() should be read as expecting that a call will occur in the future, not
that a call has occurred. Why does Google Mock work like that? Well, specifying the expectation
beforehand allows Google Mock to report a violation as soon as it arises, when the context (stack
trace, etc) is still available. This makes debugging much easier