我试图嘲笑一个模板方法。

下面是包含方法的类来模拟:

class myClass
{
public:
    virtual ~myClass() {}

    template<typename T>
    void myMethod(T param);
}

如何可以模拟该方法的MyMethod使用谷歌模拟?

有帮助吗?

解决方案

在以前版本的谷歌模拟的,你只能模拟虚函数,看到的文档在项目的页面。

的更近版本允许模拟非虚拟方法的,使用他们所说的 HI-PERF依赖注入

作为congusbongus状态:

  

谷歌模拟依赖于增加成员变量来支持方法嘲弄,因为你不能创建模板成员变量,这是不可能模仿的模板功能

在Google网上论坛一种解决方法,由迈克尔·哈灵顿从评论链接,就是让专业的模板方法,将调用可以嘲笑一个正常功能。它并没有解决一般情况下,但它会为测试工作。

struct Foo
{
    MOCK_METHOD1(GetValueString, void(std::string& value));

    template <typename ValueType>
    void GetValue(ValueType& value); 

    template <>
    void GetValue(std::string& value) {
        GetValueString(value);
    } 
};

其他提示

下面有意见,援助是原来的职位再次理解:

    struct Foo 
    { 
        // Our own mocked method that the templated call will end up calling.
        MOCK_METHOD3(GetNextValueStdString, void(const std::string& name, std::string& value, const unsigned int streamIndex)); 

        // If we see any calls with these two parameter list types throw and error as its unexpected in the unit under test.
        template< typename ValueType > 
        void GetNextValue( const std::string& name, ValueType& value, const unsigned int streamIndex ) 
        { 
            throw "Unexpected call."; 
        } 
        template< typename ValueType > 
        void GetNextValue( const std::string& name, ValueType& value ) 
        { 
            throw "Unexpected call."; 
        } 

        // These are the only two templated calls expected, notice the difference in the method parameter list. Anything outside
        // of these two flavors is considerd an error.
        template<> 
        void GetNextValue< std::string >( const std::string& name, std::string& value, const unsigned int streamIndex ) 
        { 
            GetNextValueStdString( name, value, streamIndex ); 
        } 
        template<> 
        void GetNextValue< std::string >( const std::string& name, std::string& value ) 
        { 
            GetNextValue< std::string >( name, value, 0 ); 
        } 
    }; 
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top