如何模拟 GTest 中模板 class 中的模板方法?

How to mock a template method that's in a template class in GTest?

我想在 google 测试中模拟 myFunction,但两个模板都存在问题。

template <class Outer>
class MyClass{
   template <class T>
   void myFunction(const int a, T * b);
};

首先,Outer 模板类型在这里不是问题,因为它没有在 myFunction 签名中使用。
要处理类型 T,您需要为测试期间使用的所有类型完全专门化模拟方法。
假设您想使用 T=std::string:

测试该方法
template <class Outer>
class MyClassMock {
public:
    MOCK_METHOD(void, myFunction, (const int, std::string*));

    template <class T>
    void myFunction(const int a, T* b);

    template <>
    void myFunction(const int a, std::string* b)
    {
        myFunction(a, b);
    }
};

如果您测试的函数具有这样的签名:

template <typename TMyClass>
void UseMyClassWithString(TMyClass& i_value)
{
    std::string t;
    i_value.myFunction(5, &t);
}

结果测试可能如下所示:

TEST(UseMyClass, ShouldCallMyFunction)
{
    MyClassMock<size_t> mock;
    EXPECT_CALL(mock, myFunction).Times(1);
    UseMyClassWithString(mock);
}

此处您的 Outer 类型是 size_t,它仅用于创建模拟对象。