我正在使用 C++ 中的 GMock/Gtest 编写单元测试。我无法模拟命名空间中的方法。例如:namespace::method_name()
在被调用的函数中。
示例代码:
TestClass.cc. // Unit test class
TEST(testFixture, testMethod) {
MockClass mock;
EXPECT_CALL(mock, func1(_));
mock.helloWorld();
}
MockClass.cc // Mock class
class MockClass{
MOCK_METHOD1(func1, bool(string));
}
HelloWorld.cc // Main class
void helloWorld() {
string str;
if (corona::func1(str)) { -> function to be mocked
// Actions
}
}
在上面
helloWorld
方法,corona::func1(str)
无法使用上述模拟函数进行调用。尝试的步骤:
EXPECT_CALL(mock, corona::func1(_));
-> 编译失败。 MOCK_METHOD1(corona::func1, bool(string));
-> 编译失败 我被困在这一点上,无法对
helloWorld
进行单元测试方法。实际的源代码更复杂。我怎么能这样做?
最佳答案
你不能模拟自由函数,你必须创建接口(interface):
struct Interface
{
virtual ~Interface() = default;
virtual bool func1(const std::string&) = 0;
};
struct Implementation : Interface
{
bool func1(const std::string& s) override { corona::func1(s); }
};
void helloWorld(Interface& interface) {
string str;
if (interface.func1(str)) { // -> function to be mocked
// Actions
}
}
// Possibly, helper for production
void helloWorld()
{
Implementation impl;
helloWorld(impl);
}
并测试:
class MockClass : public Interface {
MOCK_METHOD1(func1, bool(string));
};
TEST(testFixture, testMethod) {
MockClass mock;
EXPECT_CALL(mock, func1(_));
helloWorld(mock);
}
关于c++ - 使用 GMock 的具有命名空间的模拟方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61942572/