Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
freebsd
GitHub Repository: freebsd/freebsd-src
Path: blob/main/contrib/googletest/googlemock/test/gmock-spec-builders_test.cc
109682 views
1
// Copyright 2007, Google Inc.
2
// All rights reserved.
3
//
4
// Redistribution and use in source and binary forms, with or without
5
// modification, are permitted provided that the following conditions are
6
// met:
7
//
8
// * Redistributions of source code must retain the above copyright
9
// notice, this list of conditions and the following disclaimer.
10
// * Redistributions in binary form must reproduce the above
11
// copyright notice, this list of conditions and the following disclaimer
12
// in the documentation and/or other materials provided with the
13
// distribution.
14
// * Neither the name of Google Inc. nor the names of its
15
// contributors may be used to endorse or promote products derived from
16
// this software without specific prior written permission.
17
//
18
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29
30
// Google Mock - a framework for writing C++ mock classes.
31
//
32
// This file tests the spec builder syntax.
33
34
#include "gmock/gmock-spec-builders.h"
35
36
#include <memory>
37
#include <ostream> // NOLINT
38
#include <sstream>
39
#include <string>
40
#include <type_traits>
41
42
#include "gmock/gmock.h"
43
#include "gmock/internal/gmock-port.h"
44
#include "gtest/gtest-spi.h"
45
#include "gtest/gtest.h"
46
#include "gtest/internal/gtest-port.h"
47
48
namespace testing {
49
namespace {
50
51
using ::testing::internal::FormatFileLocation;
52
using ::testing::internal::kAllow;
53
using ::testing::internal::kErrorVerbosity;
54
using ::testing::internal::kFail;
55
using ::testing::internal::kInfoVerbosity;
56
using ::testing::internal::kWarn;
57
using ::testing::internal::kWarningVerbosity;
58
59
#if GTEST_HAS_STREAM_REDIRECTION
60
using ::testing::internal::CaptureStdout;
61
using ::testing::internal::GetCapturedStdout;
62
#endif
63
64
class Incomplete {
65
};
66
67
class MockIncomplete {
68
public:
69
// This line verifies that a mock method can take a by-reference
70
// argument of an incomplete type.
71
MOCK_METHOD1(ByRefFunc, void(const Incomplete& x));
72
};
73
74
// Tells Google Mock how to print a value of type Incomplete.
75
void PrintTo(const Incomplete& x, ::std::ostream* os);
76
77
TEST(MockMethodTest, CanInstantiateWithIncompleteArgType) {
78
// Even though this mock class contains a mock method that takes
79
// by-reference an argument whose type is incomplete, we can still
80
// use the mock, as long as Google Mock knows how to print the
81
// argument.
82
MockIncomplete incomplete;
83
EXPECT_CALL(incomplete, ByRefFunc(_)).Times(AnyNumber());
84
}
85
86
// The definition of the printer for the argument type doesn't have to
87
// be visible where the mock is used.
88
void PrintTo(const Incomplete& /* x */, ::std::ostream* os) {
89
*os << "incomplete";
90
}
91
92
class Result {};
93
94
// A type that's not default constructible.
95
class NonDefaultConstructible {
96
public:
97
explicit NonDefaultConstructible(int /* dummy */) {}
98
};
99
100
class MockA {
101
public:
102
MockA() = default;
103
104
MOCK_METHOD1(DoA, void(int n));
105
MOCK_METHOD1(ReturnResult, Result(int n));
106
MOCK_METHOD0(ReturnNonDefaultConstructible, NonDefaultConstructible());
107
MOCK_METHOD2(Binary, bool(int x, int y));
108
MOCK_METHOD2(ReturnInt, int(int x, int y));
109
110
private:
111
MockA(const MockA&) = delete;
112
MockA& operator=(const MockA&) = delete;
113
};
114
115
class MockB {
116
public:
117
MockB() = default;
118
119
MOCK_CONST_METHOD0(DoB, int()); // NOLINT
120
MOCK_METHOD1(DoB, int(int n)); // NOLINT
121
122
private:
123
MockB(const MockB&) = delete;
124
MockB& operator=(const MockB&) = delete;
125
};
126
127
class ReferenceHoldingMock {
128
public:
129
ReferenceHoldingMock() = default;
130
131
MOCK_METHOD1(AcceptReference, void(std::shared_ptr<MockA>*));
132
133
private:
134
ReferenceHoldingMock(const ReferenceHoldingMock&) = delete;
135
ReferenceHoldingMock& operator=(const ReferenceHoldingMock&) = delete;
136
};
137
138
// Tests that EXPECT_CALL and ON_CALL compile in a presence of macro
139
// redefining a mock method name. This could happen, for example, when
140
// the tested code #includes Win32 API headers which define many APIs
141
// as macros, e.g. #define TextOut TextOutW.
142
143
#define Method MethodW
144
145
class CC {
146
public:
147
virtual ~CC() = default;
148
virtual int Method() = 0;
149
};
150
class MockCC : public CC {
151
public:
152
MockCC() = default;
153
154
MOCK_METHOD0(Method, int());
155
156
private:
157
MockCC(const MockCC&) = delete;
158
MockCC& operator=(const MockCC&) = delete;
159
};
160
161
// Tests that a method with expanded name compiles.
162
TEST(OnCallSyntaxTest, CompilesWithMethodNameExpandedFromMacro) {
163
MockCC cc;
164
ON_CALL(cc, Method());
165
}
166
167
// Tests that the method with expanded name not only compiles but runs
168
// and returns a correct value, too.
169
TEST(OnCallSyntaxTest, WorksWithMethodNameExpandedFromMacro) {
170
MockCC cc;
171
ON_CALL(cc, Method()).WillByDefault(Return(42));
172
EXPECT_EQ(42, cc.Method());
173
}
174
175
// Tests that a method with expanded name compiles.
176
TEST(ExpectCallSyntaxTest, CompilesWithMethodNameExpandedFromMacro) {
177
MockCC cc;
178
EXPECT_CALL(cc, Method());
179
cc.Method();
180
}
181
182
// Tests that it works, too.
183
TEST(ExpectCallSyntaxTest, WorksWithMethodNameExpandedFromMacro) {
184
MockCC cc;
185
EXPECT_CALL(cc, Method()).WillOnce(Return(42));
186
EXPECT_EQ(42, cc.Method());
187
}
188
189
#undef Method // Done with macro redefinition tests.
190
191
// Tests that ON_CALL evaluates its arguments exactly once as promised
192
// by Google Mock.
193
TEST(OnCallSyntaxTest, EvaluatesFirstArgumentOnce) {
194
MockA a;
195
MockA* pa = &a;
196
197
ON_CALL(*pa++, DoA(_));
198
EXPECT_EQ(&a + 1, pa);
199
}
200
201
TEST(OnCallSyntaxTest, EvaluatesSecondArgumentOnce) {
202
MockA a;
203
int n = 0;
204
205
ON_CALL(a, DoA(n++));
206
EXPECT_EQ(1, n);
207
}
208
209
// Tests that the syntax of ON_CALL() is enforced at run time.
210
211
TEST(OnCallSyntaxTest, WithIsOptional) {
212
MockA a;
213
214
ON_CALL(a, DoA(5)).WillByDefault(Return());
215
ON_CALL(a, DoA(_)).With(_).WillByDefault(Return());
216
}
217
218
TEST(OnCallSyntaxTest, WithCanAppearAtMostOnce) {
219
MockA a;
220
221
EXPECT_NONFATAL_FAILURE(
222
{ // NOLINT
223
ON_CALL(a, ReturnResult(_))
224
.With(_)
225
.With(_)
226
.WillByDefault(Return(Result()));
227
},
228
".With() cannot appear more than once in an ON_CALL()");
229
}
230
231
TEST(OnCallSyntaxTest, WillByDefaultIsMandatory) {
232
MockA a;
233
234
EXPECT_DEATH_IF_SUPPORTED(
235
{
236
ON_CALL(a, DoA(5));
237
a.DoA(5);
238
},
239
"");
240
}
241
242
TEST(OnCallSyntaxTest, WillByDefaultCanAppearAtMostOnce) {
243
MockA a;
244
245
EXPECT_NONFATAL_FAILURE(
246
{ // NOLINT
247
ON_CALL(a, DoA(5)).WillByDefault(Return()).WillByDefault(Return());
248
},
249
".WillByDefault() must appear exactly once in an ON_CALL()");
250
}
251
252
// Tests that EXPECT_CALL evaluates its arguments exactly once as
253
// promised by Google Mock.
254
TEST(ExpectCallSyntaxTest, EvaluatesFirstArgumentOnce) {
255
MockA a;
256
MockA* pa = &a;
257
258
EXPECT_CALL(*pa++, DoA(_));
259
a.DoA(0);
260
EXPECT_EQ(&a + 1, pa);
261
}
262
263
TEST(ExpectCallSyntaxTest, EvaluatesSecondArgumentOnce) {
264
MockA a;
265
int n = 0;
266
267
EXPECT_CALL(a, DoA(n++));
268
a.DoA(0);
269
EXPECT_EQ(1, n);
270
}
271
272
// Tests that the syntax of EXPECT_CALL() is enforced at run time.
273
274
TEST(ExpectCallSyntaxTest, WithIsOptional) {
275
MockA a;
276
277
EXPECT_CALL(a, DoA(5)).Times(0);
278
EXPECT_CALL(a, DoA(6)).With(_).Times(0);
279
}
280
281
TEST(ExpectCallSyntaxTest, WithCanAppearAtMostOnce) {
282
MockA a;
283
284
EXPECT_NONFATAL_FAILURE(
285
{ // NOLINT
286
EXPECT_CALL(a, DoA(6)).With(_).With(_);
287
},
288
".With() cannot appear more than once in an EXPECT_CALL()");
289
290
a.DoA(6);
291
}
292
293
TEST(ExpectCallSyntaxTest, WithMustBeFirstClause) {
294
MockA a;
295
296
EXPECT_NONFATAL_FAILURE(
297
{ // NOLINT
298
EXPECT_CALL(a, DoA(1)).Times(1).With(_);
299
},
300
".With() must be the first clause in an EXPECT_CALL()");
301
302
a.DoA(1);
303
304
EXPECT_NONFATAL_FAILURE(
305
{ // NOLINT
306
EXPECT_CALL(a, DoA(2)).WillOnce(Return()).With(_);
307
},
308
".With() must be the first clause in an EXPECT_CALL()");
309
310
a.DoA(2);
311
}
312
313
TEST(ExpectCallSyntaxTest, TimesCanBeInferred) {
314
MockA a;
315
316
EXPECT_CALL(a, DoA(1)).WillOnce(Return());
317
318
EXPECT_CALL(a, DoA(2)).WillOnce(Return()).WillRepeatedly(Return());
319
320
a.DoA(1);
321
a.DoA(2);
322
a.DoA(2);
323
}
324
325
TEST(ExpectCallSyntaxTest, TimesCanAppearAtMostOnce) {
326
MockA a;
327
328
EXPECT_NONFATAL_FAILURE(
329
{ // NOLINT
330
EXPECT_CALL(a, DoA(1)).Times(1).Times(2);
331
},
332
".Times() cannot appear more than once in an EXPECT_CALL()");
333
334
a.DoA(1);
335
a.DoA(1);
336
}
337
338
TEST(ExpectCallSyntaxTest, TimesMustBeBeforeInSequence) {
339
MockA a;
340
Sequence s;
341
342
EXPECT_NONFATAL_FAILURE(
343
{ // NOLINT
344
EXPECT_CALL(a, DoA(1)).InSequence(s).Times(1);
345
},
346
".Times() may only appear *before* ");
347
348
a.DoA(1);
349
}
350
351
TEST(ExpectCallSyntaxTest, InSequenceIsOptional) {
352
MockA a;
353
Sequence s;
354
355
EXPECT_CALL(a, DoA(1));
356
EXPECT_CALL(a, DoA(2)).InSequence(s);
357
358
a.DoA(1);
359
a.DoA(2);
360
}
361
362
TEST(ExpectCallSyntaxTest, InSequenceCanAppearMultipleTimes) {
363
MockA a;
364
Sequence s1, s2;
365
366
EXPECT_CALL(a, DoA(1)).InSequence(s1, s2).InSequence(s1);
367
368
a.DoA(1);
369
}
370
371
TEST(ExpectCallSyntaxTest, InSequenceMustBeBeforeAfter) {
372
MockA a;
373
Sequence s;
374
375
Expectation e = EXPECT_CALL(a, DoA(1)).Times(AnyNumber());
376
EXPECT_NONFATAL_FAILURE(
377
{ // NOLINT
378
EXPECT_CALL(a, DoA(2)).After(e).InSequence(s);
379
},
380
".InSequence() cannot appear after ");
381
382
a.DoA(2);
383
}
384
385
TEST(ExpectCallSyntaxTest, InSequenceMustBeBeforeWillOnce) {
386
MockA a;
387
Sequence s;
388
389
EXPECT_NONFATAL_FAILURE(
390
{ // NOLINT
391
EXPECT_CALL(a, DoA(1)).WillOnce(Return()).InSequence(s);
392
},
393
".InSequence() cannot appear after ");
394
395
a.DoA(1);
396
}
397
398
TEST(ExpectCallSyntaxTest, AfterMustBeBeforeWillOnce) {
399
MockA a;
400
401
Expectation e = EXPECT_CALL(a, DoA(1));
402
EXPECT_NONFATAL_FAILURE(
403
{ EXPECT_CALL(a, DoA(2)).WillOnce(Return()).After(e); },
404
".After() cannot appear after ");
405
406
a.DoA(1);
407
a.DoA(2);
408
}
409
410
TEST(ExpectCallSyntaxTest, WillIsOptional) {
411
MockA a;
412
413
EXPECT_CALL(a, DoA(1));
414
EXPECT_CALL(a, DoA(2)).WillOnce(Return());
415
416
a.DoA(1);
417
a.DoA(2);
418
}
419
420
TEST(ExpectCallSyntaxTest, WillCanAppearMultipleTimes) {
421
MockA a;
422
423
EXPECT_CALL(a, DoA(1))
424
.Times(AnyNumber())
425
.WillOnce(Return())
426
.WillOnce(Return())
427
.WillOnce(Return());
428
}
429
430
TEST(ExpectCallSyntaxTest, WillMustBeBeforeWillRepeatedly) {
431
MockA a;
432
433
EXPECT_NONFATAL_FAILURE(
434
{ // NOLINT
435
EXPECT_CALL(a, DoA(1)).WillRepeatedly(Return()).WillOnce(Return());
436
},
437
".WillOnce() cannot appear after ");
438
439
a.DoA(1);
440
}
441
442
TEST(ExpectCallSyntaxTest, WillRepeatedlyIsOptional) {
443
MockA a;
444
445
EXPECT_CALL(a, DoA(1)).WillOnce(Return());
446
EXPECT_CALL(a, DoA(2)).WillOnce(Return()).WillRepeatedly(Return());
447
448
a.DoA(1);
449
a.DoA(2);
450
a.DoA(2);
451
}
452
453
TEST(ExpectCallSyntaxTest, WillRepeatedlyCannotAppearMultipleTimes) {
454
MockA a;
455
456
EXPECT_NONFATAL_FAILURE(
457
{ // NOLINT
458
EXPECT_CALL(a, DoA(1)).WillRepeatedly(Return()).WillRepeatedly(
459
Return());
460
},
461
".WillRepeatedly() cannot appear more than once in an "
462
"EXPECT_CALL()");
463
}
464
465
TEST(ExpectCallSyntaxTest, WillRepeatedlyMustBeBeforeRetiresOnSaturation) {
466
MockA a;
467
468
EXPECT_NONFATAL_FAILURE(
469
{ // NOLINT
470
EXPECT_CALL(a, DoA(1)).RetiresOnSaturation().WillRepeatedly(Return());
471
},
472
".WillRepeatedly() cannot appear after ");
473
}
474
475
TEST(ExpectCallSyntaxTest, RetiresOnSaturationIsOptional) {
476
MockA a;
477
478
EXPECT_CALL(a, DoA(1));
479
EXPECT_CALL(a, DoA(1)).RetiresOnSaturation();
480
481
a.DoA(1);
482
a.DoA(1);
483
}
484
485
TEST(ExpectCallSyntaxTest, RetiresOnSaturationCannotAppearMultipleTimes) {
486
MockA a;
487
488
EXPECT_NONFATAL_FAILURE(
489
{ // NOLINT
490
EXPECT_CALL(a, DoA(1)).RetiresOnSaturation().RetiresOnSaturation();
491
},
492
".RetiresOnSaturation() cannot appear more than once");
493
494
a.DoA(1);
495
}
496
497
TEST(ExpectCallSyntaxTest, DefaultCardinalityIsOnce) {
498
{
499
MockA a;
500
EXPECT_CALL(a, DoA(1));
501
a.DoA(1);
502
}
503
EXPECT_NONFATAL_FAILURE(
504
{ // NOLINT
505
MockA a;
506
EXPECT_CALL(a, DoA(1));
507
},
508
"to be called once");
509
EXPECT_NONFATAL_FAILURE(
510
{ // NOLINT
511
MockA a;
512
EXPECT_CALL(a, DoA(1));
513
a.DoA(1);
514
a.DoA(1);
515
},
516
"to be called once");
517
}
518
519
#if GTEST_HAS_STREAM_REDIRECTION
520
521
// Tests that Google Mock doesn't print a warning when the number of
522
// WillOnce() is adequate.
523
TEST(ExpectCallSyntaxTest, DoesNotWarnOnAdequateActionCount) {
524
CaptureStdout();
525
{
526
MockB b;
527
528
// It's always fine to omit WillOnce() entirely.
529
EXPECT_CALL(b, DoB()).Times(0);
530
EXPECT_CALL(b, DoB(1)).Times(AtMost(1));
531
EXPECT_CALL(b, DoB(2)).Times(1).WillRepeatedly(Return(1));
532
533
// It's fine for the number of WillOnce()s to equal the upper bound.
534
EXPECT_CALL(b, DoB(3))
535
.Times(Between(1, 2))
536
.WillOnce(Return(1))
537
.WillOnce(Return(2));
538
539
// It's fine for the number of WillOnce()s to be smaller than the
540
// upper bound when there is a WillRepeatedly().
541
EXPECT_CALL(b, DoB(4)).Times(AtMost(3)).WillOnce(Return(1)).WillRepeatedly(
542
Return(2));
543
544
// Satisfies the above expectations.
545
b.DoB(2);
546
b.DoB(3);
547
}
548
EXPECT_STREQ("", GetCapturedStdout().c_str());
549
}
550
551
// Tests that Google Mock warns on having too many actions in an
552
// expectation compared to its cardinality.
553
TEST(ExpectCallSyntaxTest, WarnsOnTooManyActions) {
554
CaptureStdout();
555
{
556
MockB b;
557
558
// Warns when the number of WillOnce()s is larger than the upper bound.
559
EXPECT_CALL(b, DoB()).Times(0).WillOnce(Return(1)); // #1
560
EXPECT_CALL(b, DoB()).Times(AtMost(1)).WillOnce(Return(1)).WillOnce(
561
Return(2)); // #2
562
EXPECT_CALL(b, DoB(1))
563
.Times(1)
564
.WillOnce(Return(1))
565
.WillOnce(Return(2))
566
.RetiresOnSaturation(); // #3
567
568
// Warns when the number of WillOnce()s equals the upper bound and
569
// there is a WillRepeatedly().
570
EXPECT_CALL(b, DoB()).Times(0).WillRepeatedly(Return(1)); // #4
571
EXPECT_CALL(b, DoB(2)).Times(1).WillOnce(Return(1)).WillRepeatedly(
572
Return(2)); // #5
573
574
// Satisfies the above expectations.
575
b.DoB(1);
576
b.DoB(2);
577
}
578
const std::string output = GetCapturedStdout();
579
EXPECT_PRED_FORMAT2(IsSubstring,
580
"Too many actions specified in EXPECT_CALL(b, DoB())...\n"
581
"Expected to be never called, but has 1 WillOnce().",
582
output); // #1
583
EXPECT_PRED_FORMAT2(IsSubstring,
584
"Too many actions specified in EXPECT_CALL(b, DoB())...\n"
585
"Expected to be called at most once, "
586
"but has 2 WillOnce()s.",
587
output); // #2
588
EXPECT_PRED_FORMAT2(
589
IsSubstring,
590
"Too many actions specified in EXPECT_CALL(b, DoB(1))...\n"
591
"Expected to be called once, but has 2 WillOnce()s.",
592
output); // #3
593
EXPECT_PRED_FORMAT2(IsSubstring,
594
"Too many actions specified in EXPECT_CALL(b, DoB())...\n"
595
"Expected to be never called, but has 0 WillOnce()s "
596
"and a WillRepeatedly().",
597
output); // #4
598
EXPECT_PRED_FORMAT2(
599
IsSubstring,
600
"Too many actions specified in EXPECT_CALL(b, DoB(2))...\n"
601
"Expected to be called once, but has 1 WillOnce() "
602
"and a WillRepeatedly().",
603
output); // #5
604
}
605
606
// Tests that Google Mock warns on having too few actions in an
607
// expectation compared to its cardinality.
608
TEST(ExpectCallSyntaxTest, WarnsOnTooFewActions) {
609
MockB b;
610
611
EXPECT_CALL(b, DoB()).Times(Between(2, 3)).WillOnce(Return(1));
612
613
CaptureStdout();
614
b.DoB();
615
const std::string output = GetCapturedStdout();
616
EXPECT_PRED_FORMAT2(IsSubstring,
617
"Too few actions specified in EXPECT_CALL(b, DoB())...\n"
618
"Expected to be called between 2 and 3 times, "
619
"but has only 1 WillOnce().",
620
output);
621
b.DoB();
622
}
623
624
TEST(ExpectCallSyntaxTest, WarningIsErrorWithFlag) {
625
int original_behavior = GMOCK_FLAG_GET(default_mock_behavior);
626
627
GMOCK_FLAG_SET(default_mock_behavior, kAllow);
628
CaptureStdout();
629
{
630
MockA a;
631
a.DoA(0);
632
}
633
std::string output = GetCapturedStdout();
634
EXPECT_TRUE(output.empty()) << output;
635
636
GMOCK_FLAG_SET(default_mock_behavior, kWarn);
637
CaptureStdout();
638
{
639
MockA a;
640
a.DoA(0);
641
}
642
std::string warning_output = GetCapturedStdout();
643
EXPECT_PRED_FORMAT2(IsSubstring, "GMOCK WARNING", warning_output);
644
EXPECT_PRED_FORMAT2(IsSubstring, "Uninteresting mock function call",
645
warning_output);
646
647
GMOCK_FLAG_SET(default_mock_behavior, kFail);
648
EXPECT_NONFATAL_FAILURE(
649
{
650
MockA a;
651
a.DoA(0);
652
},
653
"Uninteresting mock function call");
654
655
// Out of bounds values are converted to kWarn
656
GMOCK_FLAG_SET(default_mock_behavior, -1);
657
CaptureStdout();
658
{
659
MockA a;
660
a.DoA(0);
661
}
662
warning_output = GetCapturedStdout();
663
EXPECT_PRED_FORMAT2(IsSubstring, "GMOCK WARNING", warning_output);
664
EXPECT_PRED_FORMAT2(IsSubstring, "Uninteresting mock function call",
665
warning_output);
666
GMOCK_FLAG_SET(default_mock_behavior, 3);
667
CaptureStdout();
668
{
669
MockA a;
670
a.DoA(0);
671
}
672
warning_output = GetCapturedStdout();
673
EXPECT_PRED_FORMAT2(IsSubstring, "GMOCK WARNING", warning_output);
674
EXPECT_PRED_FORMAT2(IsSubstring, "Uninteresting mock function call",
675
warning_output);
676
677
GMOCK_FLAG_SET(default_mock_behavior, original_behavior);
678
}
679
680
#endif // GTEST_HAS_STREAM_REDIRECTION
681
682
// Tests the semantics of ON_CALL().
683
684
// Tests that the built-in default action is taken when no ON_CALL()
685
// is specified.
686
TEST(OnCallTest, TakesBuiltInDefaultActionWhenNoOnCall) {
687
MockB b;
688
EXPECT_CALL(b, DoB());
689
690
EXPECT_EQ(0, b.DoB());
691
}
692
693
// Tests that the built-in default action is taken when no ON_CALL()
694
// matches the invocation.
695
TEST(OnCallTest, TakesBuiltInDefaultActionWhenNoOnCallMatches) {
696
MockB b;
697
ON_CALL(b, DoB(1)).WillByDefault(Return(1));
698
EXPECT_CALL(b, DoB(_));
699
700
EXPECT_EQ(0, b.DoB(2));
701
}
702
703
// Tests that the last matching ON_CALL() action is taken.
704
TEST(OnCallTest, PicksLastMatchingOnCall) {
705
MockB b;
706
ON_CALL(b, DoB(_)).WillByDefault(Return(3));
707
ON_CALL(b, DoB(2)).WillByDefault(Return(2));
708
ON_CALL(b, DoB(1)).WillByDefault(Return(1));
709
EXPECT_CALL(b, DoB(_));
710
711
EXPECT_EQ(2, b.DoB(2));
712
}
713
714
// Tests the semantics of EXPECT_CALL().
715
716
// Tests that any call is allowed when no EXPECT_CALL() is specified.
717
TEST(ExpectCallTest, AllowsAnyCallWhenNoSpec) {
718
MockB b;
719
EXPECT_CALL(b, DoB());
720
// There is no expectation on DoB(int).
721
722
b.DoB();
723
724
// DoB(int) can be called any number of times.
725
b.DoB(1);
726
b.DoB(2);
727
}
728
729
// Tests that the last matching EXPECT_CALL() fires.
730
TEST(ExpectCallTest, PicksLastMatchingExpectCall) {
731
MockB b;
732
EXPECT_CALL(b, DoB(_)).WillRepeatedly(Return(2));
733
EXPECT_CALL(b, DoB(1)).WillRepeatedly(Return(1));
734
735
EXPECT_EQ(1, b.DoB(1));
736
}
737
738
// Tests lower-bound violation.
739
TEST(ExpectCallTest, CatchesTooFewCalls) {
740
EXPECT_NONFATAL_FAILURE(
741
{ // NOLINT
742
MockB b;
743
EXPECT_CALL(b, DoB(5)).Description("DoB Method").Times(AtLeast(2));
744
745
b.DoB(5);
746
},
747
"Actual function \"DoB Method\" call count "
748
"doesn't match EXPECT_CALL(b, DoB(5))...\n"
749
" Expected: to be called at least twice\n"
750
" Actual: called once - unsatisfied and active");
751
}
752
753
// Tests that the cardinality can be inferred when no Times(...) is
754
// specified.
755
TEST(ExpectCallTest, InfersCardinalityWhenThereIsNoWillRepeatedly) {
756
{
757
MockB b;
758
EXPECT_CALL(b, DoB()).WillOnce(Return(1)).WillOnce(Return(2));
759
760
EXPECT_EQ(1, b.DoB());
761
EXPECT_EQ(2, b.DoB());
762
}
763
764
EXPECT_NONFATAL_FAILURE(
765
{ // NOLINT
766
MockB b;
767
EXPECT_CALL(b, DoB()).WillOnce(Return(1)).WillOnce(Return(2));
768
769
EXPECT_EQ(1, b.DoB());
770
},
771
"to be called twice");
772
773
{ // NOLINT
774
MockB b;
775
EXPECT_CALL(b, DoB()).WillOnce(Return(1)).WillOnce(Return(2));
776
777
EXPECT_EQ(1, b.DoB());
778
EXPECT_EQ(2, b.DoB());
779
EXPECT_NONFATAL_FAILURE(b.DoB(), "to be called twice");
780
}
781
}
782
783
TEST(ExpectCallTest, InfersCardinality1WhenThereIsWillRepeatedly) {
784
{
785
MockB b;
786
EXPECT_CALL(b, DoB()).WillOnce(Return(1)).WillRepeatedly(Return(2));
787
788
EXPECT_EQ(1, b.DoB());
789
}
790
791
{ // NOLINT
792
MockB b;
793
EXPECT_CALL(b, DoB()).WillOnce(Return(1)).WillRepeatedly(Return(2));
794
795
EXPECT_EQ(1, b.DoB());
796
EXPECT_EQ(2, b.DoB());
797
EXPECT_EQ(2, b.DoB());
798
}
799
800
EXPECT_NONFATAL_FAILURE(
801
{ // NOLINT
802
MockB b;
803
EXPECT_CALL(b, DoB()).WillOnce(Return(1)).WillRepeatedly(Return(2));
804
},
805
"to be called at least once");
806
}
807
808
// TODO(b/396121064) - Fix this test under MSVC
809
#ifndef _MSC_VER
810
// It should be possible to return a non-moveable type from a mock action in
811
// C++17 and above, where it's guaranteed that such a type can be initialized
812
// from a prvalue returned from a function.
813
TEST(ExpectCallTest, NonMoveableType) {
814
// Define a non-moveable result type.
815
struct NonMoveableStruct {
816
explicit NonMoveableStruct(int x_in) : x(x_in) {}
817
NonMoveableStruct(NonMoveableStruct&&) = delete;
818
819
int x;
820
};
821
822
static_assert(!std::is_move_constructible_v<NonMoveableStruct>);
823
static_assert(!std::is_copy_constructible_v<NonMoveableStruct>);
824
825
static_assert(!std::is_move_assignable_v<NonMoveableStruct>);
826
static_assert(!std::is_copy_assignable_v<NonMoveableStruct>);
827
828
// We should be able to use a callable that returns that result as both a
829
// OnceAction and an Action, whether the callable ignores arguments or not.
830
const auto return_17 = [] { return NonMoveableStruct(17); };
831
832
static_cast<void>(OnceAction<NonMoveableStruct()>{return_17});
833
static_cast<void>(Action<NonMoveableStruct()>{return_17});
834
835
static_cast<void>(OnceAction<NonMoveableStruct(int)>{return_17});
836
static_cast<void>(Action<NonMoveableStruct(int)>{return_17});
837
838
// It should be possible to return the result end to end through an
839
// EXPECT_CALL statement, with both WillOnce and WillRepeatedly.
840
MockFunction<NonMoveableStruct()> mock;
841
EXPECT_CALL(mock, Call) //
842
.WillOnce(return_17) //
843
.WillRepeatedly(return_17);
844
845
EXPECT_EQ(17, mock.AsStdFunction()().x);
846
EXPECT_EQ(17, mock.AsStdFunction()().x);
847
EXPECT_EQ(17, mock.AsStdFunction()().x);
848
}
849
850
#endif // _MSC_VER
851
852
// Tests that the n-th action is taken for the n-th matching
853
// invocation.
854
TEST(ExpectCallTest, NthMatchTakesNthAction) {
855
MockB b;
856
EXPECT_CALL(b, DoB()).WillOnce(Return(1)).WillOnce(Return(2)).WillOnce(
857
Return(3));
858
859
EXPECT_EQ(1, b.DoB());
860
EXPECT_EQ(2, b.DoB());
861
EXPECT_EQ(3, b.DoB());
862
}
863
864
// Tests that the WillRepeatedly() action is taken when the WillOnce(...)
865
// list is exhausted.
866
TEST(ExpectCallTest, TakesRepeatedActionWhenWillListIsExhausted) {
867
MockB b;
868
EXPECT_CALL(b, DoB()).WillOnce(Return(1)).WillRepeatedly(Return(2));
869
870
EXPECT_EQ(1, b.DoB());
871
EXPECT_EQ(2, b.DoB());
872
EXPECT_EQ(2, b.DoB());
873
}
874
875
#if GTEST_HAS_STREAM_REDIRECTION
876
877
// Tests that the default action is taken when the WillOnce(...) list is
878
// exhausted and there is no WillRepeatedly().
879
TEST(ExpectCallTest, TakesDefaultActionWhenWillListIsExhausted) {
880
MockB b;
881
EXPECT_CALL(b, DoB(_)).Times(1);
882
EXPECT_CALL(b, DoB())
883
.Times(AnyNumber())
884
.WillOnce(Return(1))
885
.WillOnce(Return(2));
886
887
CaptureStdout();
888
EXPECT_EQ(0, b.DoB(1)); // Shouldn't generate a warning as the
889
// expectation has no action clause at all.
890
EXPECT_EQ(1, b.DoB());
891
EXPECT_EQ(2, b.DoB());
892
const std::string output1 = GetCapturedStdout();
893
EXPECT_STREQ("", output1.c_str());
894
895
CaptureStdout();
896
EXPECT_EQ(0, b.DoB());
897
EXPECT_EQ(0, b.DoB());
898
const std::string output2 = GetCapturedStdout();
899
EXPECT_THAT(output2.c_str(),
900
HasSubstr("Actions ran out in EXPECT_CALL(b, DoB())...\n"
901
"Called 3 times, but only 2 WillOnce()s are specified"
902
" - returning default value."));
903
EXPECT_THAT(output2.c_str(),
904
HasSubstr("Actions ran out in EXPECT_CALL(b, DoB())...\n"
905
"Called 4 times, but only 2 WillOnce()s are specified"
906
" - returning default value."));
907
}
908
909
TEST(FunctionMockerMessageTest, ReportsExpectCallLocationForExhaustedActions) {
910
MockB b;
911
std::string expect_call_location = FormatFileLocation(__FILE__, __LINE__ + 1);
912
EXPECT_CALL(b, DoB()).Times(AnyNumber()).WillOnce(Return(1));
913
914
EXPECT_EQ(1, b.DoB());
915
916
CaptureStdout();
917
EXPECT_EQ(0, b.DoB());
918
const std::string output = GetCapturedStdout();
919
// The warning message should contain the call location.
920
EXPECT_PRED_FORMAT2(IsSubstring, expect_call_location, output);
921
}
922
923
TEST(FunctionMockerMessageTest,
924
ReportsDefaultActionLocationOfUninterestingCallsForNaggyMock) {
925
std::string on_call_location;
926
CaptureStdout();
927
{
928
NaggyMock<MockB> b;
929
on_call_location = FormatFileLocation(__FILE__, __LINE__ + 1);
930
ON_CALL(b, DoB(_)).WillByDefault(Return(0));
931
b.DoB(0);
932
}
933
EXPECT_PRED_FORMAT2(IsSubstring, on_call_location, GetCapturedStdout());
934
}
935
936
#endif // GTEST_HAS_STREAM_REDIRECTION
937
938
// Tests that an uninteresting call performs the default action.
939
TEST(UninterestingCallTest, DoesDefaultAction) {
940
// When there is an ON_CALL() statement, the action specified by it
941
// should be taken.
942
MockA a;
943
ON_CALL(a, Binary(_, _)).WillByDefault(Return(true));
944
EXPECT_TRUE(a.Binary(1, 2));
945
946
// When there is no ON_CALL(), the default value for the return type
947
// should be returned.
948
MockB b;
949
EXPECT_EQ(0, b.DoB());
950
}
951
952
// Tests that an unexpected call performs the default action.
953
TEST(UnexpectedCallTest, DoesDefaultAction) {
954
// When there is an ON_CALL() statement, the action specified by it
955
// should be taken.
956
MockA a;
957
ON_CALL(a, Binary(_, _)).WillByDefault(Return(true));
958
EXPECT_CALL(a, Binary(0, 0));
959
a.Binary(0, 0);
960
bool result = false;
961
EXPECT_NONFATAL_FAILURE(result = a.Binary(1, 2),
962
"Unexpected mock function call");
963
EXPECT_TRUE(result);
964
965
// When there is no ON_CALL(), the default value for the return type
966
// should be returned.
967
MockB b;
968
EXPECT_CALL(b, DoB(0)).Times(0);
969
int n = -1;
970
EXPECT_NONFATAL_FAILURE(n = b.DoB(1), "Unexpected mock function call");
971
EXPECT_EQ(0, n);
972
}
973
974
// Tests that when an unexpected void function generates the right
975
// failure message.
976
TEST(UnexpectedCallTest, GeneratesFailureForVoidFunction) {
977
// First, tests the message when there is only one EXPECT_CALL().
978
MockA a1;
979
EXPECT_CALL(a1, DoA(1));
980
a1.DoA(1);
981
// Ideally we should match the failure message against a regex, but
982
// EXPECT_NONFATAL_FAILURE doesn't support that, so we test for
983
// multiple sub-strings instead.
984
EXPECT_NONFATAL_FAILURE(
985
a1.DoA(9),
986
"Unexpected mock function call - returning directly.\n"
987
" Function call: DoA(9)\n"
988
"Google Mock tried the following 1 expectation, but it didn't match:");
989
EXPECT_NONFATAL_FAILURE(
990
a1.DoA(9),
991
" Expected arg #0: is equal to 1\n"
992
" Actual: 9\n"
993
" Expected: to be called once\n"
994
" Actual: called once - saturated and active");
995
996
// Next, tests the message when there are more than one EXPECT_CALL().
997
MockA a2;
998
EXPECT_CALL(a2, DoA(1));
999
EXPECT_CALL(a2, DoA(3));
1000
a2.DoA(1);
1001
EXPECT_NONFATAL_FAILURE(
1002
a2.DoA(2),
1003
"Unexpected mock function call - returning directly.\n"
1004
" Function call: DoA(2)\n"
1005
"Google Mock tried the following 2 expectations, but none matched:");
1006
EXPECT_NONFATAL_FAILURE(
1007
a2.DoA(2),
1008
"tried expectation #0: EXPECT_CALL(a2, DoA(1))...\n"
1009
" Expected arg #0: is equal to 1\n"
1010
" Actual: 2\n"
1011
" Expected: to be called once\n"
1012
" Actual: called once - saturated and active");
1013
EXPECT_NONFATAL_FAILURE(
1014
a2.DoA(2),
1015
"tried expectation #1: EXPECT_CALL(a2, DoA(3))...\n"
1016
" Expected arg #0: is equal to 3\n"
1017
" Actual: 2\n"
1018
" Expected: to be called once\n"
1019
" Actual: never called - unsatisfied and active");
1020
a2.DoA(3);
1021
}
1022
1023
// Tests that an unexpected non-void function generates the right
1024
// failure message.
1025
TEST(UnexpectedCallTest, GeneartesFailureForNonVoidFunction) {
1026
MockB b1;
1027
EXPECT_CALL(b1, DoB(1));
1028
b1.DoB(1);
1029
EXPECT_NONFATAL_FAILURE(
1030
b1.DoB(2),
1031
"Unexpected mock function call - returning default value.\n"
1032
" Function call: DoB(2)\n"
1033
" Returns: 0\n"
1034
"Google Mock tried the following 1 expectation, but it didn't match:");
1035
EXPECT_NONFATAL_FAILURE(
1036
b1.DoB(2),
1037
" Expected arg #0: is equal to 1\n"
1038
" Actual: 2\n"
1039
" Expected: to be called once\n"
1040
" Actual: called once - saturated and active");
1041
}
1042
1043
// Tests that Google Mock explains that an retired expectation doesn't
1044
// match the call.
1045
TEST(UnexpectedCallTest, RetiredExpectation) {
1046
MockB b;
1047
EXPECT_CALL(b, DoB(1)).RetiresOnSaturation();
1048
1049
b.DoB(1);
1050
EXPECT_NONFATAL_FAILURE(b.DoB(1),
1051
" Expected: the expectation is active\n"
1052
" Actual: it is retired");
1053
}
1054
1055
// Tests that Google Mock explains that an expectation that doesn't
1056
// match the arguments doesn't match the call.
1057
TEST(UnexpectedCallTest, UnmatchedArguments) {
1058
MockB b;
1059
EXPECT_CALL(b, DoB(1));
1060
1061
EXPECT_NONFATAL_FAILURE(b.DoB(2),
1062
" Expected arg #0: is equal to 1\n"
1063
" Actual: 2\n");
1064
b.DoB(1);
1065
}
1066
1067
// Tests that Google Mock explains that an expectation with
1068
// unsatisfied pre-requisites doesn't match the call.
1069
TEST(UnexpectedCallTest, UnsatisfiedPrerequisites) {
1070
Sequence s1, s2;
1071
MockB b;
1072
EXPECT_CALL(b, DoB(1)).InSequence(s1);
1073
EXPECT_CALL(b, DoB(2)).Times(AnyNumber()).InSequence(s1);
1074
EXPECT_CALL(b, DoB(3)).InSequence(s2);
1075
EXPECT_CALL(b, DoB(4)).InSequence(s1, s2);
1076
1077
::testing::TestPartResultArray failures;
1078
{
1079
::testing::ScopedFakeTestPartResultReporter reporter(&failures);
1080
b.DoB(4);
1081
// Now 'failures' contains the Google Test failures generated by
1082
// the above statement.
1083
}
1084
1085
// There should be one non-fatal failure.
1086
ASSERT_EQ(1, failures.size());
1087
const ::testing::TestPartResult& r = failures.GetTestPartResult(0);
1088
EXPECT_EQ(::testing::TestPartResult::kNonFatalFailure, r.type());
1089
1090
// Verifies that the failure message contains the two unsatisfied
1091
// pre-requisites but not the satisfied one.
1092
#ifdef GTEST_USES_POSIX_RE
1093
EXPECT_THAT(r.message(),
1094
ContainsRegex(
1095
// POSIX RE doesn't understand the (?s) prefix, but has no
1096
// trouble with (.|\n).
1097
"the following immediate pre-requisites are not satisfied:\n"
1098
"(.|\n)*: pre-requisite #0\n"
1099
"(.|\n)*: pre-requisite #1"));
1100
#else
1101
// We can only use Google Test's own simple regex.
1102
EXPECT_THAT(r.message(),
1103
ContainsRegex(
1104
"the following immediate pre-requisites are not satisfied:"));
1105
EXPECT_THAT(r.message(), ContainsRegex(": pre-requisite #0"));
1106
EXPECT_THAT(r.message(), ContainsRegex(": pre-requisite #1"));
1107
#endif // GTEST_USES_POSIX_RE
1108
1109
b.DoB(1);
1110
b.DoB(3);
1111
b.DoB(4);
1112
}
1113
1114
TEST(UndefinedReturnValueTest,
1115
ReturnValueIsMandatoryWhenNotDefaultConstructible) {
1116
MockA a;
1117
// FIXME: We should really verify the output message,
1118
// but we cannot yet due to that EXPECT_DEATH only captures stderr
1119
// while Google Mock logs to stdout.
1120
#if GTEST_HAS_EXCEPTIONS
1121
EXPECT_ANY_THROW(a.ReturnNonDefaultConstructible());
1122
#else
1123
EXPECT_DEATH_IF_SUPPORTED(a.ReturnNonDefaultConstructible(), "");
1124
#endif
1125
}
1126
1127
// Tests that an excessive call (one whose arguments match the
1128
// matchers but is called too many times) performs the default action.
1129
TEST(ExcessiveCallTest, DoesDefaultAction) {
1130
// When there is an ON_CALL() statement, the action specified by it
1131
// should be taken.
1132
MockA a;
1133
ON_CALL(a, Binary(_, _)).WillByDefault(Return(true));
1134
EXPECT_CALL(a, Binary(0, 0));
1135
a.Binary(0, 0);
1136
bool result = false;
1137
EXPECT_NONFATAL_FAILURE(result = a.Binary(0, 0),
1138
"Mock function called more times than expected");
1139
EXPECT_TRUE(result);
1140
1141
// When there is no ON_CALL(), the default value for the return type
1142
// should be returned.
1143
MockB b;
1144
EXPECT_CALL(b, DoB(0)).Description("DoB Method").Times(0);
1145
int n = -1;
1146
EXPECT_NONFATAL_FAILURE(
1147
n = b.DoB(0),
1148
"Mock function \"DoB Method\" called more times than expected");
1149
EXPECT_EQ(0, n);
1150
}
1151
1152
// Tests that when a void function is called too many times,
1153
// the failure message contains the argument values.
1154
TEST(ExcessiveCallTest, GeneratesFailureForVoidFunction) {
1155
MockA a;
1156
EXPECT_CALL(a, DoA(_)).Description("DoA Method").Times(0);
1157
EXPECT_NONFATAL_FAILURE(
1158
a.DoA(9),
1159
"Mock function \"DoA Method\" called more times than expected - "
1160
"returning directly.\n"
1161
" Function call: DoA(9)\n"
1162
" Expected: to be never called\n"
1163
" Actual: called once - over-saturated and active");
1164
}
1165
1166
// Tests that when a non-void function is called too many times, the
1167
// failure message contains the argument values and the return value.
1168
TEST(ExcessiveCallTest, GeneratesFailureForNonVoidFunction) {
1169
MockB b;
1170
EXPECT_CALL(b, DoB(_));
1171
b.DoB(1);
1172
EXPECT_NONFATAL_FAILURE(
1173
b.DoB(2),
1174
"Mock function called more times than expected - "
1175
"returning default value.\n"
1176
" Function call: DoB(2)\n"
1177
" Returns: 0\n"
1178
" Expected: to be called once\n"
1179
" Actual: called twice - over-saturated and active");
1180
}
1181
1182
// Tests using sequences.
1183
1184
TEST(InSequenceTest, AllExpectationInScopeAreInSequence) {
1185
MockA a;
1186
{
1187
InSequence dummy;
1188
1189
EXPECT_CALL(a, DoA(1));
1190
EXPECT_CALL(a, DoA(2));
1191
}
1192
1193
EXPECT_NONFATAL_FAILURE(
1194
{ // NOLINT
1195
a.DoA(2);
1196
},
1197
"Unexpected mock function call");
1198
1199
a.DoA(1);
1200
a.DoA(2);
1201
}
1202
1203
TEST(InSequenceTest, NestedInSequence) {
1204
MockA a;
1205
{
1206
InSequence dummy;
1207
1208
EXPECT_CALL(a, DoA(1));
1209
{
1210
InSequence dummy2;
1211
1212
EXPECT_CALL(a, DoA(2));
1213
EXPECT_CALL(a, DoA(3));
1214
}
1215
}
1216
1217
EXPECT_NONFATAL_FAILURE(
1218
{ // NOLINT
1219
a.DoA(1);
1220
a.DoA(3);
1221
},
1222
"Unexpected mock function call");
1223
1224
a.DoA(2);
1225
a.DoA(3);
1226
}
1227
1228
TEST(InSequenceTest, ExpectationsOutOfScopeAreNotAffected) {
1229
MockA a;
1230
{
1231
InSequence dummy;
1232
1233
EXPECT_CALL(a, DoA(1));
1234
EXPECT_CALL(a, DoA(2));
1235
}
1236
EXPECT_CALL(a, DoA(3));
1237
1238
EXPECT_NONFATAL_FAILURE(
1239
{ // NOLINT
1240
a.DoA(2);
1241
},
1242
"Unexpected mock function call");
1243
1244
a.DoA(3);
1245
a.DoA(1);
1246
a.DoA(2);
1247
}
1248
1249
// Tests that any order is allowed when no sequence is used.
1250
TEST(SequenceTest, AnyOrderIsOkByDefault) {
1251
{
1252
MockA a;
1253
MockB b;
1254
1255
EXPECT_CALL(a, DoA(1));
1256
EXPECT_CALL(b, DoB()).Times(AnyNumber());
1257
1258
a.DoA(1);
1259
b.DoB();
1260
}
1261
1262
{ // NOLINT
1263
MockA a;
1264
MockB b;
1265
1266
EXPECT_CALL(a, DoA(1));
1267
EXPECT_CALL(b, DoB()).Times(AnyNumber());
1268
1269
b.DoB();
1270
a.DoA(1);
1271
}
1272
}
1273
1274
// Tests that the calls must be in strict order when a complete order
1275
// is specified.
1276
TEST(SequenceTest, CallsMustBeInStrictOrderWhenSaidSo1) {
1277
MockA a;
1278
ON_CALL(a, ReturnResult(_)).WillByDefault(Return(Result()));
1279
1280
Sequence s;
1281
EXPECT_CALL(a, ReturnResult(1)).InSequence(s);
1282
EXPECT_CALL(a, ReturnResult(2)).InSequence(s);
1283
EXPECT_CALL(a, ReturnResult(3)).InSequence(s);
1284
1285
a.ReturnResult(1);
1286
1287
// May only be called after a.ReturnResult(2).
1288
EXPECT_NONFATAL_FAILURE(a.ReturnResult(3), "Unexpected mock function call");
1289
1290
a.ReturnResult(2);
1291
a.ReturnResult(3);
1292
}
1293
1294
// Tests that the calls must be in strict order when a complete order
1295
// is specified.
1296
TEST(SequenceTest, CallsMustBeInStrictOrderWhenSaidSo2) {
1297
MockA a;
1298
ON_CALL(a, ReturnResult(_)).WillByDefault(Return(Result()));
1299
1300
Sequence s;
1301
EXPECT_CALL(a, ReturnResult(1)).InSequence(s);
1302
EXPECT_CALL(a, ReturnResult(2)).InSequence(s);
1303
1304
// May only be called after a.ReturnResult(1).
1305
EXPECT_NONFATAL_FAILURE(a.ReturnResult(2), "Unexpected mock function call");
1306
1307
a.ReturnResult(1);
1308
a.ReturnResult(2);
1309
}
1310
1311
// Tests specifying a DAG using multiple sequences.
1312
class PartialOrderTest : public testing::Test {
1313
protected:
1314
PartialOrderTest() {
1315
ON_CALL(a_, ReturnResult(_)).WillByDefault(Return(Result()));
1316
1317
// Specifies this partial ordering:
1318
//
1319
// a.ReturnResult(1) ==>
1320
// a.ReturnResult(2) * n ==> a.ReturnResult(3)
1321
// b.DoB() * 2 ==>
1322
Sequence x, y;
1323
EXPECT_CALL(a_, ReturnResult(1)).InSequence(x);
1324
EXPECT_CALL(b_, DoB()).Times(2).InSequence(y);
1325
EXPECT_CALL(a_, ReturnResult(2)).Times(AnyNumber()).InSequence(x, y);
1326
EXPECT_CALL(a_, ReturnResult(3)).InSequence(x);
1327
}
1328
1329
MockA a_;
1330
MockB b_;
1331
};
1332
1333
TEST_F(PartialOrderTest, CallsMustConformToSpecifiedDag1) {
1334
a_.ReturnResult(1);
1335
b_.DoB();
1336
1337
// May only be called after the second DoB().
1338
EXPECT_NONFATAL_FAILURE(a_.ReturnResult(2), "Unexpected mock function call");
1339
1340
b_.DoB();
1341
a_.ReturnResult(3);
1342
}
1343
1344
TEST_F(PartialOrderTest, CallsMustConformToSpecifiedDag2) {
1345
// May only be called after ReturnResult(1).
1346
EXPECT_NONFATAL_FAILURE(a_.ReturnResult(2), "Unexpected mock function call");
1347
1348
a_.ReturnResult(1);
1349
b_.DoB();
1350
b_.DoB();
1351
a_.ReturnResult(3);
1352
}
1353
1354
TEST_F(PartialOrderTest, CallsMustConformToSpecifiedDag3) {
1355
// May only be called last.
1356
EXPECT_NONFATAL_FAILURE(a_.ReturnResult(3), "Unexpected mock function call");
1357
1358
a_.ReturnResult(1);
1359
b_.DoB();
1360
b_.DoB();
1361
a_.ReturnResult(3);
1362
}
1363
1364
TEST_F(PartialOrderTest, CallsMustConformToSpecifiedDag4) {
1365
a_.ReturnResult(1);
1366
b_.DoB();
1367
b_.DoB();
1368
a_.ReturnResult(3);
1369
1370
// May only be called before ReturnResult(3).
1371
EXPECT_NONFATAL_FAILURE(a_.ReturnResult(2), "Unexpected mock function call");
1372
}
1373
1374
TEST(SequenceTest, Retirement) {
1375
MockA a;
1376
Sequence s;
1377
1378
EXPECT_CALL(a, DoA(1)).InSequence(s);
1379
EXPECT_CALL(a, DoA(_)).InSequence(s).RetiresOnSaturation();
1380
EXPECT_CALL(a, DoA(1)).InSequence(s);
1381
1382
a.DoA(1);
1383
a.DoA(2);
1384
a.DoA(1);
1385
}
1386
1387
// Tests Expectation.
1388
1389
TEST(ExpectationTest, ConstrutorsWork) {
1390
MockA a;
1391
Expectation e1; // Default ctor.
1392
1393
// Ctor from various forms of EXPECT_CALL.
1394
Expectation e2 = EXPECT_CALL(a, DoA(2));
1395
Expectation e3 = EXPECT_CALL(a, DoA(3)).With(_);
1396
{
1397
Sequence s;
1398
Expectation e4 = EXPECT_CALL(a, DoA(4)).Times(1);
1399
Expectation e5 = EXPECT_CALL(a, DoA(5)).InSequence(s);
1400
}
1401
Expectation e6 = EXPECT_CALL(a, DoA(6)).After(e2);
1402
Expectation e7 = EXPECT_CALL(a, DoA(7)).WillOnce(Return());
1403
Expectation e8 = EXPECT_CALL(a, DoA(8)).WillRepeatedly(Return());
1404
Expectation e9 = EXPECT_CALL(a, DoA(9)).RetiresOnSaturation();
1405
1406
Expectation e10 = e2; // Copy ctor.
1407
1408
EXPECT_THAT(e1, Ne(e2));
1409
EXPECT_THAT(e2, Eq(e10));
1410
1411
a.DoA(2);
1412
a.DoA(3);
1413
a.DoA(4);
1414
a.DoA(5);
1415
a.DoA(6);
1416
a.DoA(7);
1417
a.DoA(8);
1418
a.DoA(9);
1419
}
1420
1421
TEST(ExpectationTest, AssignmentWorks) {
1422
MockA a;
1423
Expectation e1;
1424
Expectation e2 = EXPECT_CALL(a, DoA(1));
1425
1426
EXPECT_THAT(e1, Ne(e2));
1427
1428
e1 = e2;
1429
EXPECT_THAT(e1, Eq(e2));
1430
1431
a.DoA(1);
1432
}
1433
1434
// Tests ExpectationSet.
1435
1436
TEST(ExpectationSetTest, MemberTypesAreCorrect) {
1437
::testing::StaticAssertTypeEq<Expectation, ExpectationSet::value_type>();
1438
}
1439
1440
TEST(ExpectationSetTest, ConstructorsWork) {
1441
MockA a;
1442
1443
Expectation e1;
1444
const Expectation e2;
1445
ExpectationSet es1; // Default ctor.
1446
ExpectationSet es2 = EXPECT_CALL(a, DoA(1)); // Ctor from EXPECT_CALL.
1447
ExpectationSet es3 = e1; // Ctor from Expectation.
1448
ExpectationSet es4(e1); // Ctor from Expectation; alternative syntax.
1449
ExpectationSet es5 = e2; // Ctor from const Expectation.
1450
ExpectationSet es6(e2); // Ctor from const Expectation; alternative syntax.
1451
ExpectationSet es7 = es2; // Copy ctor.
1452
1453
EXPECT_EQ(0, es1.size());
1454
EXPECT_EQ(1, es2.size());
1455
EXPECT_EQ(1, es3.size());
1456
EXPECT_EQ(1, es4.size());
1457
EXPECT_EQ(1, es5.size());
1458
EXPECT_EQ(1, es6.size());
1459
EXPECT_EQ(1, es7.size());
1460
1461
EXPECT_THAT(es3, Ne(es2));
1462
EXPECT_THAT(es4, Eq(es3));
1463
EXPECT_THAT(es5, Eq(es4));
1464
EXPECT_THAT(es6, Eq(es5));
1465
EXPECT_THAT(es7, Eq(es2));
1466
a.DoA(1);
1467
}
1468
1469
TEST(ExpectationSetTest, AssignmentWorks) {
1470
ExpectationSet es1;
1471
ExpectationSet es2 = Expectation();
1472
1473
es1 = es2;
1474
EXPECT_EQ(1, es1.size());
1475
EXPECT_THAT(*(es1.begin()), Eq(Expectation()));
1476
EXPECT_THAT(es1, Eq(es2));
1477
}
1478
1479
TEST(ExpectationSetTest, InsertionWorks) {
1480
ExpectationSet es1;
1481
Expectation e1;
1482
es1 += e1;
1483
EXPECT_EQ(1, es1.size());
1484
EXPECT_THAT(*(es1.begin()), Eq(e1));
1485
1486
MockA a;
1487
Expectation e2 = EXPECT_CALL(a, DoA(1));
1488
es1 += e2;
1489
EXPECT_EQ(2, es1.size());
1490
1491
ExpectationSet::const_iterator it1 = es1.begin();
1492
ExpectationSet::const_iterator it2 = it1;
1493
++it2;
1494
EXPECT_TRUE(*it1 == e1 || *it2 == e1); // e1 must be in the set.
1495
EXPECT_TRUE(*it1 == e2 || *it2 == e2); // e2 must be in the set too.
1496
a.DoA(1);
1497
}
1498
1499
TEST(ExpectationSetTest, SizeWorks) {
1500
ExpectationSet es;
1501
EXPECT_EQ(0, es.size());
1502
1503
es += Expectation();
1504
EXPECT_EQ(1, es.size());
1505
1506
MockA a;
1507
es += EXPECT_CALL(a, DoA(1));
1508
EXPECT_EQ(2, es.size());
1509
1510
a.DoA(1);
1511
}
1512
1513
TEST(ExpectationSetTest, IsEnumerable) {
1514
ExpectationSet es;
1515
EXPECT_TRUE(es.begin() == es.end());
1516
1517
es += Expectation();
1518
ExpectationSet::const_iterator it = es.begin();
1519
EXPECT_TRUE(it != es.end());
1520
EXPECT_THAT(*it, Eq(Expectation()));
1521
++it;
1522
EXPECT_TRUE(it == es.end());
1523
}
1524
1525
// Tests the .After() clause.
1526
1527
TEST(AfterTest, SucceedsWhenPartialOrderIsSatisfied) {
1528
MockA a;
1529
ExpectationSet es;
1530
es += EXPECT_CALL(a, DoA(1));
1531
es += EXPECT_CALL(a, DoA(2));
1532
EXPECT_CALL(a, DoA(3)).After(es);
1533
1534
a.DoA(1);
1535
a.DoA(2);
1536
a.DoA(3);
1537
}
1538
1539
TEST(AfterTest, SucceedsWhenTotalOrderIsSatisfied) {
1540
MockA a;
1541
MockB b;
1542
// The following also verifies that const Expectation objects work
1543
// too. Do not remove the const modifiers.
1544
const Expectation e1 = EXPECT_CALL(a, DoA(1));
1545
const Expectation e2 = EXPECT_CALL(b, DoB()).Times(2).After(e1);
1546
EXPECT_CALL(a, DoA(2)).After(e2);
1547
1548
a.DoA(1);
1549
b.DoB();
1550
b.DoB();
1551
a.DoA(2);
1552
}
1553
1554
// Calls must be in strict order when specified so using .After().
1555
TEST(AfterTest, CallsMustBeInStrictOrderWhenSpecifiedSo1) {
1556
MockA a;
1557
MockB b;
1558
1559
// Define ordering:
1560
// a.DoA(1) ==> b.DoB() ==> a.DoA(2)
1561
Expectation e1 = EXPECT_CALL(a, DoA(1));
1562
Expectation e2 = EXPECT_CALL(b, DoB()).After(e1);
1563
EXPECT_CALL(a, DoA(2)).After(e2);
1564
1565
a.DoA(1);
1566
1567
// May only be called after DoB().
1568
EXPECT_NONFATAL_FAILURE(a.DoA(2), "Unexpected mock function call");
1569
1570
b.DoB();
1571
a.DoA(2);
1572
}
1573
1574
// Calls must be in strict order when specified so using .After().
1575
TEST(AfterTest, CallsMustBeInStrictOrderWhenSpecifiedSo2) {
1576
MockA a;
1577
MockB b;
1578
1579
// Define ordering:
1580
// a.DoA(1) ==> b.DoB() * 2 ==> a.DoA(2)
1581
Expectation e1 = EXPECT_CALL(a, DoA(1));
1582
Expectation e2 = EXPECT_CALL(b, DoB()).Times(2).After(e1);
1583
EXPECT_CALL(a, DoA(2)).After(e2);
1584
1585
a.DoA(1);
1586
b.DoB();
1587
1588
// May only be called after the second DoB().
1589
EXPECT_NONFATAL_FAILURE(a.DoA(2), "Unexpected mock function call");
1590
1591
b.DoB();
1592
a.DoA(2);
1593
}
1594
1595
// Calls must satisfy the partial order when specified so.
1596
TEST(AfterTest, CallsMustSatisfyPartialOrderWhenSpecifiedSo) {
1597
MockA a;
1598
ON_CALL(a, ReturnResult(_)).WillByDefault(Return(Result()));
1599
1600
// Define ordering:
1601
// a.DoA(1) ==>
1602
// a.DoA(2) ==> a.ReturnResult(3)
1603
Expectation e = EXPECT_CALL(a, DoA(1));
1604
const ExpectationSet es = EXPECT_CALL(a, DoA(2));
1605
EXPECT_CALL(a, ReturnResult(3)).After(e, es);
1606
1607
// May only be called last.
1608
EXPECT_NONFATAL_FAILURE(a.ReturnResult(3), "Unexpected mock function call");
1609
1610
a.DoA(2);
1611
a.DoA(1);
1612
a.ReturnResult(3);
1613
}
1614
1615
// Calls must satisfy the partial order when specified so.
1616
TEST(AfterTest, CallsMustSatisfyPartialOrderWhenSpecifiedSo2) {
1617
MockA a;
1618
1619
// Define ordering:
1620
// a.DoA(1) ==>
1621
// a.DoA(2) ==> a.DoA(3)
1622
Expectation e = EXPECT_CALL(a, DoA(1));
1623
const ExpectationSet es = EXPECT_CALL(a, DoA(2));
1624
EXPECT_CALL(a, DoA(3)).After(e, es);
1625
1626
a.DoA(2);
1627
1628
// May only be called last.
1629
EXPECT_NONFATAL_FAILURE(a.DoA(3), "Unexpected mock function call");
1630
1631
a.DoA(1);
1632
a.DoA(3);
1633
}
1634
1635
// .After() can be combined with .InSequence().
1636
TEST(AfterTest, CanBeUsedWithInSequence) {
1637
MockA a;
1638
Sequence s;
1639
Expectation e = EXPECT_CALL(a, DoA(1));
1640
EXPECT_CALL(a, DoA(2)).InSequence(s);
1641
EXPECT_CALL(a, DoA(3)).InSequence(s).After(e);
1642
1643
a.DoA(1);
1644
1645
// May only be after DoA(2).
1646
EXPECT_NONFATAL_FAILURE(a.DoA(3), "Unexpected mock function call");
1647
1648
a.DoA(2);
1649
a.DoA(3);
1650
}
1651
1652
// .After() can be called multiple times.
1653
TEST(AfterTest, CanBeCalledManyTimes) {
1654
MockA a;
1655
Expectation e1 = EXPECT_CALL(a, DoA(1));
1656
Expectation e2 = EXPECT_CALL(a, DoA(2));
1657
Expectation e3 = EXPECT_CALL(a, DoA(3));
1658
EXPECT_CALL(a, DoA(4)).After(e1).After(e2).After(e3);
1659
1660
a.DoA(3);
1661
a.DoA(1);
1662
a.DoA(2);
1663
a.DoA(4);
1664
}
1665
1666
// .After() accepts up to 5 arguments.
1667
TEST(AfterTest, AcceptsUpToFiveArguments) {
1668
MockA a;
1669
Expectation e1 = EXPECT_CALL(a, DoA(1));
1670
Expectation e2 = EXPECT_CALL(a, DoA(2));
1671
Expectation e3 = EXPECT_CALL(a, DoA(3));
1672
ExpectationSet es1 = EXPECT_CALL(a, DoA(4));
1673
ExpectationSet es2 = EXPECT_CALL(a, DoA(5));
1674
EXPECT_CALL(a, DoA(6)).After(e1, e2, e3, es1, es2);
1675
1676
a.DoA(5);
1677
a.DoA(2);
1678
a.DoA(4);
1679
a.DoA(1);
1680
a.DoA(3);
1681
a.DoA(6);
1682
}
1683
1684
// .After() allows input to contain duplicated Expectations.
1685
TEST(AfterTest, AcceptsDuplicatedInput) {
1686
MockA a;
1687
ON_CALL(a, ReturnResult(_)).WillByDefault(Return(Result()));
1688
1689
// Define ordering:
1690
// DoA(1) ==>
1691
// DoA(2) ==> ReturnResult(3)
1692
Expectation e1 = EXPECT_CALL(a, DoA(1));
1693
Expectation e2 = EXPECT_CALL(a, DoA(2));
1694
ExpectationSet es;
1695
es += e1;
1696
es += e2;
1697
EXPECT_CALL(a, ReturnResult(3)).After(e1, e2, es, e1);
1698
1699
a.DoA(1);
1700
1701
// May only be after DoA(2).
1702
EXPECT_NONFATAL_FAILURE(a.ReturnResult(3), "Unexpected mock function call");
1703
1704
a.DoA(2);
1705
a.ReturnResult(3);
1706
}
1707
1708
// An Expectation added to an ExpectationSet after it has been used in
1709
// an .After() has no effect.
1710
TEST(AfterTest, ChangesToExpectationSetHaveNoEffectAfterwards) {
1711
MockA a;
1712
ExpectationSet es1 = EXPECT_CALL(a, DoA(1));
1713
Expectation e2 = EXPECT_CALL(a, DoA(2));
1714
EXPECT_CALL(a, DoA(3)).After(es1);
1715
es1 += e2;
1716
1717
a.DoA(1);
1718
a.DoA(3);
1719
a.DoA(2);
1720
}
1721
1722
// Tests that Google Mock correctly handles calls to mock functions
1723
// after a mock object owning one of their pre-requisites has died.
1724
1725
// Tests that calls that satisfy the original spec are successful.
1726
TEST(DeletingMockEarlyTest, Success1) {
1727
MockB* const b1 = new MockB;
1728
MockA* const a = new MockA;
1729
MockB* const b2 = new MockB;
1730
1731
{
1732
InSequence dummy;
1733
EXPECT_CALL(*b1, DoB(_)).WillOnce(Return(1));
1734
EXPECT_CALL(*a, Binary(_, _))
1735
.Times(AnyNumber())
1736
.WillRepeatedly(Return(true));
1737
EXPECT_CALL(*b2, DoB(_)).Times(AnyNumber()).WillRepeatedly(Return(2));
1738
}
1739
1740
EXPECT_EQ(1, b1->DoB(1));
1741
delete b1;
1742
// a's pre-requisite has died.
1743
EXPECT_TRUE(a->Binary(0, 1));
1744
delete b2;
1745
// a's successor has died.
1746
EXPECT_TRUE(a->Binary(1, 2));
1747
delete a;
1748
}
1749
1750
// Tests that calls that satisfy the original spec are successful.
1751
TEST(DeletingMockEarlyTest, Success2) {
1752
MockB* const b1 = new MockB;
1753
MockA* const a = new MockA;
1754
MockB* const b2 = new MockB;
1755
1756
{
1757
InSequence dummy;
1758
EXPECT_CALL(*b1, DoB(_)).WillOnce(Return(1));
1759
EXPECT_CALL(*a, Binary(_, _)).Times(AnyNumber());
1760
EXPECT_CALL(*b2, DoB(_)).Times(AnyNumber()).WillRepeatedly(Return(2));
1761
}
1762
1763
delete a; // a is trivially satisfied.
1764
EXPECT_EQ(1, b1->DoB(1));
1765
EXPECT_EQ(2, b2->DoB(2));
1766
delete b1;
1767
delete b2;
1768
}
1769
1770
// Tests that it's OK to delete a mock object itself in its action.
1771
1772
// Suppresses warning on unreferenced formal parameter in MSVC with
1773
// -W4.
1774
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4100)
1775
1776
ACTION_P(Delete, ptr) { delete ptr; }
1777
1778
GTEST_DISABLE_MSC_WARNINGS_POP_() // 4100
1779
1780
TEST(DeletingMockEarlyTest, CanDeleteSelfInActionReturningVoid) {
1781
MockA* const a = new MockA;
1782
EXPECT_CALL(*a, DoA(_)).WillOnce(Delete(a));
1783
a->DoA(42); // This will cause a to be deleted.
1784
}
1785
1786
TEST(DeletingMockEarlyTest, CanDeleteSelfInActionReturningValue) {
1787
MockA* const a = new MockA;
1788
EXPECT_CALL(*a, ReturnResult(_)).WillOnce(DoAll(Delete(a), Return(Result())));
1789
a->ReturnResult(42); // This will cause a to be deleted.
1790
}
1791
1792
// Tests that calls that violate the original spec yield failures.
1793
TEST(DeletingMockEarlyTest, Failure1) {
1794
MockB* const b1 = new MockB;
1795
MockA* const a = new MockA;
1796
MockB* const b2 = new MockB;
1797
1798
{
1799
InSequence dummy;
1800
EXPECT_CALL(*b1, DoB(_)).WillOnce(Return(1));
1801
EXPECT_CALL(*a, Binary(_, _)).Times(AnyNumber());
1802
EXPECT_CALL(*b2, DoB(_)).Times(AnyNumber()).WillRepeatedly(Return(2));
1803
}
1804
1805
delete a; // a is trivially satisfied.
1806
EXPECT_NONFATAL_FAILURE({ b2->DoB(2); }, "Unexpected mock function call");
1807
EXPECT_EQ(1, b1->DoB(1));
1808
delete b1;
1809
delete b2;
1810
}
1811
1812
// Tests that calls that violate the original spec yield failures.
1813
TEST(DeletingMockEarlyTest, Failure2) {
1814
MockB* const b1 = new MockB;
1815
MockA* const a = new MockA;
1816
MockB* const b2 = new MockB;
1817
1818
{
1819
InSequence dummy;
1820
EXPECT_CALL(*b1, DoB(_));
1821
EXPECT_CALL(*a, Binary(_, _)).Times(AnyNumber());
1822
EXPECT_CALL(*b2, DoB(_)).Times(AnyNumber());
1823
}
1824
1825
EXPECT_NONFATAL_FAILURE(delete b1, "Actual: never called");
1826
EXPECT_NONFATAL_FAILURE(a->Binary(0, 1), "Unexpected mock function call");
1827
EXPECT_NONFATAL_FAILURE(b2->DoB(1), "Unexpected mock function call");
1828
delete a;
1829
delete b2;
1830
}
1831
1832
class EvenNumberCardinality : public CardinalityInterface {
1833
public:
1834
// Returns true if and only if call_count calls will satisfy this
1835
// cardinality.
1836
bool IsSatisfiedByCallCount(int call_count) const override {
1837
return call_count % 2 == 0;
1838
}
1839
1840
// Returns true if and only if call_count calls will saturate this
1841
// cardinality.
1842
bool IsSaturatedByCallCount(int /* call_count */) const override {
1843
return false;
1844
}
1845
1846
// Describes self to an ostream.
1847
void DescribeTo(::std::ostream* os) const override {
1848
*os << "called even number of times";
1849
}
1850
};
1851
1852
Cardinality EvenNumber() { return Cardinality(new EvenNumberCardinality); }
1853
1854
TEST(ExpectationBaseTest,
1855
AllPrerequisitesAreSatisfiedWorksForNonMonotonicCardinality) {
1856
MockA* a = new MockA;
1857
Sequence s;
1858
1859
EXPECT_CALL(*a, DoA(1)).Times(EvenNumber()).InSequence(s);
1860
EXPECT_CALL(*a, DoA(2)).Times(AnyNumber()).InSequence(s);
1861
EXPECT_CALL(*a, DoA(3)).Times(AnyNumber());
1862
1863
a->DoA(3);
1864
a->DoA(1);
1865
EXPECT_NONFATAL_FAILURE(a->DoA(2), "Unexpected mock function call");
1866
EXPECT_NONFATAL_FAILURE(delete a, "to be called even number of times");
1867
}
1868
1869
// The following tests verify the message generated when a mock
1870
// function is called.
1871
1872
struct Printable {};
1873
1874
inline void operator<<(::std::ostream& os, const Printable&) {
1875
os << "Printable";
1876
}
1877
1878
struct Unprintable {
1879
Unprintable() : value(0) {}
1880
int value;
1881
};
1882
1883
class MockC {
1884
public:
1885
MockC() = default;
1886
1887
MOCK_METHOD6(VoidMethod, void(bool cond, int n, std::string s, void* p,
1888
const Printable& x, Unprintable y));
1889
MOCK_METHOD0(NonVoidMethod, int()); // NOLINT
1890
1891
private:
1892
MockC(const MockC&) = delete;
1893
MockC& operator=(const MockC&) = delete;
1894
};
1895
1896
class VerboseFlagPreservingFixture : public testing::Test {
1897
protected:
1898
VerboseFlagPreservingFixture()
1899
: saved_verbose_flag_(GMOCK_FLAG_GET(verbose)) {}
1900
1901
~VerboseFlagPreservingFixture() override {
1902
GMOCK_FLAG_SET(verbose, saved_verbose_flag_);
1903
}
1904
1905
private:
1906
const std::string saved_verbose_flag_;
1907
1908
VerboseFlagPreservingFixture(const VerboseFlagPreservingFixture&) = delete;
1909
VerboseFlagPreservingFixture& operator=(const VerboseFlagPreservingFixture&) =
1910
delete;
1911
};
1912
1913
#if GTEST_HAS_STREAM_REDIRECTION
1914
1915
// Tests that an uninteresting mock function call on a naggy mock
1916
// generates a warning without the stack trace when
1917
// --gmock_verbose=warning is specified.
1918
TEST(FunctionCallMessageTest,
1919
UninterestingCallOnNaggyMockGeneratesNoStackTraceWhenVerboseWarning) {
1920
GMOCK_FLAG_SET(verbose, kWarningVerbosity);
1921
NaggyMock<MockC> c;
1922
CaptureStdout();
1923
c.VoidMethod(false, 5, "Hi", nullptr, Printable(), Unprintable());
1924
const std::string output = GetCapturedStdout();
1925
EXPECT_PRED_FORMAT2(IsSubstring, "GMOCK WARNING", output);
1926
EXPECT_PRED_FORMAT2(IsNotSubstring, "Stack trace:", output);
1927
}
1928
1929
// Tests that an uninteresting mock function call on a naggy mock
1930
// generates a warning containing the stack trace when
1931
// --gmock_verbose=info is specified.
1932
TEST(FunctionCallMessageTest,
1933
UninterestingCallOnNaggyMockGeneratesFyiWithStackTraceWhenVerboseInfo) {
1934
GMOCK_FLAG_SET(verbose, kInfoVerbosity);
1935
NaggyMock<MockC> c;
1936
CaptureStdout();
1937
c.VoidMethod(false, 5, "Hi", nullptr, Printable(), Unprintable());
1938
const std::string output = GetCapturedStdout();
1939
EXPECT_PRED_FORMAT2(IsSubstring, "GMOCK WARNING", output);
1940
EXPECT_PRED_FORMAT2(IsSubstring, "Stack trace:", output);
1941
1942
#ifndef NDEBUG
1943
1944
// We check the stack trace content in dbg-mode only, as opt-mode
1945
// may inline the call we are interested in seeing.
1946
1947
// Verifies that a void mock function's name appears in the stack
1948
// trace.
1949
EXPECT_PRED_FORMAT2(IsSubstring, "VoidMethod(", output);
1950
1951
// Verifies that a non-void mock function's name appears in the
1952
// stack trace.
1953
CaptureStdout();
1954
c.NonVoidMethod();
1955
const std::string output2 = GetCapturedStdout();
1956
EXPECT_PRED_FORMAT2(IsSubstring, "NonVoidMethod(", output2);
1957
1958
#endif // NDEBUG
1959
}
1960
1961
// Tests that an uninteresting mock function call on a naggy mock
1962
// causes the function arguments and return value to be printed.
1963
TEST(FunctionCallMessageTest,
1964
UninterestingCallOnNaggyMockPrintsArgumentsAndReturnValue) {
1965
// A non-void mock function.
1966
NaggyMock<MockB> b;
1967
CaptureStdout();
1968
b.DoB();
1969
const std::string output1 = GetCapturedStdout();
1970
EXPECT_PRED_FORMAT2(
1971
IsSubstring,
1972
"Uninteresting mock function call - returning default value.\n"
1973
" Function call: DoB()\n"
1974
" Returns: 0\n",
1975
output1.c_str());
1976
// Makes sure the return value is printed.
1977
1978
// A void mock function.
1979
NaggyMock<MockC> c;
1980
CaptureStdout();
1981
c.VoidMethod(false, 5, "Hi", nullptr, Printable(), Unprintable());
1982
const std::string output2 = GetCapturedStdout();
1983
EXPECT_THAT(
1984
output2.c_str(),
1985
ContainsRegex("Uninteresting mock function call - returning directly\\.\n"
1986
" Function call: VoidMethod"
1987
"\\(false, 5, \"Hi\", NULL, @.+ "
1988
"Printable, 4-byte object <00-00 00-00>\\)"));
1989
// A void function has no return value to print.
1990
}
1991
1992
// Tests how the --gmock_verbose flag affects Google Mock's output.
1993
1994
class GMockVerboseFlagTest : public VerboseFlagPreservingFixture {
1995
public:
1996
// Verifies that the given Google Mock output is correct. (When
1997
// should_print is true, the output should match the given regex and
1998
// contain the given function name in the stack trace. When it's
1999
// false, the output should be empty.)
2000
void VerifyOutput(const std::string& output, bool should_print,
2001
const std::string& expected_substring,
2002
const std::string& function_name) {
2003
if (should_print) {
2004
EXPECT_THAT(output.c_str(), HasSubstr(expected_substring));
2005
#ifndef NDEBUG
2006
// We check the stack trace content in dbg-mode only, as opt-mode
2007
// may inline the call we are interested in seeing.
2008
EXPECT_THAT(output.c_str(), HasSubstr(function_name));
2009
#else
2010
// Suppresses 'unused function parameter' warnings.
2011
static_cast<void>(function_name);
2012
#endif // NDEBUG
2013
} else {
2014
EXPECT_STREQ("", output.c_str());
2015
}
2016
}
2017
2018
// Tests how the flag affects expected calls.
2019
void TestExpectedCall(bool should_print) {
2020
MockA a;
2021
EXPECT_CALL(a, DoA(5));
2022
EXPECT_CALL(a, Binary(_, 1)).WillOnce(Return(true));
2023
2024
// A void-returning function.
2025
CaptureStdout();
2026
a.DoA(5);
2027
VerifyOutput(GetCapturedStdout(), should_print,
2028
"Mock function call matches EXPECT_CALL(a, DoA(5))...\n"
2029
" Function call: DoA(5)\n"
2030
"Stack trace:\n",
2031
"DoA");
2032
2033
// A non-void-returning function.
2034
CaptureStdout();
2035
a.Binary(2, 1);
2036
VerifyOutput(GetCapturedStdout(), should_print,
2037
"Mock function call matches EXPECT_CALL(a, Binary(_, 1))...\n"
2038
" Function call: Binary(2, 1)\n"
2039
" Returns: true\n"
2040
"Stack trace:\n",
2041
"Binary");
2042
}
2043
2044
// Tests how the flag affects uninteresting calls on a naggy mock.
2045
void TestUninterestingCallOnNaggyMock(bool should_print) {
2046
NaggyMock<MockA> a;
2047
const std::string note =
2048
"NOTE: You can safely ignore the above warning unless this "
2049
"call should not happen. Do not suppress it by blindly adding "
2050
"an EXPECT_CALL() if you don't mean to enforce the call. "
2051
"See "
2052
"https://github.com/google/googletest/blob/main/docs/"
2053
"gmock_cook_book.md#"
2054
"knowing-when-to-expect-useoncall for details.";
2055
2056
// A void-returning function.
2057
CaptureStdout();
2058
a.DoA(5);
2059
VerifyOutput(GetCapturedStdout(), should_print,
2060
"\nGMOCK WARNING:\n"
2061
"Uninteresting mock function call - returning directly.\n"
2062
" Function call: DoA(5)\n" +
2063
note,
2064
"DoA");
2065
2066
// A non-void-returning function.
2067
CaptureStdout();
2068
a.Binary(2, 1);
2069
VerifyOutput(GetCapturedStdout(), should_print,
2070
"\nGMOCK WARNING:\n"
2071
"Uninteresting mock function call - returning default value.\n"
2072
" Function call: Binary(2, 1)\n"
2073
" Returns: false\n" +
2074
note,
2075
"Binary");
2076
}
2077
};
2078
2079
// Tests that --gmock_verbose=info causes both expected and
2080
// uninteresting calls to be reported.
2081
TEST_F(GMockVerboseFlagTest, Info) {
2082
GMOCK_FLAG_SET(verbose, kInfoVerbosity);
2083
TestExpectedCall(true);
2084
TestUninterestingCallOnNaggyMock(true);
2085
}
2086
2087
// Tests that --gmock_verbose=warning causes uninteresting calls to be
2088
// reported.
2089
TEST_F(GMockVerboseFlagTest, Warning) {
2090
GMOCK_FLAG_SET(verbose, kWarningVerbosity);
2091
TestExpectedCall(false);
2092
TestUninterestingCallOnNaggyMock(true);
2093
}
2094
2095
// Tests that --gmock_verbose=warning causes neither expected nor
2096
// uninteresting calls to be reported.
2097
TEST_F(GMockVerboseFlagTest, Error) {
2098
GMOCK_FLAG_SET(verbose, kErrorVerbosity);
2099
TestExpectedCall(false);
2100
TestUninterestingCallOnNaggyMock(false);
2101
}
2102
2103
// Tests that --gmock_verbose=SOME_INVALID_VALUE has the same effect
2104
// as --gmock_verbose=warning.
2105
TEST_F(GMockVerboseFlagTest, InvalidFlagIsTreatedAsWarning) {
2106
GMOCK_FLAG_SET(verbose, "invalid"); // Treated as "warning".
2107
TestExpectedCall(false);
2108
TestUninterestingCallOnNaggyMock(true);
2109
}
2110
2111
#endif // GTEST_HAS_STREAM_REDIRECTION
2112
2113
// A helper class that generates a failure when printed. We use it to
2114
// ensure that Google Mock doesn't print a value (even to an internal
2115
// buffer) when it is not supposed to do so.
2116
class PrintMeNot {};
2117
2118
void PrintTo(PrintMeNot /* dummy */, ::std::ostream* /* os */) {
2119
ADD_FAILURE() << "Google Mock is printing a value that shouldn't be "
2120
<< "printed even to an internal buffer.";
2121
}
2122
2123
class LogTestHelper {
2124
public:
2125
LogTestHelper() = default;
2126
2127
MOCK_METHOD1(Foo, PrintMeNot(PrintMeNot));
2128
2129
private:
2130
LogTestHelper(const LogTestHelper&) = delete;
2131
LogTestHelper& operator=(const LogTestHelper&) = delete;
2132
};
2133
2134
class GMockLogTest : public VerboseFlagPreservingFixture {
2135
protected:
2136
LogTestHelper helper_;
2137
};
2138
2139
TEST_F(GMockLogTest, DoesNotPrintGoodCallInternallyIfVerbosityIsWarning) {
2140
GMOCK_FLAG_SET(verbose, kWarningVerbosity);
2141
EXPECT_CALL(helper_, Foo(_)).WillOnce(Return(PrintMeNot()));
2142
helper_.Foo(PrintMeNot()); // This is an expected call.
2143
}
2144
2145
TEST_F(GMockLogTest, DoesNotPrintGoodCallInternallyIfVerbosityIsError) {
2146
GMOCK_FLAG_SET(verbose, kErrorVerbosity);
2147
EXPECT_CALL(helper_, Foo(_)).WillOnce(Return(PrintMeNot()));
2148
helper_.Foo(PrintMeNot()); // This is an expected call.
2149
}
2150
2151
TEST_F(GMockLogTest, DoesNotPrintWarningInternallyIfVerbosityIsError) {
2152
GMOCK_FLAG_SET(verbose, kErrorVerbosity);
2153
ON_CALL(helper_, Foo(_)).WillByDefault(Return(PrintMeNot()));
2154
helper_.Foo(PrintMeNot()); // This should generate a warning.
2155
}
2156
2157
// Tests Mock::AllowLeak().
2158
2159
TEST(AllowLeakTest, AllowsLeakingUnusedMockObject) {
2160
MockA* a = new MockA;
2161
Mock::AllowLeak(a);
2162
}
2163
2164
TEST(AllowLeakTest, CanBeCalledBeforeOnCall) {
2165
MockA* a = new MockA;
2166
Mock::AllowLeak(a);
2167
ON_CALL(*a, DoA(_)).WillByDefault(Return());
2168
a->DoA(0);
2169
}
2170
2171
TEST(AllowLeakTest, CanBeCalledAfterOnCall) {
2172
MockA* a = new MockA;
2173
ON_CALL(*a, DoA(_)).WillByDefault(Return());
2174
Mock::AllowLeak(a);
2175
}
2176
2177
TEST(AllowLeakTest, CanBeCalledBeforeExpectCall) {
2178
MockA* a = new MockA;
2179
Mock::AllowLeak(a);
2180
EXPECT_CALL(*a, DoA(_));
2181
a->DoA(0);
2182
}
2183
2184
TEST(AllowLeakTest, CanBeCalledAfterExpectCall) {
2185
MockA* a = new MockA;
2186
EXPECT_CALL(*a, DoA(_)).Times(AnyNumber());
2187
Mock::AllowLeak(a);
2188
}
2189
2190
TEST(AllowLeakTest, WorksWhenBothOnCallAndExpectCallArePresent) {
2191
MockA* a = new MockA;
2192
ON_CALL(*a, DoA(_)).WillByDefault(Return());
2193
EXPECT_CALL(*a, DoA(_)).Times(AnyNumber());
2194
Mock::AllowLeak(a);
2195
}
2196
2197
// Tests that we can verify and clear a mock object's expectations
2198
// when none of its methods has expectations.
2199
TEST(VerifyAndClearExpectationsTest, NoMethodHasExpectations) {
2200
MockB b;
2201
ASSERT_TRUE(Mock::VerifyAndClearExpectations(&b));
2202
2203
// There should be no expectations on the methods now, so we can
2204
// freely call them.
2205
EXPECT_EQ(0, b.DoB());
2206
EXPECT_EQ(0, b.DoB(1));
2207
}
2208
2209
// Tests that we can verify and clear a mock object's expectations
2210
// when some, but not all, of its methods have expectations *and* the
2211
// verification succeeds.
2212
TEST(VerifyAndClearExpectationsTest, SomeMethodsHaveExpectationsAndSucceed) {
2213
MockB b;
2214
EXPECT_CALL(b, DoB()).WillOnce(Return(1));
2215
b.DoB();
2216
ASSERT_TRUE(Mock::VerifyAndClearExpectations(&b));
2217
2218
// There should be no expectations on the methods now, so we can
2219
// freely call them.
2220
EXPECT_EQ(0, b.DoB());
2221
EXPECT_EQ(0, b.DoB(1));
2222
}
2223
2224
// Tests that we can verify and clear a mock object's expectations
2225
// when some, but not all, of its methods have expectations *and* the
2226
// verification fails.
2227
TEST(VerifyAndClearExpectationsTest, SomeMethodsHaveExpectationsAndFail) {
2228
MockB b;
2229
EXPECT_CALL(b, DoB()).WillOnce(Return(1));
2230
bool result = true;
2231
EXPECT_NONFATAL_FAILURE(result = Mock::VerifyAndClearExpectations(&b),
2232
"Actual: never called");
2233
ASSERT_FALSE(result);
2234
2235
// There should be no expectations on the methods now, so we can
2236
// freely call them.
2237
EXPECT_EQ(0, b.DoB());
2238
EXPECT_EQ(0, b.DoB(1));
2239
}
2240
2241
// Tests that we can verify and clear a mock object's expectations
2242
// when all of its methods have expectations.
2243
TEST(VerifyAndClearExpectationsTest, AllMethodsHaveExpectations) {
2244
MockB b;
2245
EXPECT_CALL(b, DoB()).WillOnce(Return(1));
2246
EXPECT_CALL(b, DoB(_)).WillOnce(Return(2));
2247
b.DoB();
2248
b.DoB(1);
2249
ASSERT_TRUE(Mock::VerifyAndClearExpectations(&b));
2250
2251
// There should be no expectations on the methods now, so we can
2252
// freely call them.
2253
EXPECT_EQ(0, b.DoB());
2254
EXPECT_EQ(0, b.DoB(1));
2255
}
2256
2257
// Tests that we can verify and clear a mock object's expectations
2258
// when a method has more than one expectation.
2259
TEST(VerifyAndClearExpectationsTest, AMethodHasManyExpectations) {
2260
MockB b;
2261
EXPECT_CALL(b, DoB(0)).WillOnce(Return(1));
2262
EXPECT_CALL(b, DoB(_)).WillOnce(Return(2));
2263
b.DoB(1);
2264
bool result = true;
2265
EXPECT_NONFATAL_FAILURE(result = Mock::VerifyAndClearExpectations(&b),
2266
"Actual: never called");
2267
ASSERT_FALSE(result);
2268
2269
// There should be no expectations on the methods now, so we can
2270
// freely call them.
2271
EXPECT_EQ(0, b.DoB());
2272
EXPECT_EQ(0, b.DoB(1));
2273
}
2274
2275
// Tests that we can call VerifyAndClearExpectations() on the same
2276
// mock object multiple times.
2277
TEST(VerifyAndClearExpectationsTest, CanCallManyTimes) {
2278
MockB b;
2279
EXPECT_CALL(b, DoB());
2280
b.DoB();
2281
Mock::VerifyAndClearExpectations(&b);
2282
2283
EXPECT_CALL(b, DoB(_)).WillOnce(Return(1));
2284
b.DoB(1);
2285
Mock::VerifyAndClearExpectations(&b);
2286
Mock::VerifyAndClearExpectations(&b);
2287
2288
// There should be no expectations on the methods now, so we can
2289
// freely call them.
2290
EXPECT_EQ(0, b.DoB());
2291
EXPECT_EQ(0, b.DoB(1));
2292
}
2293
2294
// Tests that we can clear a mock object's default actions when none
2295
// of its methods has default actions.
2296
TEST(VerifyAndClearTest, NoMethodHasDefaultActions) {
2297
MockB b;
2298
// If this crashes or generates a failure, the test will catch it.
2299
Mock::VerifyAndClear(&b);
2300
EXPECT_EQ(0, b.DoB());
2301
}
2302
2303
// Tests that we can clear a mock object's default actions when some,
2304
// but not all of its methods have default actions.
2305
TEST(VerifyAndClearTest, SomeMethodsHaveDefaultActions) {
2306
MockB b;
2307
ON_CALL(b, DoB()).WillByDefault(Return(1));
2308
2309
Mock::VerifyAndClear(&b);
2310
2311
// Verifies that the default action of int DoB() was removed.
2312
EXPECT_EQ(0, b.DoB());
2313
}
2314
2315
// Tests that we can clear a mock object's default actions when all of
2316
// its methods have default actions.
2317
TEST(VerifyAndClearTest, AllMethodsHaveDefaultActions) {
2318
MockB b;
2319
ON_CALL(b, DoB()).WillByDefault(Return(1));
2320
ON_CALL(b, DoB(_)).WillByDefault(Return(2));
2321
2322
Mock::VerifyAndClear(&b);
2323
2324
// Verifies that the default action of int DoB() was removed.
2325
EXPECT_EQ(0, b.DoB());
2326
2327
// Verifies that the default action of int DoB(int) was removed.
2328
EXPECT_EQ(0, b.DoB(0));
2329
}
2330
2331
// Tests that we can clear a mock object's default actions when a
2332
// method has more than one ON_CALL() set on it.
2333
TEST(VerifyAndClearTest, AMethodHasManyDefaultActions) {
2334
MockB b;
2335
ON_CALL(b, DoB(0)).WillByDefault(Return(1));
2336
ON_CALL(b, DoB(_)).WillByDefault(Return(2));
2337
2338
Mock::VerifyAndClear(&b);
2339
2340
// Verifies that the default actions (there are two) of int DoB(int)
2341
// were removed.
2342
EXPECT_EQ(0, b.DoB(0));
2343
EXPECT_EQ(0, b.DoB(1));
2344
}
2345
2346
// Tests that we can call VerifyAndClear() on a mock object multiple
2347
// times.
2348
TEST(VerifyAndClearTest, CanCallManyTimes) {
2349
MockB b;
2350
ON_CALL(b, DoB()).WillByDefault(Return(1));
2351
Mock::VerifyAndClear(&b);
2352
Mock::VerifyAndClear(&b);
2353
2354
ON_CALL(b, DoB(_)).WillByDefault(Return(1));
2355
Mock::VerifyAndClear(&b);
2356
2357
EXPECT_EQ(0, b.DoB());
2358
EXPECT_EQ(0, b.DoB(1));
2359
}
2360
2361
// Tests that VerifyAndClear() works when the verification succeeds.
2362
TEST(VerifyAndClearTest, Success) {
2363
MockB b;
2364
ON_CALL(b, DoB()).WillByDefault(Return(1));
2365
EXPECT_CALL(b, DoB(1)).WillOnce(Return(2));
2366
2367
b.DoB();
2368
b.DoB(1);
2369
ASSERT_TRUE(Mock::VerifyAndClear(&b));
2370
2371
// There should be no expectations on the methods now, so we can
2372
// freely call them.
2373
EXPECT_EQ(0, b.DoB());
2374
EXPECT_EQ(0, b.DoB(1));
2375
}
2376
2377
// Tests that VerifyAndClear() works when the verification fails.
2378
TEST(VerifyAndClearTest, Failure) {
2379
MockB b;
2380
ON_CALL(b, DoB(_)).WillByDefault(Return(1));
2381
EXPECT_CALL(b, DoB()).WillOnce(Return(2));
2382
2383
b.DoB(1);
2384
bool result = true;
2385
EXPECT_NONFATAL_FAILURE(result = Mock::VerifyAndClear(&b),
2386
"Actual: never called");
2387
ASSERT_FALSE(result);
2388
2389
// There should be no expectations on the methods now, so we can
2390
// freely call them.
2391
EXPECT_EQ(0, b.DoB());
2392
EXPECT_EQ(0, b.DoB(1));
2393
}
2394
2395
// Tests that VerifyAndClear() works when the default actions and
2396
// expectations are set on a const mock object.
2397
TEST(VerifyAndClearTest, Const) {
2398
MockB b;
2399
ON_CALL(Const(b), DoB()).WillByDefault(Return(1));
2400
2401
EXPECT_CALL(Const(b), DoB()).WillOnce(DoDefault()).WillOnce(Return(2));
2402
2403
b.DoB();
2404
b.DoB();
2405
ASSERT_TRUE(Mock::VerifyAndClear(&b));
2406
2407
// There should be no expectations on the methods now, so we can
2408
// freely call them.
2409
EXPECT_EQ(0, b.DoB());
2410
EXPECT_EQ(0, b.DoB(1));
2411
}
2412
2413
// Tests that we can set default actions and expectations on a mock
2414
// object after VerifyAndClear() has been called on it.
2415
TEST(VerifyAndClearTest, CanSetDefaultActionsAndExpectationsAfterwards) {
2416
MockB b;
2417
ON_CALL(b, DoB()).WillByDefault(Return(1));
2418
EXPECT_CALL(b, DoB(_)).WillOnce(Return(2));
2419
b.DoB(1);
2420
2421
Mock::VerifyAndClear(&b);
2422
2423
EXPECT_CALL(b, DoB()).WillOnce(Return(3));
2424
ON_CALL(b, DoB(_)).WillByDefault(Return(4));
2425
2426
EXPECT_EQ(3, b.DoB());
2427
EXPECT_EQ(4, b.DoB(1));
2428
}
2429
2430
// Tests that calling VerifyAndClear() on one mock object does not
2431
// affect other mock objects (either of the same type or not).
2432
TEST(VerifyAndClearTest, DoesNotAffectOtherMockObjects) {
2433
MockA a;
2434
MockB b1;
2435
MockB b2;
2436
2437
ON_CALL(a, Binary(_, _)).WillByDefault(Return(true));
2438
EXPECT_CALL(a, Binary(_, _)).WillOnce(DoDefault()).WillOnce(Return(false));
2439
2440
ON_CALL(b1, DoB()).WillByDefault(Return(1));
2441
EXPECT_CALL(b1, DoB(_)).WillOnce(Return(2));
2442
2443
ON_CALL(b2, DoB()).WillByDefault(Return(3));
2444
EXPECT_CALL(b2, DoB(_));
2445
2446
b2.DoB(0);
2447
Mock::VerifyAndClear(&b2);
2448
2449
// Verifies that the default actions and expectations of a and b1
2450
// are still in effect.
2451
EXPECT_TRUE(a.Binary(0, 0));
2452
EXPECT_FALSE(a.Binary(0, 0));
2453
2454
EXPECT_EQ(1, b1.DoB());
2455
EXPECT_EQ(2, b1.DoB(0));
2456
}
2457
2458
TEST(VerifyAndClearTest,
2459
DestroyingChainedMocksDoesNotDeadlockThroughExpectations) {
2460
std::shared_ptr<MockA> a(new MockA);
2461
ReferenceHoldingMock test_mock;
2462
2463
// EXPECT_CALL stores a reference to a inside test_mock.
2464
EXPECT_CALL(test_mock, AcceptReference(_))
2465
.WillRepeatedly(SetArgPointee<0>(a));
2466
2467
// Throw away the reference to the mock that we have in a. After this, the
2468
// only reference to it is stored by test_mock.
2469
a.reset();
2470
2471
// When test_mock goes out of scope, it destroys the last remaining reference
2472
// to the mock object originally pointed to by a. This will cause the MockA
2473
// destructor to be called from inside the ReferenceHoldingMock destructor.
2474
// The state of all mocks is protected by a single global lock, but there
2475
// should be no deadlock.
2476
}
2477
2478
TEST(VerifyAndClearTest,
2479
DestroyingChainedMocksDoesNotDeadlockThroughDefaultAction) {
2480
std::shared_ptr<MockA> a(new MockA);
2481
ReferenceHoldingMock test_mock;
2482
2483
// ON_CALL stores a reference to a inside test_mock.
2484
ON_CALL(test_mock, AcceptReference(_)).WillByDefault(SetArgPointee<0>(a));
2485
2486
// Throw away the reference to the mock that we have in a. After this, the
2487
// only reference to it is stored by test_mock.
2488
a.reset();
2489
2490
// When test_mock goes out of scope, it destroys the last remaining reference
2491
// to the mock object originally pointed to by a. This will cause the MockA
2492
// destructor to be called from inside the ReferenceHoldingMock destructor.
2493
// The state of all mocks is protected by a single global lock, but there
2494
// should be no deadlock.
2495
}
2496
2497
// Tests that a mock function's action can call a mock function
2498
// (either the same function or a different one) either as an explicit
2499
// action or as a default action without causing a dead lock. It
2500
// verifies that the action is not performed inside the critical
2501
// section.
2502
TEST(SynchronizationTest, CanCallMockMethodInAction) {
2503
MockA a;
2504
MockC c;
2505
ON_CALL(a, DoA(_)).WillByDefault(
2506
IgnoreResult(InvokeWithoutArgs(&c, &MockC::NonVoidMethod)));
2507
EXPECT_CALL(a, DoA(1));
2508
EXPECT_CALL(a, DoA(1))
2509
.WillOnce(Invoke(&a, &MockA::DoA))
2510
.RetiresOnSaturation();
2511
EXPECT_CALL(c, NonVoidMethod());
2512
2513
a.DoA(1);
2514
// This will match the second EXPECT_CALL() and trigger another a.DoA(1),
2515
// which will in turn match the first EXPECT_CALL() and trigger a call to
2516
// c.NonVoidMethod() that was specified by the ON_CALL() since the first
2517
// EXPECT_CALL() did not specify an action.
2518
}
2519
2520
TEST(ParameterlessExpectationsTest, CanSetExpectationsWithoutMatchers) {
2521
MockA a;
2522
int do_a_arg0 = 0;
2523
ON_CALL(a, DoA).WillByDefault(SaveArg<0>(&do_a_arg0));
2524
int do_a_47_arg0 = 0;
2525
ON_CALL(a, DoA(47)).WillByDefault(SaveArg<0>(&do_a_47_arg0));
2526
2527
a.DoA(17);
2528
EXPECT_THAT(do_a_arg0, 17);
2529
EXPECT_THAT(do_a_47_arg0, 0);
2530
a.DoA(47);
2531
EXPECT_THAT(do_a_arg0, 17);
2532
EXPECT_THAT(do_a_47_arg0, 47);
2533
2534
ON_CALL(a, Binary).WillByDefault(Return(true));
2535
ON_CALL(a, Binary(_, 14)).WillByDefault(Return(false));
2536
EXPECT_THAT(a.Binary(14, 17), true);
2537
EXPECT_THAT(a.Binary(17, 14), false);
2538
}
2539
2540
TEST(ParameterlessExpectationsTest, CanSetExpectationsForOverloadedMethods) {
2541
MockB b;
2542
ON_CALL(b, DoB()).WillByDefault(Return(9));
2543
ON_CALL(b, DoB(5)).WillByDefault(Return(11));
2544
2545
EXPECT_THAT(b.DoB(), 9);
2546
EXPECT_THAT(b.DoB(1), 0); // default value
2547
EXPECT_THAT(b.DoB(5), 11);
2548
}
2549
2550
struct MockWithConstMethods {
2551
public:
2552
MOCK_CONST_METHOD1(Foo, int(int));
2553
MOCK_CONST_METHOD2(Bar, int(int, const char*));
2554
};
2555
2556
TEST(ParameterlessExpectationsTest, CanSetExpectationsForConstMethods) {
2557
MockWithConstMethods mock;
2558
ON_CALL(mock, Foo).WillByDefault(Return(7));
2559
ON_CALL(mock, Bar).WillByDefault(Return(33));
2560
2561
EXPECT_THAT(mock.Foo(17), 7);
2562
EXPECT_THAT(mock.Bar(27, "purple"), 33);
2563
}
2564
2565
class MockConstOverload {
2566
public:
2567
MOCK_METHOD1(Overloaded, int(int));
2568
MOCK_CONST_METHOD1(Overloaded, int(int));
2569
};
2570
2571
TEST(ParameterlessExpectationsTest,
2572
CanSetExpectationsForConstOverloadedMethods) {
2573
MockConstOverload mock;
2574
ON_CALL(mock, Overloaded(_)).WillByDefault(Return(7));
2575
ON_CALL(mock, Overloaded(5)).WillByDefault(Return(9));
2576
ON_CALL(Const(mock), Overloaded(5)).WillByDefault(Return(11));
2577
ON_CALL(Const(mock), Overloaded(7)).WillByDefault(Return(13));
2578
2579
EXPECT_THAT(mock.Overloaded(1), 7);
2580
EXPECT_THAT(mock.Overloaded(5), 9);
2581
EXPECT_THAT(mock.Overloaded(7), 7);
2582
2583
const MockConstOverload& const_mock = mock;
2584
EXPECT_THAT(const_mock.Overloaded(1), 0);
2585
EXPECT_THAT(const_mock.Overloaded(5), 11);
2586
EXPECT_THAT(const_mock.Overloaded(7), 13);
2587
}
2588
2589
} // namespace
2590
} // namespace testing
2591
2592
int main(int argc, char** argv) {
2593
testing::InitGoogleMock(&argc, argv);
2594
// Ensures that the tests pass no matter what value of
2595
// --gmock_catch_leaked_mocks and --gmock_verbose the user specifies.
2596
GMOCK_FLAG_SET(catch_leaked_mocks, true);
2597
GMOCK_FLAG_SET(verbose, testing::internal::kWarningVerbosity);
2598
2599
return RUN_ALL_TESTS();
2600
}
2601
2602