【学习】白盒测试例中使用mocker打桩

2024-02-07  本文已影响0人  papi_k的小茅屋

mocker工具的作用是指定函数的行为(模拟函数的行为)。可以对入参进行校验,对出参进行设定,还可以指定函数的返回值。
mock规范:每个MOCKER(function)开始,跟一系列的.stubs、.with、.will等的内容体,称为一个mock规范。
核心关键字:.stubs().expects() .with().will().returnValue()outBoundP()any()eq().

其中
.stubs()用来表示函数的调用次数为不限。例如:

MOCKER(func)
    .stubs()   //不限制func函数的调用次数
    .with(any())
    .will(returnValue(0))

.expects()关键字对函数的调用次数进行限定,例如:

MOCKER(func)
    .expects(once())   //限制函数调用次数为1次
    .with(any())
    .will(returnValue(0))

.with()指定函数的约束条件

.will()指定函数的返回值


主要使用场景

1.使用白盒测试某接口,如果只检查该接口的返回值可能会有点单薄。可以考虑深入一些,通过MOCKER方式,期望一定会调到该接口的某个更底层一些的函数。
如果这个“某接口”有返回值,可以写为 MOCKER(某底层接口).expects(once()).will(returnValue(1))
如果不关心接口返回值,可以写成:MOCKER(某底层接口).expects(once()).will(ignoreReturnValue())

2.outboundP用法,设置出参值
例1,

int function1(int *a, int *b)
{
    //...
}
int value = 10;
MOCKER(function1).stubs().with(any(), outBoundP(&value, sizeof(int)), any()).will(returnValue(0));

作用:对function1接口的第1个入参设置参数值为10.

例如2,

int function2(int *a, int *b, int *c, int d)
{
    //...
}
MOCKER(function2)
    .stubs()
    .with(any(), any(), outBoundP(&value, sizeof(value)), eq(10)) 
    .will(returnValue(0));

该例子表示对function2函数的第1、2个入参不做限制,第3个输出参数必须为value,第4个入参约束为10。will()和returnValue()表示对func返回值的约束,此处约束返回值必须为0。
注:outBoundP尽量不要使用数组,容易出现编译错误

复杂一点的用法:

MOCKER(func).expects(atLeast(1)).with(any(), outBoundP(&inputInfo, sizeof(inputInfo结构体)), any()).after("first").will(returnValue(0));

这里多了一个atLeast(1),after的用户,前者表示func要至少被调用一次;后者的用法往往伴随着一个id使用,例如对某个接口调用过两次,但两次的入参不一样,可以考虑这么用:

int func(int a, int b)
{
    // ...
}
int a = 1;
int b = 2;
// 第一次调用时,设置id
MOCKER(func)
    .expects(once()) 
    .with(any(), eq(a)) // 指定入参为a
    .will(returnValue(0))
    .id("first") // 自定义id的字符串first

// 第二次调用时,设置after
MOCKER(func)
    .expects(once()) 
    .with(any(), eq(b)) // 指定入参为b
    .after("first")
    .will(returnValue(0))

3.打桩替换一个接口。

MOCKER(func1).stubs().will(invoke(func2)); // 接口func2是自定义的一个接口

4.checkwith 进行定制化的入参检查

MOCKER(func1)
    .expects(once())
    .with(any(), checkWith(func2), any())
    .will(returnValue(1));

其中with()中的checkWith在第二个位置,表示对func1的第二个入参进行校验。
其中接口func2为自定义,例如判断flag的数值是否为0:

bool func2(结构体struct *key)
{
    return key->flag == 0;
}

5.使用eq() neq() gt() lt() 与输入参数直接比较。
例如:

int plus4(int a, int b, int c , int d)
{
    return xxx;
}

MOCKER(plus4)
    .stubs()
    .with(eq(1), neq(2), gt(3), lt(4))
    .will(returnValue(-1));

对接口plus4打桩,当入参分别为 等于1,不等于2,大于3,小于4时,满足这个条件则直接返回error(-1)。


yo peace!

上一篇 下一篇

猜你喜欢

热点阅读