如何在GTest中模拟外部函数



我有一个名为tt_init_device()的函数。我写了一个TSET_F()测试用例来验证它。但在tt_init_device()内部,我有一个外部函数wfdEnumerateDevices(NULL, 0, NULL);。。。我需要模拟这个函数以获得true或false的返回值。。。需要帮助来做同样的事情。

TEST_F(FusaAppTh,Sample)
{
FusaTelltaleClientAppTh AppThObj(1,"abc");
EXPECT_EQ( WFD_ERROR_NONE,AppThObj.tt_init_device());
}
WFDErrorCode FusaTelltaleClientAppTh::tt_init_device(void)
{
.
.
value = wfdEnumerateDevices(NULL, 0, NULL);
.
.
}

提前感谢!

您应该为要模拟的函数创建一个包装器。下面是一个例子。

首先为包装器创建一个接口,然后创建两个继承的版本。一个用于生产代码,调用原始wfdEnumerateDevices函数,另一个用于测试,用于模拟该函数。

下面是一个示例实现:

// This is your original function.
int wfdEnumerateDevices(int* p1, int v1, int* p2) { return 0; }
// Create a wrapper interface for it.
class WrapperInterface {
public:
virtual int wfdEnumerateDevices(int* p1, int v1, int* p2) = 0;
};
// An inherited wrapper that calls your original function. Use this for
// your production code.
class ProductionWrapper : public WrapperInterface {
public:
int wfdEnumerateDevices(int* p1, int v1, int* p2) {
return ::wfdEnumerateDevices(p1, v1, p2);
}
};
// An inherited wrapper used only for testing.
class MockWrapper : public WrapperInterface {
public:
MOCK_METHOD(int, wfdEnumerateDevices, (int*, int, int*), (override));
};
class FusaTelltaleClientAppTh {
public:
// Your class should now have a wrapper member which can either be the
// production version for production or the test version for testing.
WrapperInterface* wrapper_;
// Inject the  wrapper in constructor.
FusaTelltaleClientAppTh(int v1, std::string s1, WrapperInterface* wrapper)
: wrapper_(wrapper) {}
int tt_init_device(void) {
//  Call the wrapper function instead of the original one. Depending on the
//  wrapper_  type, either the  production or the test version will be
//  called.
return wrapper_->wfdEnumerateDevices(nullptr, 0, nullptr);
}
};
// Tests mocking the function to true.
TEST(FusaAppTh, Sample1) {
MockWrapper mockWrapper;
FusaTelltaleClientAppTh AppThObj(1, "abc", &mockWrapper);
ON_CALL(mockWrapper, wfdEnumerateDevices)
.WillByDefault(testing::Return(true));
EXPECT_EQ(1, AppThObj.tt_init_device());
}

// Tests mocking the function to false.
TEST(FusaAppTh, Sample2) {
MockWrapper mockWrapper;
FusaTelltaleClientAppTh AppThObj(1, "abc", &mockWrapper);
ON_CALL(mockWrapper, wfdEnumerateDevices)
.WillByDefault(testing::Return(false));
EXPECT_EQ(0, AppThObj.tt_init_device());
}

下面是一个活生生的例子:https://godbolt.org/z/vfbKf6oT8

最新更新