使用 GMock 的具有命名空间的模拟方法
Mock method with namespace using GMock
我正在使用 GMock/Gtest 编写单元测试C++。我无法模拟命名空间中的方法。例如: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
方法进行单元测试。实际的源代码更为复杂。我该怎么做?
你不能模拟自由函数,你必须创建接口:
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);
}
相关文章:
- 有什么好的方法可以让系统调用代理允许在单元测试中进行模拟
- 使用 GMock 的具有命名空间的模拟方法
- 确保模拟的 GTest 方法覆盖虚拟方法
- C++ 谷歌模拟/单元测试:模拟方法未调用,原始方法是
- 如何模拟C++中使用GMock返回特定值的方法(非虚拟)
- 模拟 - 方法和工具
- 为什么在我的代码中没有调用 g 模拟方法
- 对于 gtest,如何模拟具有相同名称但不同类型的方法
- 如何测试基类中的方法是否已使用谷歌模拟调用和执行?
- 模拟返回具有多个用户定义转换的类型的方法
- 使用 gmock 返回模拟方法参数
- 不是虚拟的模拟方法
- 我如何验证2种模拟方法以相同的参考调用
- gmock-模拟对象及其内部模拟方法
- gmock - 测试模拟方法参数
- 如何对传递给模拟方法的对象调用方法
- 如何模拟方法模板的虚拟性
- 如何用指针参数模拟方法
- 如何在Google mock中使用可选参数模拟方法
- 自动生成谷歌模拟方法