blob: 3e27aa847bd954f63fa398c9363acbafa7566fee [file] [log] [blame]
shiqiane35fdd92008-12-10 05:08:54 +00001// 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// Author: wan@google.com (Zhanyong Wan)
31
32// Google Mock - a framework for writing C++ mock classes.
33//
34// This file tests the spec builder syntax.
35
36#include <gmock/gmock-spec-builders.h>
37
38#include <ostream> // NOLINT
39#include <sstream>
40#include <string>
41
42#include <gmock/gmock.h>
43#include <gmock/internal/gmock-port.h>
44#include <gtest/gtest.h>
45#include <gtest/gtest-spi.h>
46
47namespace testing {
48namespace internal {
49
50// Helper class for testing the Expectation class template.
51class ExpectationTester {
52 public:
53 // Sets the call count of the given expectation to the given number.
54 void SetCallCount(int n, ExpectationBase* exp) {
55 exp->call_count_ = n;
56 }
57};
58
59} // namespace internal
60} // namespace testing
61
62namespace {
63
64using testing::_;
65using testing::AnyNumber;
66using testing::AtLeast;
67using testing::AtMost;
68using testing::Between;
69using testing::Cardinality;
70using testing::CardinalityInterface;
71using testing::Const;
72using testing::DoAll;
73using testing::DoDefault;
74using testing::GMOCK_FLAG(verbose);
75using testing::InSequence;
76using testing::Invoke;
77using testing::InvokeWithoutArgs;
78using testing::IsSubstring;
79using testing::Lt;
80using testing::Message;
81using testing::Mock;
82using testing::Return;
83using testing::Sequence;
84using testing::internal::g_gmock_mutex;
85using testing::internal::kErrorVerbosity;
86using testing::internal::kInfoVerbosity;
87using testing::internal::kWarningVerbosity;
88using testing::internal::Expectation;
89using testing::internal::ExpectationTester;
90using testing::internal::string;
91
92class Result {};
93
94class MockA {
95 public:
96 MOCK_METHOD1(DoA, void(int n)); // NOLINT
97 MOCK_METHOD1(ReturnResult, Result(int n)); // NOLINT
98 MOCK_METHOD2(Binary, bool(int x, int y)); // NOLINT
99};
100
101class MockB {
102 public:
103 MOCK_CONST_METHOD0(DoB, int()); // NOLINT
104 MOCK_METHOD1(DoB, int(int n)); // NOLINT
105};
106
107// Tests that EXPECT_CALL and ON_CALL compile in a presence of macro
108// redefining a mock method name. This could happen, for example, when
109// the tested code #includes Win32 API headers which define many APIs
110// as macros, e.g. #define TextOut TextOutW.
111
112#define Method MethodW
113
114class CC {
115 public:
116 virtual ~CC() {}
117 virtual int Method() = 0;
118};
119class MockCC : public CC {
120 public:
121 MOCK_METHOD0(Method, int());
122};
123
124// Tests that a method with expanded name compiles.
125TEST(OnCallSyntaxTest, CompilesWithMethodNameExpandedFromMacro) {
126 MockCC cc;
127 ON_CALL(cc, Method());
128}
129
130// Tests that the method with expanded name not only compiles but runs
131// and returns a correct value, too.
132TEST(OnCallSyntaxTest, WorksWithMethodNameExpandedFromMacro) {
133 MockCC cc;
134 ON_CALL(cc, Method()).WillByDefault(Return(42));
135 EXPECT_EQ(42, cc.Method());
136}
137
138// Tests that a method with expanded name compiles.
139TEST(ExpectCallSyntaxTest, CompilesWithMethodNameExpandedFromMacro) {
140 MockCC cc;
141 EXPECT_CALL(cc, Method());
142 cc.Method();
143}
144
145// Tests that it works, too.
146TEST(ExpectCallSyntaxTest, WorksWithMethodNameExpandedFromMacro) {
147 MockCC cc;
148 EXPECT_CALL(cc, Method()).WillOnce(Return(42));
149 EXPECT_EQ(42, cc.Method());
150}
151
152#undef Method // Done with macro redefinition tests.
153
154// Tests that ON_CALL evaluates its arguments exactly once as promised
155// by Google Mock.
156TEST(OnCallSyntaxTest, EvaluatesFirstArgumentOnce) {
157 MockA a;
158 MockA* pa = &a;
159
160 ON_CALL(*pa++, DoA(_));
161 EXPECT_EQ(&a + 1, pa);
162}
163
164TEST(OnCallSyntaxTest, EvaluatesSecondArgumentOnce) {
165 MockA a;
166 int n = 0;
167
168 ON_CALL(a, DoA(n++));
169 EXPECT_EQ(1, n);
170}
171
172// Tests that the syntax of ON_CALL() is enforced at run time.
173
174TEST(OnCallSyntaxTest, WithArgumentsIsOptional) {
175 MockA a;
176
177 ON_CALL(a, DoA(5))
178 .WillByDefault(Return());
179 ON_CALL(a, DoA(_))
180 .WithArguments(_)
181 .WillByDefault(Return());
182}
183
184TEST(OnCallSyntaxTest, WithArgumentsCanAppearAtMostOnce) {
185 MockA a;
186
187 EXPECT_NONFATAL_FAILURE({ // NOLINT
188 ON_CALL(a, ReturnResult(_))
189 .WithArguments(_)
190 .WithArguments(_)
191 .WillByDefault(Return(Result()));
192 }, ".WithArguments() cannot appear more than once in an ON_CALL()");
193}
194
195#ifdef GTEST_HAS_DEATH_TEST
196
197TEST(OnCallSyntaxTest, WillByDefaultIsMandatory) {
198 MockA a;
199
200 EXPECT_DEATH({ // NOLINT
201 ON_CALL(a, DoA(5));
202 a.DoA(5);
203 }, "");
204}
205
206#endif // GTEST_HAS_DEATH_TEST
207
208TEST(OnCallSyntaxTest, WillByDefaultCanAppearAtMostOnce) {
209 MockA a;
210
211 EXPECT_NONFATAL_FAILURE({ // NOLINT
212 ON_CALL(a, DoA(5))
213 .WillByDefault(Return())
214 .WillByDefault(Return());
215 }, ".WillByDefault() must appear exactly once in an ON_CALL()");
216}
217
218// Tests that EXPECT_CALL evaluates its arguments exactly once as
219// promised by Google Mock.
220TEST(ExpectCallSyntaxTest, EvaluatesFirstArgumentOnce) {
221 MockA a;
222 MockA* pa = &a;
223
224 EXPECT_CALL(*pa++, DoA(_));
225 a.DoA(0);
226 EXPECT_EQ(&a + 1, pa);
227}
228
229TEST(ExpectCallSyntaxTest, EvaluatesSecondArgumentOnce) {
230 MockA a;
231 int n = 0;
232
233 EXPECT_CALL(a, DoA(n++));
234 a.DoA(0);
235 EXPECT_EQ(1, n);
236}
237
238// Tests that the syntax of EXPECT_CALL() is enforced at run time.
239
240TEST(ExpectCallSyntaxTest, WithArgumentsIsOptional) {
241 MockA a;
242
243 EXPECT_CALL(a, DoA(5))
244 .Times(0);
245 EXPECT_CALL(a, DoA(6))
246 .WithArguments(_)
247 .Times(0);
248}
249
250TEST(ExpectCallSyntaxTest, WithArgumentsCanAppearAtMostOnce) {
251 MockA a;
252
253 EXPECT_NONFATAL_FAILURE({ // NOLINT
254 EXPECT_CALL(a, DoA(6))
255 .WithArguments(_)
256 .WithArguments(_);
257 }, ".WithArguments() cannot appear more than once in "
258 "an EXPECT_CALL()");
259
260 a.DoA(6);
261}
262
263TEST(ExpectCallSyntaxTest, WithArgumentsMustBeFirstClause) {
264 MockA a;
265
266 EXPECT_NONFATAL_FAILURE({ // NOLINT
267 EXPECT_CALL(a, DoA(1))
268 .Times(1)
269 .WithArguments(_);
270 }, ".WithArguments() must be the first clause in an "
271 "EXPECT_CALL()");
272
273 a.DoA(1);
274
275 EXPECT_NONFATAL_FAILURE({ // NOLINT
276 EXPECT_CALL(a, DoA(2))
277 .WillOnce(Return())
278 .WithArguments(_);
279 }, ".WithArguments() must be the first clause in an "
280 "EXPECT_CALL()");
281
282 a.DoA(2);
283}
284
285TEST(ExpectCallSyntaxTest, TimesCanBeInferred) {
286 MockA a;
287
288 EXPECT_CALL(a, DoA(1))
289 .WillOnce(Return());
290
291 EXPECT_CALL(a, DoA(2))
292 .WillOnce(Return())
293 .WillRepeatedly(Return());
294
295 a.DoA(1);
296 a.DoA(2);
297 a.DoA(2);
298}
299
300TEST(ExpectCallSyntaxTest, TimesCanAppearAtMostOnce) {
301 MockA a;
302
303 EXPECT_NONFATAL_FAILURE({ // NOLINT
304 EXPECT_CALL(a, DoA(1))
305 .Times(1)
306 .Times(2);
307 }, ".Times() cannot appear more than once in an EXPECT_CALL()");
308
309 a.DoA(1);
310 a.DoA(1);
311}
312
313TEST(ExpectCallSyntaxTest, TimesMustBeBeforeInSequence) {
314 MockA a;
315 Sequence s;
316
317 EXPECT_NONFATAL_FAILURE({ // NOLINT
318 EXPECT_CALL(a, DoA(1))
319 .InSequence(s)
320 .Times(1);
321 }, ".Times() cannot appear after ");
322
323 a.DoA(1);
324}
325
326TEST(ExpectCallSyntaxTest, InSequenceIsOptional) {
327 MockA a;
328 Sequence s;
329
330 EXPECT_CALL(a, DoA(1));
331 EXPECT_CALL(a, DoA(2))
332 .InSequence(s);
333
334 a.DoA(1);
335 a.DoA(2);
336}
337
338TEST(ExpectCallSyntaxTest, InSequenceCanAppearMultipleTimes) {
339 MockA a;
340 Sequence s1, s2;
341
342 EXPECT_CALL(a, DoA(1))
343 .InSequence(s1, s2)
344 .InSequence(s1);
345
346 a.DoA(1);
347}
348
349TEST(ExpectCallSyntaxTest, InSequenceMustBeBeforeWill) {
350 MockA a;
351 Sequence s;
352
353 EXPECT_NONFATAL_FAILURE({ // NOLINT
354 EXPECT_CALL(a, DoA(1))
355 .WillOnce(Return())
356 .InSequence(s);
357 }, ".InSequence() cannot appear after ");
358
359 a.DoA(1);
360}
361
362TEST(ExpectCallSyntaxTest, WillIsOptional) {
363 MockA a;
364
365 EXPECT_CALL(a, DoA(1));
366 EXPECT_CALL(a, DoA(2))
367 .WillOnce(Return());
368
369 a.DoA(1);
370 a.DoA(2);
371}
372
373TEST(ExpectCallSyntaxTest, WillCanAppearMultipleTimes) {
374 MockA a;
375
376 EXPECT_CALL(a, DoA(1))
377 .Times(AnyNumber())
378 .WillOnce(Return())
379 .WillOnce(Return())
380 .WillOnce(Return());
381}
382
383TEST(ExpectCallSyntaxTest, WillMustBeBeforeWillRepeatedly) {
384 MockA a;
385
386 EXPECT_NONFATAL_FAILURE({ // NOLINT
387 EXPECT_CALL(a, DoA(1))
388 .WillRepeatedly(Return())
389 .WillOnce(Return());
390 }, ".WillOnce() cannot appear after ");
391
392 a.DoA(1);
393}
394
395TEST(ExpectCallSyntaxTest, WillRepeatedlyIsOptional) {
396 MockA a;
397
398 EXPECT_CALL(a, DoA(1))
399 .WillOnce(Return());
400 EXPECT_CALL(a, DoA(2))
401 .WillOnce(Return())
402 .WillRepeatedly(Return());
403
404 a.DoA(1);
405 a.DoA(2);
406 a.DoA(2);
407}
408
409TEST(ExpectCallSyntaxTest, WillRepeatedlyCannotAppearMultipleTimes) {
410 MockA a;
411
412 EXPECT_NONFATAL_FAILURE({ // NOLINT
413 EXPECT_CALL(a, DoA(1))
414 .WillRepeatedly(Return())
415 .WillRepeatedly(Return());
416 }, ".WillRepeatedly() cannot appear more than once in an "
417 "EXPECT_CALL()");
418}
419
420TEST(ExpectCallSyntaxTest, WillRepeatedlyMustBeBeforeRetiresOnSaturation) {
421 MockA a;
422
423 EXPECT_NONFATAL_FAILURE({ // NOLINT
424 EXPECT_CALL(a, DoA(1))
425 .RetiresOnSaturation()
426 .WillRepeatedly(Return());
427 }, ".WillRepeatedly() cannot appear after ");
428}
429
430TEST(ExpectCallSyntaxTest, RetiresOnSaturationIsOptional) {
431 MockA a;
432
433 EXPECT_CALL(a, DoA(1));
434 EXPECT_CALL(a, DoA(1))
435 .RetiresOnSaturation();
436
437 a.DoA(1);
438 a.DoA(1);
439}
440
441TEST(ExpectCallSyntaxTest, RetiresOnSaturationCannotAppearMultipleTimes) {
442 MockA a;
443
444 EXPECT_NONFATAL_FAILURE({ // NOLINT
445 EXPECT_CALL(a, DoA(1))
446 .RetiresOnSaturation()
447 .RetiresOnSaturation();
448 }, ".RetiresOnSaturation() cannot appear more than once");
449
450 a.DoA(1);
451}
452
453TEST(ExpectCallSyntaxTest, DefaultCardinalityIsOnce) {
454 {
455 MockA a;
456 EXPECT_CALL(a, DoA(1));
457 a.DoA(1);
458 }
459 EXPECT_NONFATAL_FAILURE({ // NOLINT
460 MockA a;
461 EXPECT_CALL(a, DoA(1));
462 }, "to be called once");
463 EXPECT_NONFATAL_FAILURE({ // NOLINT
464 MockA a;
465 EXPECT_CALL(a, DoA(1));
466 a.DoA(1);
467 a.DoA(1);
468 }, "to be called once");
469}
470
471// TODO(wan@google.com): find a way to re-enable these tests.
472#if 0
473
474// Tests that Google Mock doesn't print a warning when the number of
475// WillOnce() is adequate.
476TEST(ExpectCallSyntaxTest, DoesNotWarnOnAdequateActionCount) {
477 CaptureTestStdout();
478 {
479 MockB b;
480
481 // It's always fine to omit WillOnce() entirely.
482 EXPECT_CALL(b, DoB())
483 .Times(0);
484 EXPECT_CALL(b, DoB(1))
485 .Times(AtMost(1));
486 EXPECT_CALL(b, DoB(2))
487 .Times(1)
488 .WillRepeatedly(Return(1));
489
490 // It's fine for the number of WillOnce()s to equal the upper bound.
491 EXPECT_CALL(b, DoB(3))
492 .Times(Between(1, 2))
493 .WillOnce(Return(1))
494 .WillOnce(Return(2));
495
496 // It's fine for the number of WillOnce()s to be smaller than the
497 // upper bound when there is a WillRepeatedly().
498 EXPECT_CALL(b, DoB(4))
499 .Times(AtMost(3))
500 .WillOnce(Return(1))
501 .WillRepeatedly(Return(2));
502
503 // Satisfies the above expectations.
504 b.DoB(2);
505 b.DoB(3);
506 }
507 const string& output = GetCapturedTestStdout();
508 EXPECT_EQ("", output);
509}
510
511// Tests that Google Mock warns on having too many actions in an
512// expectation compared to its cardinality.
513TEST(ExpectCallSyntaxTest, WarnsOnTooManyActions) {
514 CaptureTestStdout();
515 {
516 MockB b;
517
518 // Warns when the number of WillOnce()s is larger than the upper bound.
519 EXPECT_CALL(b, DoB())
520 .Times(0)
521 .WillOnce(Return(1)); // #1
522 EXPECT_CALL(b, DoB())
523 .Times(AtMost(1))
524 .WillOnce(Return(1))
525 .WillOnce(Return(2)); // #2
526 EXPECT_CALL(b, DoB(1))
527 .Times(1)
528 .WillOnce(Return(1))
529 .WillOnce(Return(2))
530 .RetiresOnSaturation(); // #3
531
532 // Warns when the number of WillOnce()s equals the upper bound and
533 // there is a WillRepeatedly().
534 EXPECT_CALL(b, DoB())
535 .Times(0)
536 .WillRepeatedly(Return(1)); // #4
537 EXPECT_CALL(b, DoB(2))
538 .Times(1)
539 .WillOnce(Return(1))
540 .WillRepeatedly(Return(2)); // #5
541
542 // Satisfies the above expectations.
543 b.DoB(1);
544 b.DoB(2);
545 }
546 const string& output = GetCapturedTestStdout();
547 EXPECT_PRED_FORMAT2(IsSubstring,
548 "Too many actions specified.\n"
549 "Expected to be never called, but has 1 WillOnce().",
550 output); // #1
551 EXPECT_PRED_FORMAT2(IsSubstring,
552 "Too many actions specified.\n"
553 "Expected to be called at most once, "
554 "but has 2 WillOnce()s.",
555 output); // #2
556 EXPECT_PRED_FORMAT2(IsSubstring,
557 "Too many actions specified.\n"
558 "Expected to be called once, but has 2 WillOnce()s.",
559 output); // #3
560 EXPECT_PRED_FORMAT2(IsSubstring,
561 "Too many actions specified.\n"
562 "Expected to be never called, but has 0 WillOnce()s "
563 "and a WillRepeatedly().",
564 output); // #4
565 EXPECT_PRED_FORMAT2(IsSubstring,
566 "Too many actions specified.\n"
567 "Expected to be called once, but has 1 WillOnce() "
568 "and a WillRepeatedly().",
569 output); // #5
570}
571
572// Tests that Google Mock warns on having too few actions in an
573// expectation compared to its cardinality.
574TEST(ExpectCallSyntaxTest, WarnsOnTooFewActions) {
575 MockB b;
576
577 EXPECT_CALL(b, DoB())
578 .Times(Between(2, 3))
579 .WillOnce(Return(1));
580
581 CaptureTestStdout();
582 b.DoB();
583 const string& output = GetCapturedTestStdout();
584 EXPECT_PRED_FORMAT2(IsSubstring,
585 "Too few actions specified.\n"
586 "Expected to be called between 2 and 3 times, "
587 "but has only 1 WillOnce().",
588 output);
589 b.DoB();
590}
591
592#endif // 0
593
594// Tests the semantics of ON_CALL().
595
596// Tests that the built-in default action is taken when no ON_CALL()
597// is specified.
598TEST(OnCallTest, TakesBuiltInDefaultActionWhenNoOnCall) {
599 MockB b;
600 EXPECT_CALL(b, DoB());
601
602 EXPECT_EQ(0, b.DoB());
603}
604
605// Tests that the built-in default action is taken when no ON_CALL()
606// matches the invocation.
607TEST(OnCallTest, TakesBuiltInDefaultActionWhenNoOnCallMatches) {
608 MockB b;
609 ON_CALL(b, DoB(1))
610 .WillByDefault(Return(1));
611 EXPECT_CALL(b, DoB(_));
612
613 EXPECT_EQ(0, b.DoB(2));
614}
615
616// Tests that the last matching ON_CALL() action is taken.
617TEST(OnCallTest, PicksLastMatchingOnCall) {
618 MockB b;
619 ON_CALL(b, DoB(_))
620 .WillByDefault(Return(3));
621 ON_CALL(b, DoB(2))
622 .WillByDefault(Return(2));
623 ON_CALL(b, DoB(1))
624 .WillByDefault(Return(1));
625 EXPECT_CALL(b, DoB(_));
626
627 EXPECT_EQ(2, b.DoB(2));
628}
629
630// Tests the semantics of EXPECT_CALL().
631
632// Tests that any call is allowed when no EXPECT_CALL() is specified.
633TEST(ExpectCallTest, AllowsAnyCallWhenNoSpec) {
634 MockB b;
635 EXPECT_CALL(b, DoB());
636 // There is no expectation on DoB(int).
637
638 b.DoB();
639
640 // DoB(int) can be called any number of times.
641 b.DoB(1);
642 b.DoB(2);
643}
644
645// Tests that the last matching EXPECT_CALL() fires.
646TEST(ExpectCallTest, PicksLastMatchingExpectCall) {
647 MockB b;
648 EXPECT_CALL(b, DoB(_))
649 .WillRepeatedly(Return(2));
650 EXPECT_CALL(b, DoB(1))
651 .WillRepeatedly(Return(1));
652
653 EXPECT_EQ(1, b.DoB(1));
654}
655
656// Tests lower-bound violation.
657TEST(ExpectCallTest, CatchesTooFewCalls) {
658 EXPECT_NONFATAL_FAILURE({ // NOLINT
659 MockB b;
660 EXPECT_CALL(b, DoB(5))
661 .Times(AtLeast(2));
662
663 b.DoB(5);
664 }, "Actual function call count doesn't match this expectation.\n"
665 " Expected: to be called at least twice\n"
666 " Actual: called once - unsatisfied and active");
667}
668
669// Tests that the cardinality can be inferred when no Times(...) is
670// specified.
671TEST(ExpectCallTest, InfersCardinalityWhenThereIsNoWillRepeatedly) {
672 {
673 MockB b;
674 EXPECT_CALL(b, DoB())
675 .WillOnce(Return(1))
676 .WillOnce(Return(2));
677
678 EXPECT_EQ(1, b.DoB());
679 EXPECT_EQ(2, b.DoB());
680 }
681
682 EXPECT_NONFATAL_FAILURE({ // NOLINT
683 MockB b;
684 EXPECT_CALL(b, DoB())
685 .WillOnce(Return(1))
686 .WillOnce(Return(2));
687
688 EXPECT_EQ(1, b.DoB());
689 }, "to be called twice");
690
691 { // NOLINT
692 MockB b;
693 EXPECT_CALL(b, DoB())
694 .WillOnce(Return(1))
695 .WillOnce(Return(2));
696
697 EXPECT_EQ(1, b.DoB());
698 EXPECT_EQ(2, b.DoB());
699 EXPECT_NONFATAL_FAILURE(b.DoB(), "to be called twice");
700 }
701}
702
703TEST(ExpectCallTest, InfersCardinality1WhenThereIsWillRepeatedly) {
704 {
705 MockB b;
706 EXPECT_CALL(b, DoB())
707 .WillOnce(Return(1))
708 .WillRepeatedly(Return(2));
709
710 EXPECT_EQ(1, b.DoB());
711 }
712
713 { // NOLINT
714 MockB b;
715 EXPECT_CALL(b, DoB())
716 .WillOnce(Return(1))
717 .WillRepeatedly(Return(2));
718
719 EXPECT_EQ(1, b.DoB());
720 EXPECT_EQ(2, b.DoB());
721 EXPECT_EQ(2, b.DoB());
722 }
723
724 EXPECT_NONFATAL_FAILURE({ // NOLINT
725 MockB b;
726 EXPECT_CALL(b, DoB())
727 .WillOnce(Return(1))
728 .WillRepeatedly(Return(2));
729 }, "to be called at least once");
730}
731
732// Tests that the n-th action is taken for the n-th matching
733// invocation.
734TEST(ExpectCallTest, NthMatchTakesNthAction) {
735 MockB b;
736 EXPECT_CALL(b, DoB())
737 .WillOnce(Return(1))
738 .WillOnce(Return(2))
739 .WillOnce(Return(3));
740
741 EXPECT_EQ(1, b.DoB());
742 EXPECT_EQ(2, b.DoB());
743 EXPECT_EQ(3, b.DoB());
744}
745
746// TODO(wan@google.com): find a way to re-enable these tests.
747#if 0
748
749// Tests that the default action is taken when the WillOnce(...) list is
750// exhausted and there is no WillRepeatedly().
751TEST(ExpectCallTest, TakesDefaultActionWhenWillListIsExhausted) {
752 MockB b;
753 EXPECT_CALL(b, DoB(_))
754 .Times(1);
755 EXPECT_CALL(b, DoB())
756 .Times(AnyNumber())
757 .WillOnce(Return(1))
758 .WillOnce(Return(2));
759
760 CaptureTestStdout();
761 EXPECT_EQ(0, b.DoB(1)); // Shouldn't generate a warning as the
762 // expectation has no action clause at all.
763 EXPECT_EQ(1, b.DoB());
764 EXPECT_EQ(2, b.DoB());
765 const string& output1 = GetCapturedTestStdout();
766 EXPECT_EQ("", output1);
767
768 CaptureTestStdout();
769 EXPECT_EQ(0, b.DoB());
770 EXPECT_EQ(0, b.DoB());
771 const string& output2 = GetCapturedTestStdout();
772 EXPECT_PRED2(RE::PartialMatch, output2,
773 "Actions ran out\\.\n"
774 "Called 3 times, but only 2 WillOnce\\(\\)s are specified - "
775 "returning default value\\.");
776 EXPECT_PRED2(RE::PartialMatch, output2,
777 "Actions ran out\\.\n"
778 "Called 4 times, but only 2 WillOnce\\(\\)s are specified - "
779 "returning default value\\.");
780}
781
782#endif // 0
783
784// Tests that the WillRepeatedly() action is taken when the WillOnce(...)
785// list is exhausted.
786TEST(ExpectCallTest, TakesRepeatedActionWhenWillListIsExhausted) {
787 MockB b;
788 EXPECT_CALL(b, DoB())
789 .WillOnce(Return(1))
790 .WillRepeatedly(Return(2));
791
792 EXPECT_EQ(1, b.DoB());
793 EXPECT_EQ(2, b.DoB());
794 EXPECT_EQ(2, b.DoB());
795}
796
797// Tests that an uninteresting call performs the default action.
798TEST(UninterestingCallTest, DoesDefaultAction) {
799 // When there is an ON_CALL() statement, the action specified by it
800 // should be taken.
801 MockA a;
802 ON_CALL(a, Binary(_, _))
803 .WillByDefault(Return(true));
804 EXPECT_TRUE(a.Binary(1, 2));
805
806 // When there is no ON_CALL(), the default value for the return type
807 // should be returned.
808 MockB b;
809 EXPECT_EQ(0, b.DoB());
810}
811
812// Tests that an unexpected call performs the default action.
813TEST(UnexpectedCallTest, DoesDefaultAction) {
814 // When there is an ON_CALL() statement, the action specified by it
815 // should be taken.
816 MockA a;
817 ON_CALL(a, Binary(_, _))
818 .WillByDefault(Return(true));
819 EXPECT_CALL(a, Binary(0, 0));
820 a.Binary(0, 0);
821 bool result = false;
822 EXPECT_NONFATAL_FAILURE(result = a.Binary(1, 2),
823 "Unexpected mock function call");
824 EXPECT_TRUE(result);
825
826 // When there is no ON_CALL(), the default value for the return type
827 // should be returned.
828 MockB b;
829 EXPECT_CALL(b, DoB(0))
830 .Times(0);
831 int n = -1;
832 EXPECT_NONFATAL_FAILURE(n = b.DoB(1),
833 "Unexpected mock function call");
834 EXPECT_EQ(0, n);
835}
836
837// Tests that when an unexpected void function generates the right
838// failure message.
839TEST(UnexpectedCallTest, GeneratesFailureForVoidFunction) {
840 // First, tests the message when there is only one EXPECT_CALL().
841 MockA a1;
842 EXPECT_CALL(a1, DoA(1));
843 a1.DoA(1);
844 // Ideally we should match the failure message against a regex, but
845 // EXPECT_NONFATAL_FAILURE doesn't support that, so we test for
846 // multiple sub-strings instead.
847 EXPECT_NONFATAL_FAILURE(
848 a1.DoA(9),
849 "Unexpected mock function call - returning directly.\n"
850 " Function call: DoA(9)\n"
851 "Google Mock tried the following 1 expectation, but it didn't match:");
852 EXPECT_NONFATAL_FAILURE(
853 a1.DoA(9),
854 " Expected arg #0: is equal to 1\n"
855 " Actual: 9\n"
856 " Expected: to be called once\n"
857 " Actual: called once - saturated and active");
858
859 // Next, tests the message when there are more than one EXPECT_CALL().
860 MockA a2;
861 EXPECT_CALL(a2, DoA(1));
862 EXPECT_CALL(a2, DoA(3));
863 a2.DoA(1);
864 EXPECT_NONFATAL_FAILURE(
865 a2.DoA(2),
866 "Unexpected mock function call - returning directly.\n"
867 " Function call: DoA(2)\n"
868 "Google Mock tried the following 2 expectations, but none matched:");
869 EXPECT_NONFATAL_FAILURE(
870 a2.DoA(2),
871 "tried expectation #0\n"
872 " Expected arg #0: is equal to 1\n"
873 " Actual: 2\n"
874 " Expected: to be called once\n"
875 " Actual: called once - saturated and active");
876 EXPECT_NONFATAL_FAILURE(
877 a2.DoA(2),
878 "tried expectation #1\n"
879 " Expected arg #0: is equal to 3\n"
880 " Actual: 2\n"
881 " Expected: to be called once\n"
882 " Actual: never called - unsatisfied and active");
883 a2.DoA(3);
884}
885
886// Tests that an unexpected non-void function generates the right
887// failure message.
888TEST(UnexpectedCallTest, GeneartesFailureForNonVoidFunction) {
889 MockB b1;
890 EXPECT_CALL(b1, DoB(1));
891 b1.DoB(1);
892 EXPECT_NONFATAL_FAILURE(
893 b1.DoB(2),
894 "Unexpected mock function call - returning default value.\n"
895 " Function call: DoB(2)\n"
896 " Returns: 0\n"
897 "Google Mock tried the following 1 expectation, but it didn't match:");
898 EXPECT_NONFATAL_FAILURE(
899 b1.DoB(2),
900 " Expected arg #0: is equal to 1\n"
901 " Actual: 2\n"
902 " Expected: to be called once\n"
903 " Actual: called once - saturated and active");
904}
905
906// Tests that Google Mock explains that an retired expectation doesn't
907// match the call.
908TEST(UnexpectedCallTest, RetiredExpectation) {
909 MockB b;
910 EXPECT_CALL(b, DoB(1))
911 .RetiresOnSaturation();
912
913 b.DoB(1);
914 EXPECT_NONFATAL_FAILURE(
915 b.DoB(1),
916 " Expected: the expectation is active\n"
917 " Actual: it is retired");
918}
919
920// Tests that Google Mock explains that an expectation that doesn't
921// match the arguments doesn't match the call.
922TEST(UnexpectedCallTest, UnmatchedArguments) {
923 MockB b;
924 EXPECT_CALL(b, DoB(1));
925
926 EXPECT_NONFATAL_FAILURE(
927 b.DoB(2),
928 " Expected arg #0: is equal to 1\n"
929 " Actual: 2\n");
930 b.DoB(1);
931}
932
933#ifdef GMOCK_HAS_REGEX
934
935// Tests that Google Mock explains that an expectation with
936// unsatisfied pre-requisites doesn't match the call.
937TEST(UnexpectedCallTest, UnsatisifiedPrerequisites) {
938 Sequence s1, s2;
939 MockB b;
940 EXPECT_CALL(b, DoB(1))
941 .InSequence(s1);
942 EXPECT_CALL(b, DoB(2))
943 .Times(AnyNumber())
944 .InSequence(s1);
945 EXPECT_CALL(b, DoB(3))
946 .InSequence(s2);
947 EXPECT_CALL(b, DoB(4))
948 .InSequence(s1, s2);
949
950 ::testing::TestPartResultArray failures;
951 {
952 ::testing::ScopedFakeTestPartResultReporter reporter(&failures);
953 b.DoB(4);
954 // Now 'failures' contains the Google Test failures generated by
955 // the above statement.
956 }
957
958 // There should be one non-fatal failure.
959 ASSERT_EQ(1, failures.size());
960 const ::testing::TestPartResult& r = failures.GetTestPartResult(0);
961 EXPECT_EQ(::testing::TPRT_NONFATAL_FAILURE, r.type());
962
963 // Verifies that the failure message contains the two unsatisfied
964 // pre-requisites but not the satisfied one.
965 const char* const pattern =
966#if GMOCK_USES_PCRE
967 // PCRE has trouble using (.|\n) to match any character, but
968 // supports the (?s) prefix for using . to match any character.
969 "(?s)the following immediate pre-requisites are not satisfied:\n"
970 ".*: pre-requisite #0\n"
971 ".*: pre-requisite #1";
972#else
973 // POSIX RE doesn't understand the (?s) prefix, but has no trouble
974 // with (.|\n).
975 "the following immediate pre-requisites are not satisfied:\n"
976 "(.|\n)*: pre-requisite #0\n"
977 "(.|\n)*: pre-requisite #1";
978#endif // GMOCK_USES_PCRE
979
980 EXPECT_TRUE(
981 ::testing::internal::RE::PartialMatch(r.message(), pattern))
982 << " where the message is " << r.message();
983 b.DoB(1);
984 b.DoB(3);
985 b.DoB(4);
986}
987
988#endif // GMOCK_HAS_REGEX
989
990// Tests that an excessive call (one whose arguments match the
991// matchers but is called too many times) performs the default action.
992TEST(ExcessiveCallTest, DoesDefaultAction) {
993 // When there is an ON_CALL() statement, the action specified by it
994 // should be taken.
995 MockA a;
996 ON_CALL(a, Binary(_, _))
997 .WillByDefault(Return(true));
998 EXPECT_CALL(a, Binary(0, 0));
999 a.Binary(0, 0);
1000 bool result = false;
1001 EXPECT_NONFATAL_FAILURE(result = a.Binary(0, 0),
1002 "Mock function called more times than expected");
1003 EXPECT_TRUE(result);
1004
1005 // When there is no ON_CALL(), the default value for the return type
1006 // should be returned.
1007 MockB b;
1008 EXPECT_CALL(b, DoB(0))
1009 .Times(0);
1010 int n = -1;
1011 EXPECT_NONFATAL_FAILURE(n = b.DoB(0),
1012 "Mock function called more times than expected");
1013 EXPECT_EQ(0, n);
1014}
1015
1016// Tests that when a void function is called too many times,
1017// the failure message contains the argument values.
1018TEST(ExcessiveCallTest, GeneratesFailureForVoidFunction) {
1019 MockA a;
1020 EXPECT_CALL(a, DoA(_))
1021 .Times(0);
1022 EXPECT_NONFATAL_FAILURE(
1023 a.DoA(9),
1024 "Mock function called more times than expected - returning directly.\n"
1025 " Function call: DoA(9)\n"
1026 " Expected: to be never called\n"
1027 " Actual: called once - over-saturated and active");
1028}
1029
1030// Tests that when a non-void function is called too many times, the
1031// failure message contains the argument values and the return value.
1032TEST(ExcessiveCallTest, GeneratesFailureForNonVoidFunction) {
1033 MockB b;
1034 EXPECT_CALL(b, DoB(_));
1035 b.DoB(1);
1036 EXPECT_NONFATAL_FAILURE(
1037 b.DoB(2),
1038 "Mock function called more times than expected - "
1039 "returning default value.\n"
1040 " Function call: DoB(2)\n"
1041 " Returns: 0\n"
1042 " Expected: to be called once\n"
1043 " Actual: called twice - over-saturated and active");
1044}
1045
1046// Tests using sequences.
1047
1048TEST(InSequenceTest, AllExpectationInScopeAreInSequence) {
1049 MockA a;
1050 {
1051 InSequence dummy;
1052
1053 EXPECT_CALL(a, DoA(1));
1054 EXPECT_CALL(a, DoA(2));
1055 }
1056
1057 EXPECT_NONFATAL_FAILURE({ // NOLINT
1058 a.DoA(2);
1059 }, "Unexpected mock function call");
1060
1061 a.DoA(1);
1062 a.DoA(2);
1063}
1064
1065TEST(InSequenceTest, NestedInSequence) {
1066 MockA a;
1067 {
1068 InSequence dummy;
1069
1070 EXPECT_CALL(a, DoA(1));
1071 {
1072 InSequence dummy2;
1073
1074 EXPECT_CALL(a, DoA(2));
1075 EXPECT_CALL(a, DoA(3));
1076 }
1077 }
1078
1079 EXPECT_NONFATAL_FAILURE({ // NOLINT
1080 a.DoA(1);
1081 a.DoA(3);
1082 }, "Unexpected mock function call");
1083
1084 a.DoA(2);
1085 a.DoA(3);
1086}
1087
1088TEST(InSequenceTest, ExpectationsOutOfScopeAreNotAffected) {
1089 MockA a;
1090 {
1091 InSequence dummy;
1092
1093 EXPECT_CALL(a, DoA(1));
1094 EXPECT_CALL(a, DoA(2));
1095 }
1096 EXPECT_CALL(a, DoA(3));
1097
1098 EXPECT_NONFATAL_FAILURE({ // NOLINT
1099 a.DoA(2);
1100 }, "Unexpected mock function call");
1101
1102 a.DoA(3);
1103 a.DoA(1);
1104 a.DoA(2);
1105}
1106
1107// Tests that any order is allowed when no sequence is used.
1108TEST(SequenceTest, AnyOrderIsOkByDefault) {
1109 {
1110 MockA a;
1111 MockB b;
1112
1113 EXPECT_CALL(a, DoA(1));
1114 EXPECT_CALL(b, DoB())
1115 .Times(AnyNumber());
1116
1117 a.DoA(1);
1118 b.DoB();
1119 }
1120
1121 { // NOLINT
1122 MockA a;
1123 MockB b;
1124
1125 EXPECT_CALL(a, DoA(1));
1126 EXPECT_CALL(b, DoB())
1127 .Times(AnyNumber());
1128
1129 b.DoB();
1130 a.DoA(1);
1131 }
1132}
1133
1134#ifdef GTEST_HAS_DEATH_TEST
1135
1136// Tests that the calls must be in strict order when a complete order
1137// is specified.
1138TEST(SequenceTest, CallsMustBeInStrictOrderWhenSaidSo) {
1139 MockA a;
1140 Sequence s;
1141
1142 EXPECT_CALL(a, ReturnResult(1))
1143 .InSequence(s)
1144 .WillOnce(Return(Result()));
1145
1146 EXPECT_CALL(a, ReturnResult(2))
1147 .InSequence(s)
1148 .WillOnce(Return(Result()));
1149
1150 EXPECT_CALL(a, ReturnResult(3))
1151 .InSequence(s)
1152 .WillOnce(Return(Result()));
1153
1154 EXPECT_DEATH({ // NOLINT
1155 a.ReturnResult(1);
1156 a.ReturnResult(3);
1157 a.ReturnResult(2);
1158 }, "");
1159
1160 EXPECT_DEATH({ // NOLINT
1161 a.ReturnResult(2);
1162 a.ReturnResult(1);
1163 a.ReturnResult(3);
1164 }, "");
1165
1166 a.ReturnResult(1);
1167 a.ReturnResult(2);
1168 a.ReturnResult(3);
1169}
1170
1171// Tests specifying a DAG using multiple sequences.
1172TEST(SequenceTest, CallsMustConformToSpecifiedDag) {
1173 MockA a;
1174 MockB b;
1175 Sequence x, y;
1176
1177 EXPECT_CALL(a, ReturnResult(1))
1178 .InSequence(x)
1179 .WillOnce(Return(Result()));
1180
1181 EXPECT_CALL(b, DoB())
1182 .Times(2)
1183 .InSequence(y);
1184
1185 EXPECT_CALL(a, ReturnResult(2))
1186 .InSequence(x, y)
1187 .WillRepeatedly(Return(Result()));
1188
1189 EXPECT_CALL(a, ReturnResult(3))
1190 .InSequence(x)
1191 .WillOnce(Return(Result()));
1192
1193 EXPECT_DEATH({ // NOLINT
1194 a.ReturnResult(1);
1195 b.DoB();
1196 a.ReturnResult(2);
1197 }, "");
1198
1199 EXPECT_DEATH({ // NOLINT
1200 a.ReturnResult(2);
1201 }, "");
1202
1203 EXPECT_DEATH({ // NOLINT
1204 a.ReturnResult(3);
1205 }, "");
1206
1207 EXPECT_DEATH({ // NOLINT
1208 a.ReturnResult(1);
1209 b.DoB();
1210 b.DoB();
1211 a.ReturnResult(3);
1212 a.ReturnResult(2);
1213 }, "");
1214
1215 b.DoB();
1216 a.ReturnResult(1);
1217 b.DoB();
1218 a.ReturnResult(3);
1219}
1220
1221#endif // GTEST_HAS_DEATH_TEST
1222
1223TEST(SequenceTest, Retirement) {
1224 MockA a;
1225 Sequence s;
1226
1227 EXPECT_CALL(a, DoA(1))
1228 .InSequence(s);
1229 EXPECT_CALL(a, DoA(_))
1230 .InSequence(s)
1231 .RetiresOnSaturation();
1232 EXPECT_CALL(a, DoA(1))
1233 .InSequence(s);
1234
1235 a.DoA(1);
1236 a.DoA(2);
1237 a.DoA(1);
1238}
1239
1240// Tests that Google Mock correctly handles calls to mock functions
1241// after a mock object owning one of their pre-requisites has died.
1242
1243// Tests that calls that satisfy the original spec are successful.
1244TEST(DeletingMockEarlyTest, Success1) {
1245 MockB* const b1 = new MockB;
1246 MockA* const a = new MockA;
1247 MockB* const b2 = new MockB;
1248
1249 {
1250 InSequence dummy;
1251 EXPECT_CALL(*b1, DoB(_))
1252 .WillOnce(Return(1));
1253 EXPECT_CALL(*a, Binary(_, _))
1254 .Times(AnyNumber())
1255 .WillRepeatedly(Return(true));
1256 EXPECT_CALL(*b2, DoB(_))
1257 .Times(AnyNumber())
1258 .WillRepeatedly(Return(2));
1259 }
1260
1261 EXPECT_EQ(1, b1->DoB(1));
1262 delete b1;
1263 // a's pre-requisite has died.
1264 EXPECT_TRUE(a->Binary(0, 1));
1265 delete b2;
1266 // a's successor has died.
1267 EXPECT_TRUE(a->Binary(1, 2));
1268 delete a;
1269}
1270
1271// Tests that calls that satisfy the original spec are successful.
1272TEST(DeletingMockEarlyTest, Success2) {
1273 MockB* const b1 = new MockB;
1274 MockA* const a = new MockA;
1275 MockB* const b2 = new MockB;
1276
1277 {
1278 InSequence dummy;
1279 EXPECT_CALL(*b1, DoB(_))
1280 .WillOnce(Return(1));
1281 EXPECT_CALL(*a, Binary(_, _))
1282 .Times(AnyNumber());
1283 EXPECT_CALL(*b2, DoB(_))
1284 .Times(AnyNumber())
1285 .WillRepeatedly(Return(2));
1286 }
1287
1288 delete a; // a is trivially satisfied.
1289 EXPECT_EQ(1, b1->DoB(1));
1290 EXPECT_EQ(2, b2->DoB(2));
1291 delete b1;
1292 delete b2;
1293}
1294
1295// Tests that calls that violates the original spec yield failures.
1296TEST(DeletingMockEarlyTest, Failure1) {
1297 MockB* const b1 = new MockB;
1298 MockA* const a = new MockA;
1299 MockB* const b2 = new MockB;
1300
1301 {
1302 InSequence dummy;
1303 EXPECT_CALL(*b1, DoB(_))
1304 .WillOnce(Return(1));
1305 EXPECT_CALL(*a, Binary(_, _))
1306 .Times(AnyNumber());
1307 EXPECT_CALL(*b2, DoB(_))
1308 .Times(AnyNumber())
1309 .WillRepeatedly(Return(2));
1310 }
1311
1312 delete a; // a is trivially satisfied.
1313 EXPECT_NONFATAL_FAILURE({
1314 b2->DoB(2);
1315 }, "Unexpected mock function call");
1316 EXPECT_EQ(1, b1->DoB(1));
1317 delete b1;
1318 delete b2;
1319}
1320
1321// Tests that calls that violates the original spec yield failures.
1322TEST(DeletingMockEarlyTest, Failure2) {
1323 MockB* const b1 = new MockB;
1324 MockA* const a = new MockA;
1325 MockB* const b2 = new MockB;
1326
1327 {
1328 InSequence dummy;
1329 EXPECT_CALL(*b1, DoB(_));
1330 EXPECT_CALL(*a, Binary(_, _))
1331 .Times(AnyNumber());
1332 EXPECT_CALL(*b2, DoB(_))
1333 .Times(AnyNumber());
1334 }
1335
1336 EXPECT_NONFATAL_FAILURE(delete b1,
1337 "Actual: never called");
1338 EXPECT_NONFATAL_FAILURE(a->Binary(0, 1),
1339 "Unexpected mock function call");
1340 EXPECT_NONFATAL_FAILURE(b2->DoB(1),
1341 "Unexpected mock function call");
1342 delete a;
1343 delete b2;
1344}
1345
1346class EvenNumberCardinality : public CardinalityInterface {
1347 public:
1348 // Returns true iff call_count calls will satisfy this cardinality.
1349 virtual bool IsSatisfiedByCallCount(int call_count) const {
1350 return call_count % 2 == 0;
1351 }
1352
1353 // Returns true iff call_count calls will saturate this cardinality.
1354 virtual bool IsSaturatedByCallCount(int call_count) const { return false; }
1355
1356 // Describes self to an ostream.
1357 virtual void DescribeTo(::std::ostream* os) const {
1358 *os << "called even number of times";
1359 }
1360};
1361
1362Cardinality EvenNumber() {
1363 return Cardinality(new EvenNumberCardinality);
1364}
1365
1366TEST(ExpectationBaseTest,
1367 AllPrerequisitesAreSatisfiedWorksForNonMonotonicCardinality) {
1368 MockA* a = new MockA;
1369 Sequence s;
1370
1371 EXPECT_CALL(*a, DoA(1))
1372 .Times(EvenNumber())
1373 .InSequence(s);
1374 EXPECT_CALL(*a, DoA(2))
1375 .Times(AnyNumber())
1376 .InSequence(s);
1377 EXPECT_CALL(*a, DoA(3))
1378 .Times(AnyNumber());
1379
1380 a->DoA(3);
1381 a->DoA(1);
1382 EXPECT_NONFATAL_FAILURE(a->DoA(2), "Unexpected mock function call");
1383 EXPECT_NONFATAL_FAILURE(delete a, "to be called even number of times");
1384}
1385
1386// The following tests verify the message generated when a mock
1387// function is called.
1388
1389struct Printable {
1390};
1391
1392inline void operator<<(::std::ostream& os, const Printable&) {
1393 os << "Printable";
1394}
1395
1396struct Unprintable {
1397 Unprintable() : value(0) {}
1398 int value;
1399};
1400
1401class MockC {
1402 public:
1403 MOCK_METHOD6(VoidMethod, void(bool cond, int n, string s, void* p,
1404 const Printable& x, Unprintable y));
1405 MOCK_METHOD0(NonVoidMethod, int()); // NOLINT
1406};
1407
1408// TODO(wan@google.com): find a way to re-enable these tests.
1409#if 0
1410
1411// Tests that an uninteresting mock function call generates a warning
1412// containing the stack trace.
1413TEST(FunctionCallMessageTest, UninterestingCallGeneratesFyiWithStackTrace) {
1414 MockC c;
1415 CaptureTestStdout();
1416 c.VoidMethod(false, 5, "Hi", NULL, Printable(), Unprintable());
1417 const string& output = GetCapturedTestStdout();
1418 EXPECT_PRED_FORMAT2(IsSubstring, "GMOCK WARNING", output);
1419 EXPECT_PRED_FORMAT2(IsSubstring, "Stack trace:", output);
1420#ifndef NDEBUG
1421 // We check the stack trace content in dbg-mode only, as opt-mode
1422 // may inline the call we are interested in seeing.
1423
1424 // Verifies that a void mock function's name appears in the stack
1425 // trace.
1426 EXPECT_PRED_FORMAT2(IsSubstring, "::MockC::VoidMethod(", output);
1427
1428 // Verifies that a non-void mock function's name appears in the
1429 // stack trace.
1430 CaptureTestStdout();
1431 c.NonVoidMethod();
1432 const string& output2 = GetCapturedTestStdout();
1433 EXPECT_PRED_FORMAT2(IsSubstring, "::MockC::NonVoidMethod(", output2);
1434#endif // NDEBUG
1435}
1436
1437// Tests that an uninteresting mock function call causes the function
1438// arguments and return value to be printed.
1439TEST(FunctionCallMessageTest, UninterestingCallPrintsArgumentsAndReturnValue) {
1440 // A non-void mock function.
1441 MockB b;
1442 CaptureTestStdout();
1443 b.DoB();
1444 const string& output1 = GetCapturedTestStdout();
1445 EXPECT_PRED_FORMAT2(
1446 IsSubstring,
1447 "Uninteresting mock function call - returning default value.\n"
1448 " Function call: DoB()\n"
1449 " Returns: 0\n", output1);
1450 // Makes sure the return value is printed.
1451
1452 // A void mock function.
1453 MockC c;
1454 CaptureTestStdout();
1455 c.VoidMethod(false, 5, "Hi", NULL, Printable(), Unprintable());
1456 const string& output2 = GetCapturedTestStdout();
1457 EXPECT_PRED2(RE::PartialMatch, output2,
1458 "Uninteresting mock function call - returning directly\\.\n"
1459 " Function call: VoidMethod"
1460 "\\(false, 5, \"Hi\", NULL, @0x\\w+ "
1461 "Printable, 4-byte object <0000 0000>\\)");
1462 // A void function has no return value to print.
1463}
1464
1465// Tests how the --gmock_verbose flag affects Google Mock's output.
1466
1467class GMockVerboseFlagTest : public testing::Test {
1468 public:
1469 // Verifies that the given Google Mock output is correct. (When
1470 // should_print is true, the output should match the given regex and
1471 // contain the given function name in the stack trace. When it's
1472 // false, the output should be empty.)
1473 void VerifyOutput(const string& output, bool should_print,
1474 const string& regex,
1475 const string& function_name) {
1476 if (should_print) {
1477 EXPECT_PRED2(RE::PartialMatch, output, regex);
1478#ifndef NDEBUG
1479 // We check the stack trace content in dbg-mode only, as opt-mode
1480 // may inline the call we are interested in seeing.
1481 EXPECT_PRED_FORMAT2(IsSubstring, function_name, output);
1482#endif // NDEBUG
1483 } else {
1484 EXPECT_EQ("", output);
1485 }
1486 }
1487
1488 // Tests how the flag affects expected calls.
1489 void TestExpectedCall(bool should_print) {
1490 MockA a;
1491 EXPECT_CALL(a, DoA(5));
1492 EXPECT_CALL(a, Binary(_, 1))
1493 .WillOnce(Return(true));
1494
1495 // A void-returning function.
1496 CaptureTestStdout();
1497 a.DoA(5);
1498 VerifyOutput(
1499 GetCapturedTestStdout(),
1500 should_print,
1501 "Expected mock function call\\.\n"
1502 " Function call: DoA\\(5\\)\n"
1503 "Stack trace:",
1504 "MockA::DoA");
1505
1506 // A non-void-returning function.
1507 CaptureTestStdout();
1508 a.Binary(2, 1);
1509 VerifyOutput(
1510 GetCapturedTestStdout(),
1511 should_print,
1512 "Expected mock function call\\.\n"
1513 " Function call: Binary\\(2, 1\\)\n"
1514 " Returns: true\n"
1515 "Stack trace:",
1516 "MockA::Binary");
1517 }
1518
1519 // Tests how the flag affects uninteresting calls.
1520 void TestUninterestingCall(bool should_print) {
1521 MockA a;
1522
1523 // A void-returning function.
1524 CaptureTestStdout();
1525 a.DoA(5);
1526 VerifyOutput(
1527 GetCapturedTestStdout(),
1528 should_print,
1529 "\nGMOCK WARNING:\n"
1530 "Uninteresting mock function call - returning directly\\.\n"
1531 " Function call: DoA\\(5\\)\n"
1532 "Stack trace:\n"
1533 "[\\s\\S]*",
1534 "MockA::DoA");
1535
1536 // A non-void-returning function.
1537 CaptureTestStdout();
1538 a.Binary(2, 1);
1539 VerifyOutput(
1540 GetCapturedTestStdout(),
1541 should_print,
1542 "\nGMOCK WARNING:\n"
1543 "Uninteresting mock function call - returning default value\\.\n"
1544 " Function call: Binary\\(2, 1\\)\n"
1545 " Returns: false\n"
1546 "Stack trace:\n"
1547 "[\\s\\S]*",
1548 "MockA::Binary");
1549 }
1550};
1551
1552// Tests that --gmock_verbose=info causes both expected and
1553// uninteresting calls to be reported.
1554TEST_F(GMockVerboseFlagTest, Info) {
1555 GMOCK_FLAG(verbose) = kInfoVerbosity;
1556 TestExpectedCall(true);
1557 TestUninterestingCall(true);
1558}
1559
1560// Tests that --gmock_verbose=warning causes uninteresting calls to be
1561// reported.
1562TEST_F(GMockVerboseFlagTest, Warning) {
1563 GMOCK_FLAG(verbose) = kWarningVerbosity;
1564 TestExpectedCall(false);
1565 TestUninterestingCall(true);
1566}
1567
1568// Tests that --gmock_verbose=warning causes neither expected nor
1569// uninteresting calls to be reported.
1570TEST_F(GMockVerboseFlagTest, Error) {
1571 GMOCK_FLAG(verbose) = kErrorVerbosity;
1572 TestExpectedCall(false);
1573 TestUninterestingCall(false);
1574}
1575
1576// Tests that --gmock_verbose=SOME_INVALID_VALUE has the same effect
1577// as --gmock_verbose=warning.
1578TEST_F(GMockVerboseFlagTest, InvalidFlagIsTreatedAsWarning) {
1579 GMOCK_FLAG(verbose) = "invalid"; // Treated as "warning".
1580 TestExpectedCall(false);
1581 TestUninterestingCall(true);
1582}
1583
1584#endif // 0
1585
1586
1587// Tests that we can verify and clear a mock object's expectations
1588// when none of its methods has expectations.
1589TEST(VerifyAndClearExpectationsTest, NoMethodHasExpectations) {
1590 MockB b;
1591 ASSERT_TRUE(Mock::VerifyAndClearExpectations(&b));
1592
1593 // There should be no expectations on the methods now, so we can
1594 // freely call them.
1595 EXPECT_EQ(0, b.DoB());
1596 EXPECT_EQ(0, b.DoB(1));
1597}
1598
1599// Tests that we can verify and clear a mock object's expectations
1600// when some, but not all, of its methods have expectations *and* the
1601// verification succeeds.
1602TEST(VerifyAndClearExpectationsTest, SomeMethodsHaveExpectationsAndSucceed) {
1603 MockB b;
1604 EXPECT_CALL(b, DoB())
1605 .WillOnce(Return(1));
1606 b.DoB();
1607 ASSERT_TRUE(Mock::VerifyAndClearExpectations(&b));
1608
1609 // There should be no expectations on the methods now, so we can
1610 // freely call them.
1611 EXPECT_EQ(0, b.DoB());
1612 EXPECT_EQ(0, b.DoB(1));
1613}
1614
1615// Tests that we can verify and clear a mock object's expectations
1616// when some, but not all, of its methods have expectations *and* the
1617// verification fails.
1618TEST(VerifyAndClearExpectationsTest, SomeMethodsHaveExpectationsAndFail) {
1619 MockB b;
1620 EXPECT_CALL(b, DoB())
1621 .WillOnce(Return(1));
1622 bool result;
1623 EXPECT_NONFATAL_FAILURE(result = Mock::VerifyAndClearExpectations(&b),
1624 "Actual: never called");
1625 ASSERT_FALSE(result);
1626
1627 // There should be no expectations on the methods now, so we can
1628 // freely call them.
1629 EXPECT_EQ(0, b.DoB());
1630 EXPECT_EQ(0, b.DoB(1));
1631}
1632
1633// Tests that we can verify and clear a mock object's expectations
1634// when all of its methods have expectations.
1635TEST(VerifyAndClearExpectationsTest, AllMethodsHaveExpectations) {
1636 MockB b;
1637 EXPECT_CALL(b, DoB())
1638 .WillOnce(Return(1));
1639 EXPECT_CALL(b, DoB(_))
1640 .WillOnce(Return(2));
1641 b.DoB();
1642 b.DoB(1);
1643 ASSERT_TRUE(Mock::VerifyAndClearExpectations(&b));
1644
1645 // There should be no expectations on the methods now, so we can
1646 // freely call them.
1647 EXPECT_EQ(0, b.DoB());
1648 EXPECT_EQ(0, b.DoB(1));
1649}
1650
1651// Tests that we can verify and clear a mock object's expectations
1652// when a method has more than one expectation.
1653TEST(VerifyAndClearExpectationsTest, AMethodHasManyExpectations) {
1654 MockB b;
1655 EXPECT_CALL(b, DoB(0))
1656 .WillOnce(Return(1));
1657 EXPECT_CALL(b, DoB(_))
1658 .WillOnce(Return(2));
1659 b.DoB(1);
1660 bool result;
1661 EXPECT_NONFATAL_FAILURE(result = Mock::VerifyAndClearExpectations(&b),
1662 "Actual: never called");
1663 ASSERT_FALSE(result);
1664
1665 // There should be no expectations on the methods now, so we can
1666 // freely call them.
1667 EXPECT_EQ(0, b.DoB());
1668 EXPECT_EQ(0, b.DoB(1));
1669}
1670
1671// Tests that we can call VerifyAndClearExpectations() on the same
1672// mock object multiple times.
1673TEST(VerifyAndClearExpectationsTest, CanCallManyTimes) {
1674 MockB b;
1675 EXPECT_CALL(b, DoB());
1676 b.DoB();
1677 Mock::VerifyAndClearExpectations(&b);
1678
1679 EXPECT_CALL(b, DoB(_))
1680 .WillOnce(Return(1));
1681 b.DoB(1);
1682 Mock::VerifyAndClearExpectations(&b);
1683 Mock::VerifyAndClearExpectations(&b);
1684
1685 // There should be no expectations on the methods now, so we can
1686 // freely call them.
1687 EXPECT_EQ(0, b.DoB());
1688 EXPECT_EQ(0, b.DoB(1));
1689}
1690
1691// Tests that we can clear a mock object's default actions when none
1692// of its methods has default actions.
1693TEST(VerifyAndClearTest, NoMethodHasDefaultActions) {
1694 MockB b;
1695 // If this crashes or generates a failure, the test will catch it.
1696 Mock::VerifyAndClear(&b);
1697 EXPECT_EQ(0, b.DoB());
1698}
1699
1700// Tests that we can clear a mock object's default actions when some,
1701// but not all of its methods have default actions.
1702TEST(VerifyAndClearTest, SomeMethodsHaveDefaultActions) {
1703 MockB b;
1704 ON_CALL(b, DoB())
1705 .WillByDefault(Return(1));
1706
1707 Mock::VerifyAndClear(&b);
1708
1709 // Verifies that the default action of int DoB() was removed.
1710 EXPECT_EQ(0, b.DoB());
1711}
1712
1713// Tests that we can clear a mock object's default actions when all of
1714// its methods have default actions.
1715TEST(VerifyAndClearTest, AllMethodsHaveDefaultActions) {
1716 MockB b;
1717 ON_CALL(b, DoB())
1718 .WillByDefault(Return(1));
1719 ON_CALL(b, DoB(_))
1720 .WillByDefault(Return(2));
1721
1722 Mock::VerifyAndClear(&b);
1723
1724 // Verifies that the default action of int DoB() was removed.
1725 EXPECT_EQ(0, b.DoB());
1726
1727 // Verifies that the default action of int DoB(int) was removed.
1728 EXPECT_EQ(0, b.DoB(0));
1729}
1730
1731// Tests that we can clear a mock object's default actions when a
1732// method has more than one ON_CALL() set on it.
1733TEST(VerifyAndClearTest, AMethodHasManyDefaultActions) {
1734 MockB b;
1735 ON_CALL(b, DoB(0))
1736 .WillByDefault(Return(1));
1737 ON_CALL(b, DoB(_))
1738 .WillByDefault(Return(2));
1739
1740 Mock::VerifyAndClear(&b);
1741
1742 // Verifies that the default actions (there are two) of int DoB(int)
1743 // were removed.
1744 EXPECT_EQ(0, b.DoB(0));
1745 EXPECT_EQ(0, b.DoB(1));
1746}
1747
1748// Tests that we can call VerifyAndClear() on a mock object multiple
1749// times.
1750TEST(VerifyAndClearTest, CanCallManyTimes) {
1751 MockB b;
1752 ON_CALL(b, DoB())
1753 .WillByDefault(Return(1));
1754 Mock::VerifyAndClear(&b);
1755 Mock::VerifyAndClear(&b);
1756
1757 ON_CALL(b, DoB(_))
1758 .WillByDefault(Return(1));
1759 Mock::VerifyAndClear(&b);
1760
1761 EXPECT_EQ(0, b.DoB());
1762 EXPECT_EQ(0, b.DoB(1));
1763}
1764
1765// Tests that VerifyAndClear() works when the verification succeeds.
1766TEST(VerifyAndClearTest, Success) {
1767 MockB b;
1768 ON_CALL(b, DoB())
1769 .WillByDefault(Return(1));
1770 EXPECT_CALL(b, DoB(1))
1771 .WillOnce(Return(2));
1772
1773 b.DoB();
1774 b.DoB(1);
1775 ASSERT_TRUE(Mock::VerifyAndClear(&b));
1776
1777 // There should be no expectations on the methods now, so we can
1778 // freely call them.
1779 EXPECT_EQ(0, b.DoB());
1780 EXPECT_EQ(0, b.DoB(1));
1781}
1782
1783// Tests that VerifyAndClear() works when the verification fails.
1784TEST(VerifyAndClearTest, Failure) {
1785 MockB b;
1786 ON_CALL(b, DoB(_))
1787 .WillByDefault(Return(1));
1788 EXPECT_CALL(b, DoB())
1789 .WillOnce(Return(2));
1790
1791 b.DoB(1);
1792 bool result;
1793 EXPECT_NONFATAL_FAILURE(result = Mock::VerifyAndClear(&b),
1794 "Actual: never called");
1795 ASSERT_FALSE(result);
1796
1797 // There should be no expectations on the methods now, so we can
1798 // freely call them.
1799 EXPECT_EQ(0, b.DoB());
1800 EXPECT_EQ(0, b.DoB(1));
1801}
1802
1803// Tests that VerifyAndClear() works when the default actions and
1804// expectations are set on a const mock object.
1805TEST(VerifyAndClearTest, Const) {
1806 MockB b;
1807 ON_CALL(Const(b), DoB())
1808 .WillByDefault(Return(1));
1809
1810 EXPECT_CALL(Const(b), DoB())
1811 .WillOnce(DoDefault())
1812 .WillOnce(Return(2));
1813
1814 b.DoB();
1815 b.DoB();
1816 ASSERT_TRUE(Mock::VerifyAndClear(&b));
1817
1818 // There should be no expectations on the methods now, so we can
1819 // freely call them.
1820 EXPECT_EQ(0, b.DoB());
1821 EXPECT_EQ(0, b.DoB(1));
1822}
1823
1824// Tests that we can set default actions and expectations on a mock
1825// object after VerifyAndClear() has been called on it.
1826TEST(VerifyAndClearTest, CanSetDefaultActionsAndExpectationsAfterwards) {
1827 MockB b;
1828 ON_CALL(b, DoB())
1829 .WillByDefault(Return(1));
1830 EXPECT_CALL(b, DoB(_))
1831 .WillOnce(Return(2));
1832 b.DoB(1);
1833
1834 Mock::VerifyAndClear(&b);
1835
1836 EXPECT_CALL(b, DoB())
1837 .WillOnce(Return(3));
1838 ON_CALL(b, DoB(_))
1839 .WillByDefault(Return(4));
1840
1841 EXPECT_EQ(3, b.DoB());
1842 EXPECT_EQ(4, b.DoB(1));
1843}
1844
1845// Tests that calling VerifyAndClear() on one mock object does not
1846// affect other mock objects (either of the same type or not).
1847TEST(VerifyAndClearTest, DoesNotAffectOtherMockObjects) {
1848 MockA a;
1849 MockB b1;
1850 MockB b2;
1851
1852 ON_CALL(a, Binary(_, _))
1853 .WillByDefault(Return(true));
1854 EXPECT_CALL(a, Binary(_, _))
1855 .WillOnce(DoDefault())
1856 .WillOnce(Return(false));
1857
1858 ON_CALL(b1, DoB())
1859 .WillByDefault(Return(1));
1860 EXPECT_CALL(b1, DoB(_))
1861 .WillOnce(Return(2));
1862
1863 ON_CALL(b2, DoB())
1864 .WillByDefault(Return(3));
1865 EXPECT_CALL(b2, DoB(_));
1866
1867 b2.DoB(0);
1868 Mock::VerifyAndClear(&b2);
1869
1870 // Verifies that the default actions and expectations of a and b1
1871 // are still in effect.
1872 EXPECT_TRUE(a.Binary(0, 0));
1873 EXPECT_FALSE(a.Binary(0, 0));
1874
1875 EXPECT_EQ(1, b1.DoB());
1876 EXPECT_EQ(2, b1.DoB(0));
1877}
1878
1879// Tests that a mock function's action can call a mock function
1880// (either the same function or a different one) either as an explicit
1881// action or as a default action without causing a dead lock. It
1882// verifies that the action is not performed inside the critical
1883// section.
1884
1885void Helper(MockC* c) {
1886 c->NonVoidMethod();
1887}
1888
1889} // namespace