有被測函數(shù)如下,該函數(shù)使用了一個接口類。我們測試的時候,這個接口類的實現(xiàn)是要用gmock打樁打掉的。
int FuncToBeTested(SomeInterface & if, std::string & param) {
return if.some_func(param) == true ? 1 : -1;
}
接口類的定義如下:
class SomeInterface {
public:
virtual bool some_func(std::string & some_param) = 0;
};
使用Gmock樁掉這個接口類的實現(xiàn):
class MockInterfaceImpl : public SomeInterface {
public:
MOCK_METHOD1(some_func, bool(std::string & param));
};
MOCK_METHOD1中的1表示樁掉的函數(shù)只有一個入?yún)ⅰ?/p>
完整的示例代碼如下:
$ cat Test.cpp
#include <iostream>
#include <gtest/gtest.h>
#include <gmock/gmock.h>
class SomeInterface {
public:
virtual bool some_func(std::string & param) = 0;
};
class MockInterfaceImpl : public SomeInterface {
public:
MOCK_METHOD1(some_func, bool(std::string & param));
};
int FuncToBeTested(SomeInterface & interface, std::string param) {
return interface.some_func(param) == true ? 1 : -1;
}
TEST(TestSuiteName, TestCaseName) {
MockInterfaceImpl mock_if_impl;
EXPECT_CALL(mock_if_impl, some_func)
.Times(::testing::AtLeast(1))
.WillOnce(::testing::Return(true));
int ret_value = FuncToBeTested(mock_if_impl, "SomeString");
EXPECT_EQ(ret_value, 1);
}
$ g++ Test.cpp -l gtest -l gtest_main -l gmock -l pthread && ./a.out