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