单元测试2-gmock及MOCK_METHOD学习

发布时间 2024-01-01 22:30:27作者: lypbendlf

转自:https://www.cnblogs.com/welkinwalker/archive/2011/11/29/2267225.html,https://www.cnblogs.com/pugang/p/9500352.html

1.介绍

#include <gmock/gmock.h>
#include <string>

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

public:
        virtual std::string getArbitraryString() = 0; //mock的函数必须是虚函数(gmock的局限性)
};

class MockFoo: public FooInterface {//需要继承已有的类
public:
        MOCK_METHOD0(getArbitraryString, std::string());//宏0表示mock的函数形参数量为0
};
//调用case:
    1. int main(int argc, char** argv) {
    2.         ::testing::InitGoogleMock(&argc, argv);
    3.  
    4.         string value = "Hello World!";
    5.         MockFoo mockFoo;
    6.         EXPECT_CALL(mockFoo, getArbitraryString()).Times(1).
    7.                 WillOnce(Return(value));
    8.         string returnValue = mockFoo.getArbitraryString();
    9.         cout << "Returned Value: " << returnValue << endl;
    10.  
    11.         return EXIT_SUCCESS;
    12. }

gmock 依赖C++多态机制进行工作,只有虚函数才能被mock, 非虚函数不能被mock。 派生类中的同名函数仍然是虚函数,同样支持多态,支持gomck。类实例以引用类型传入,不能mock相应的接口,以引用类型传入的成员变量本身不具备多态特性,因此gmock不支持。

EXPECT_CALL:

EXPECT_CALL(mock_object, method(matcher1, matcher2, ...))//mock对象,mock的方法
    .With(multi_argument_matcher)
    .Times(cardinality)//基数,运行几次,可选
    .InSequence(sequences)
    .After(expectations)
    .WillOnce(action)// 一次调用时所产生的行为
    .WillRepeatedly(action) // 缺省/重复行为。
    .RetiresOnSaturation();

例子:

EXPECT_CALL(mockTurtle, getX()).Times(testing::AtLeast(5)). //至少运行5次
                WillOnce(testing::Return(100)).WillOnce(testing::Return(150)).//第一次返回100,第二次返回150,之后3次返回200
                WillRepeatedly(testing::Return(200))

2.元素

2.1 matcher匹配器

官方链接:https://google.github.io/googletest/reference/matchers.html

期望传入的参数符合的条件,_表示任何值,不用检查。有些比较大小的函数等。//比较高阶的用法。

2.2 Actoins行为

2.3 序列Sequences 

直接定义一个对象,InSequence dummy;,执行时按照EXPECT_CALL声明的顺序来即可。

gmock还可以mock protected/private方法。

3. 运行

https://www.cnblogs.com/coderzh/archive/2009/04/10/1432789.html,链接中有系列文章,想进阶可以再学习

对于运行参数,gtest提供了三种设置的途径,优先级依次从低到高:

  • 1. 系统环境变量。--gtest_output对应的系统环境变量为:GTEST_OUTPUT
  • 2. 代码中指定FLAG。testing::GTEST_FLAG。
  • 3.命令行参数。因为在初始化时接收了命令行参数 testing::InitGoogleTest(&argc, argv); 
int _tmain(int argc, _TCHAR* argv[])
{
    testing::GTEST_FLAG(output) "xml:"; //指定flag,--gtest_output
    testing::InitGoogleTest(&argc, argv); //命令行参数优先级更高,--gtest_output
    return RUN_ALL_TESTS();
}

命令行参数:

  • --gtest_filter,支持通配符过滤执行