google mock - "function must be called ONCE with a certain parameter but ok to be called many times with different parameters" 怎么说?

google mock - how to say "function must be called ONCE with a certain parameter but ok to be called many times with different parameters"?

我需要检测给定函数是否已使用特定参数集被调用一次。

EXPECT_CALL(Mock_Obj, func("abc")).Times(1)

但是可以多次使用不同的参数调用该函数。

如何表达?

在Google Mock中,后面的期望覆盖前面的期望(更多细节在docs),所以你可以这样写:

EXPECT_CALL(Mock_Obj, func(_)).Times(AnyNumber());
EXPECT_CALL(Mock_Obj, func("abc")).Times(1);

这里有更多信息。做 。将默认值(最通用,因为它允许 any 参数带有 _ 字符)案例 first 和更具体的案例 after,如果它们首先匹配,则覆盖默认大小写。我说后者 EXPECT_CALL()s 可能匹配 first 因为 gmock 执行 reverse 搜索匹配项,这意味着它试图匹配 last EXPECT_CALL() first,然后向上移动,在first[=40处停止并退出该过程=] 以相反的顺序匹配它为呼叫找到的。

EXPECT_CALL(Mock_Obj, func(_)).Times(AnyNumber());
EXPECT_CALL(Mock_Obj, func("abc")).Times(1);
EXPECT_CALL(Mock_Obj, func("def")).Times(1);
EXPECT_CALL(Mock_Obj, func("cab")).Times(1);
EXPECT_CALL(Mock_Obj, func("bac")).Times(1);

来自"gMock for Dummies {#GMockForDummies}" guide:

Using Multiple Expectations {#MultiExpectations}

So far we've only shown examples where you have a single expectation. More realistically, you'll specify expectations on multiple mock methods which may be from multiple mock objects.

By default, when a mock method is invoked, gMock will search the expectations in the reverse order they are defined, and stop when an active expectation that matches the arguments is found (you can think of it as "newer rules override older ones."). If the matching expectation cannot take any more calls, you will get an upper-bound-violated failure. Here's an example:

using ::testing::_;
...
EXPECT_CALL(turtle, Forward(_));  // #1
EXPECT_CALL(turtle, Forward(10))  // #2
    .Times(2);

If Forward(10) is called three times in a row, the third time it will be an error, as the last matching expectation (#2) has been saturated. If, however, the third Forward(10) call is replaced by Forward(20), then it would be OK, as now #1 will be the matching expectation.

Note: Why does gMock search for a match in the reverse order of the expectations? The reason is that this allows a user to set up the default expectations in a mock object's constructor or the test fixture's set-up phase and then customize the mock by writing more specific expectations in the test body. So, if you have two expectations on the same method, you want to put the one with more specific matchers after the other, or the more specific rule would be shadowed by the more general one that comes after it.

Tip: It is very common to start with a catch-all expectation for a method and Times(AnyNumber()) (omitting arguments, or with _ for all arguments, if overloaded). This makes any calls to the method expected. This is not necessary for methods that are not mentioned at all (these are "uninteresting"), but is useful for methods that have some expectations, but for which other calls are ok. See Understanding Uninteresting vs Unexpected Calls.

相关: