GMOCK学习笔记-CheatSheet.md

GMOCK学习笔记-

说明:
1.GMOCK中的说明文档CheatSheet.md。
2.GMOCK基于多态实现,所以想要mock一个object,被mock的类必须有虚函数,可以在gmock的代码CheatSheet.md中看到这个说明

mock使用

mock一个普通的接口类

Given

class Foo {
  ...
  virtual ~Foo();
  virtual int GetSize() const = 0;
  virtual string Describe(const char* name) = 0;
  virtual string Describe(int type) = 0;
  virtual bool Process(Bar elem, int count) = 0;
};

(note that ~Foo() must be virtual) we can define its mock as
mock上面的类如下:

#include "gmock/gmock.h"
class MockFoo : public Foo {
  MOCK_CONST_METHOD0(GetSize, int());
  MOCK_METHOD1(Describe, string(const char* name));
  MOCK_METHOD1(Describe, string(int type));
  MOCK_METHOD2(Process, bool(Bar elem, int count));
};

mock一个模板

template <typename Elem>
class StackInterface {
 public:
  ...
  virtual ~StackInterface();
  virtual int GetSize() const = 0;
  virtual void Push(const Elem& x) = 0;
};

template <typename Elem>
class MockStack : public StackInterface<Elem> {
 public:
  ...
  MOCK_CONST_METHOD0_T(GetSize, int());
  MOCK_METHOD1_T(Push, void(const Elem& x));
};

在测试中使用mock

典型用法:
• Import gmock。gmock的各种变量名都在testing这个命名空间下,除非某些宏定义
• 创建mock对象
• 可选的操作是,设置mock对象的默认动作(怎么调用以及mock做了什么)
• 使用了这个mock对象的函数,check 结果
• 当mock对象析构的时候,gmock会自动的看所有基于它的期望值是不是正确

设置期望值

EXPECT_CALL对一个Mock的函数设置期望值(怎么被调用以及将做什么)

EXPECT_CALL(mock_object, method(matchers))
    .With(multi_argument_matcher)  ?
    .Times(cardinality)            ?
    .InSequence(sequences)         *
    .After(expectations)           *
    .WillOnce(action)              *
    .WillRepeatedly(action)        ?
    .RetiresOnSaturation();        ?
  • Times(1) when there is neither WillOnce() nor WillRepeatedly();
  • Times(n) when there are n WillOnce()s but no WillRepeatedly(), where n >= 1; or
  • Times(AtLeast(n)) when there are n WillOnce()s and a WillRepeatedly(), where n >= 0.

匹配器matcher

模糊匹配

EXPECT_THAT(value, matcher) 意思是指“value”匹配“matcher”
_标识任何值

一般匹配

Eq(value) or valueargument == value
Ge(value)argument >= value
Gt(value)argument > value
Le(value)argument <= value
Lt(value)argument < value
Ne(value)argument != value
IsNull()argument is a NULL pointer (raw or smart).
NotNull()argument is a non-null pointer (raw or smart).
VariantWith<T>(m)argument is variant<> that holds the alternative of
type T with a value matching m.
Ref(variable)argument is a reference to variable.
TypedEq<type>(value)argument has type type and is equal to value. You may need to use this instead of Eq(value) when the mock function is overloaded.

除了引用Ref(variable)之外,其他的匹配器mather都是copy了“value”防止value被修改或者销毁。如果“value”没有Public的拷贝构造,可以给mather包一层ByRef(),比如
Eq(ByRef(non_copyable_value))

float matcher

DoubleEq(a_double)argument is a double value approximately equal to a_double, treating two NaNs as unequal.
FloatEq(a_float)argument is a float value approximately equal to a_float, treating two NaNs as unequal.
NanSensitiveDoubleEq(a_double)argument is a double value approximately equal to a_double, treating two NaNs as equal.
NanSensitiveFloatEq(a_float)argument is a float value approximately equal to a_float, treating two NaNs as equal.

String Matchers

matcher中的argument可以是c string或者是c++ string object

ContainsRegex(string)argument matches the given regular expression.
EndsWith(suffix)argument ends with string suffix.
HasSubstr(string)argument contains string as a sub-string.
MatchesRegex(string)argument matches the given regular expression with the match starting at the first character and ending at the last character.
StartsWith(prefix)argument starts with string prefix.
StrCaseEq(string)argument is equal to string, ignoring case.
StrCaseNe(string)argument is not equal to string, ignoring case.
StrEq(string)argument is equal to string.
StrNe(string)argument is not equal to string.

ContainsRegex() and MatchesRegex() use the regular expression

Container Matchers

大部分SLT的容器实现了==,所以可以简单的是使用
Eq(expected_container) or simply expected_container 精确的匹配一个容器
另外还有

