我有一个模拟对象设置,如下所示:
MyObject obj;
EXPECT_CALL(obj, myFunction(_))
.WillOnce(Return(1))
.WillOnce(Return(1))
.WillOnce(Return(1))
.WillRepeatedly(Return(-1));
有没有办法不必重复.WillOnce(Return(1))
三次?
答案 0 :(得分:26)
using testing::InSequence;
MyObject obj;
{
InSequence s;
EXPECT_CALL(obj, myFunction(_))
.Times(3)
.WillRepeatedly(Return(1));
EXPECT_CALL(obj, myFunction(_))
.WillRepeatedly(Return(-1));
}
答案 1 :(得分:2)
为了完整性'此外,还有另一种标准/简单的选择,尽管在这种情况下接受的答案似乎更清楚。
EXPECT_CALL(obj, myFunction(_)).WillRepeatedly(Return(-1));
EXPECT_CALL(obj, myFunction(_)).Times(3).WillRepeatedly(Return(1)).RetiresOnSaturation();
如果你知道你的上一个/默认响应是什么(-1
),但想要知道它之前被调用的次数,那么这可能很有用。
答案 2 :(得分:1)
我担心没有其他方法可以配置此行为。至少在文档中找不到明显的方法。
你可能会引入一个适当的user defined matcher来解决这个问题,它可以跟踪你可以通过模板参数从测试用例中提供的调用计数和阈值(实际上并不知道如何诱导{ {1}}自动:-():
ResultType
然后使用,以期望一个肯定计算的通话结果:
using ::testing::MakeMatcher;
using ::testing::Matcher;
using ::testing::MatcherInterface;
using ::testing::MatchResultListener;
template
< unsigned int CallThreshold
, typename ResultType
, ResultType LowerRetValue
, ResultType HigherRetValue
>
class MyCountingReturnMatcher
: public MatcherInterface<ResultType>
{
public:
MyCountingReturnMatcher()
: callCount(0)
{
}
virtual bool MatchAndExplain
( ResultType n
, MatchResultListener* listener
) const
{
++callCount;
if(callCount <= CallThreshold)
{
return n == LowerRetValue;
}
return n == HigherRetValue;
}
virtual void DescribeTo(::std::ostream* os) const
{
if(callCount <= CallThreshold)
{
*os << "returned " << LowerRetValue;
}
else
{
*os << "returned " << HigherRetValue;
}
}
virtual void DescribeNegationTo(::std::ostream* os) const
{
*os << " didn't return expected value ";
if(callCount <= CallThreshold)
{
*os << "didn't return expected " << LowerRetValue
<< " at call #" << callCount;
}
else
{
*os << "didn't return expected " << HigherRetValue
<< " at call #" << callCount;
}
}
private:
unsigned int callCount;
};
template
< unsigned int CallThreshold
, typename ResultType
, ResultType LowerRetValue
, ResultType HigherRetValue
>
inline Matcher<ResultType> MyCountingReturnMatcher()
{
return MakeMatcher
( new MyCountingReturnMatcher
< ResultType
, CallThreshold
, ResultType
, LowerRetValue
, HigherRetValue
>()
);
}
注意强>
我没有检查此代码是否按预期工作,但它应该引导您进入正确的方向。