emock
emock copied to clipboard
同一个函数在目标被测函数中多次调用(会有不同结果)该如何mock?
如何在同一个用例中mock同一个函数多次,并且期望的行为每次都不同? 例如下面的示例:
class a {
public:
int aFunc(int i) {
// do something, return different value
// or read differen value from file...
}
};
class call {
public:
int call_aFunc(int x) {
int ret = 0;
if (x==y) {
ret = x * aobj.aFunc(x); // expect return 2
} else if (x%y==0) {
ret = x % aobj.aFunc(x); // expect return 10
rer += y*aobj.aFunc(y); // expect return 6
} else if (x/y) {
rer += y/aobj.aFunc(y); // expect return 8
} else {
rer += aobj.aFunc(x); // expect return 0
}
return rer += aobj.aFunc(ret); // expect return 666
}
a aobj;
int y;
};
mockcpp中有类似的语法: .stubs().will(returnValue(10)).then(returnValue(6)).then(returnVaule(666));
emock也支持类似的语法,但是实测then没效果,每次返回的都是will中设定的10.
系统:Linux x86_64,编译器:g++
连续调用目前没有限制,但是就和实际效果一致,单条约定中设置多个返回后续的不会生效,可以考虑以下方案:
方案一,用returnObjectList
will(returnObjectList(10, 6, 666))
方案二,用invoke
will(invoke(mock_func))
在mock_func
里控制返回的值
方案三,写成多条约定
EMOCK(xxx).expects(once()).will(returnValue(10));
EMOCK(xxx).expects(once()).will(returnValue(6));
EMOCK(xxx).expects(once()).will(returnVaule(666));
感谢大佬回复。我试试看