代码之家  ›  专栏  ›  技术社区  ›  Xavier V.

如何使用Google Mock模拟模板化方法?

  •  15
  • Xavier V.  · 技术社区  · 16 年前

    我在模仿一个模板化的方法。

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

    class myClass
    {
    public:
        virtual ~myClass() {}
    
        template<typename T>
        void myMethod(T param);
    }
    

    我怎样才能用谷歌模拟来模拟我的方法呢?

    2 回复  |  直到 7 年前
        1
  •  8
  •   Ismael    10 年前

    在Google Mock的早期版本中,您只能模拟虚拟函数,请参见 documentation 在项目页面中。

    允许模拟的最新版本 non-virtual methods ,使用他们所说的 高性能依赖注入 .

    AS congusbongus 国家:

    google mock依赖于添加成员变量来支持方法mocking,并且由于不能创建模板成员变量,所以不可能模拟模板函数。

    由MichaelHarrington在GoogleGroups的评论链接中提出的一个解决方法是专门化模板方法,该方法将调用可模拟的正常函数。它不能解决一般情况,但可以用于测试。

    struct Foo
    {
        MOCK_METHOD1(GetValueString, void(std::string& value));
    
        template <typename ValueType>
        void GetValue(ValueType& value); 
    
        template <>
        void GetValue(std::string& value) {
            GetValueString(value);
        } 
    };
    
        2
  •  0
  •   Chris    7 年前

    这是原版的帖子,还有一些有助于理解的评论:

        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 ); 
            } 
        };