美文网首页
Gtest和Gmock使用指南 (7) - 桩掉C++类

Gtest和Gmock使用指南 (7) - 桩掉C++类

作者: louyang | 来源:发表于2021-01-04 11:04 被阅读0次

    有被测函数如下,该函数使用了一个接口类。我们测试的时候,这个接口类的实现是要用gmock打桩打掉的。

    int FuncToBeTested(SomeInterface & if, std::string & param) {
        return if.some_func(param) == true ? 1 : -1;
    }
    

    接口类的定义如下:

    class SomeInterface {
    public:
        virtual bool some_func(std::string & some_param) = 0;
    };
    

    使用Gmock桩掉这个接口类的实现:

    class MockInterfaceImpl : public SomeInterface {
    public:
        MOCK_METHOD1(some_func, bool(std::string & param));
    };
    

    MOCK_METHOD1中的1表示桩掉的函数只有一个入参。

    完整的示例代码如下:

    $ cat Test.cpp 
    #include <iostream>
    #include <gtest/gtest.h>
    #include <gmock/gmock.h>
    
    class SomeInterface {
    public:
        virtual bool some_func(std::string & param) = 0;
    };
    
    class MockInterfaceImpl : public SomeInterface {
    public:
        MOCK_METHOD1(some_func, bool(std::string & param));
    };
    
    int FuncToBeTested(SomeInterface & interface, std::string param) {
        return interface.some_func(param) == true ? 1 : -1;
    }
    
    TEST(TestSuiteName, TestCaseName) {
        MockInterfaceImpl mock_if_impl;
        EXPECT_CALL(mock_if_impl, some_func)
        .Times(::testing::AtLeast(1))
        .WillOnce(::testing::Return(true));
    
        int ret_value = FuncToBeTested(mock_if_impl, "SomeString");
    
        EXPECT_EQ(ret_value, 1);
    }
    
    $ g++ Test.cpp -l gtest -l gtest_main -l gmock -l pthread && ./a.out
    

    相关文章

      网友评论

          本文标题:Gtest和Gmock使用指南 (7) - 桩掉C++类

          本文链接:https://www.haomeiwen.com/subject/fkcynktx.html