ContainerEq(container)The same as Eq(container) except that the failure message also includes which elements are in one container but not the other.
Contains(e)argument contains an element that matches e, which can be either a value or a matcher.
Each(e)argument is a container where every element matches e, which can be either a value or a matcher.
ElementsAre(e0, e1, ..., en)argument has n + 1 elements, where the i-th element matches ei, which can be a value or a matcher. 0 to 10 arguments are allowed.
ElementsAreArray({ e0, e1, ..., en }), ElementsAreArray(array), or ElementsAreArray(array, count)The same as ElementsAre() except that the expected element values/matchers come from an initializer list, STL-style container, or C-style array.
IsEmpty()argument is an empty container (container.empty()).
Pointwise(m, container)argument contains the same number of elements as in container, and for all i, (the i-th element in argument, the i-th element in container) match m, which is a matcher on 2-tuples. E.g. Pointwise(Le(), upper_bounds) verifies that each element in argument doesn’t exceed the corresponding element in upper_bounds. See more detail below.
SizeIs(m)argument is a container whose size matches m. E.g. SizeIs(2) or SizeIs(Lt(2)).
UnorderedElementsAre(e0, e1, ..., en)argument has n + 1 elements, and under some permutation each element matches an ei (for a different i), which can be a value or a matcher. 0 to 10 arguments are allowed.
UnorderedElementsAreArray({ e0, e1, ..., en }), UnorderedElementsAreArray(array), or UnorderedElementsAreArray(array, count)The same as UnorderedElementsAre() except that the expected element values/matchers come from an initializer list, STL-style container, or C-style array.
WhenSorted(m)When argument is sorted using the < operator, it matches container matcher m. E.g. WhenSorted(ElementsAre(1, 2, 3)) verifies that argument contains elements 1, 2, and 3, ignoring order.
WhenSortedBy(comparator, m)The same as WhenSorted(m), except that the given comparator instead of < is used to sort argument. E.g. WhenSortedBy(std::greater<int>(), ElementsAre(3, 2, 1)).

类成员 Matchers

Field(&class::field, m)argument.field (or argument->field when argument is a plain pointer) matches matcher m, where argument is an object of type class.
Key(e)argument.first matches e, which can be either a value or a matcher. E.g. Contains(Key(Le(5))) can verify that a map contains a key <= 5.

等等一系列matcher

action

说明了当一个mock的function被调用时的动作

return值

Return()Return from a void mock function.
Return(value)Return value. If the type of value is different to the mock function’s return type, value is converted to the latter type at the time the expectation is set, not when the action is executed.
ReturnArg<N>()Return the N-th (0-based) argument.
ReturnNew<T>(a1, ..., ak)Return new T(a1, ..., ak); a different object is created each time.
ReturnNull()Return a null pointer.
ReturnPointee(ptr)Return the value pointed to by ptr.
ReturnRef(variable)Return a reference to variable.
ReturnRefOfCopy(value)Return a reference to a copy of value; the copy lives as long as the action.

side effects 副作用 可能翻译不太准确

Assign(&variable, value)Assign value to variable.
DeleteArg<N>()Delete the N-th (0-based) argument, which must be a pointer.
SaveArg<N>(pointer)Save the N-th (0-based) argument to *pointer.
SaveArgPointee<N>(pointer)Save the value pointed to by the N-th (0-based) argument to *pointer.
SetArgReferee<N>(value)Assign value to the variable referenced by the N-th (0-based) argument.
SetArgPointee<N>(value)Assign value to the variable pointed by the N-th (0-based) argument.
SetArgumentPointee<N>(value)Same as SetArgPointee<N>(value). Deprecated. Will be removed in v1.7.0.
SetArrayArgument<N>(first, last)Copies the elements in source range [first, last) to the array pointed to by the N-th (0-based) argument, which can be either a pointer or an iterator. The action does not take ownership of the elements in the source range.
SetErrnoAndReturn(error, value)Set errno to error and return value.
Throw(exception)Throws the given exception, which can be any copyable value. Available since v1.1.0.

调用另外一个函数或者仿函数作为一个动作

Invoke(f)Invoke f with the arguments passed to the mock function, where f can be a global/static function or a functor.
Invoke(object_pointer, &class::method)Invoke the {method on the object with the arguments passed to the mock function.
InvokeWithoutArgs(f)Invoke f, which can be a global/static function or a functor. f must take no arguments.
InvokeWithoutArgs(object_pointer, &class::method)Invoke the method on the object, which takes no arguments.
InvokeArgument<N>(arg1, arg2, ..., argk)Invoke the mock function’s N-th (0-based) argument, which must be a function or a functor, with the k arguments.

基数

在Times中使用,指明了这个mock的funciton会被调用多少次

AnyNumber()The function can be called any number of times.
AtLeast(n)The call is expected at least n times.
AtMost(n)The call is expected at most n times.
Between(m, n)The call is expected between m and n (inclusive) times.
Exactly(n) or nThe call is expected exactly n times. In particular, the call should never happen when n is 0.

验证和reset一个mock

可以等到gmock的对象析构的时候,或者可以早点做:
using ::testing::Mock;

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值