blob: 4e330f0b7bf127faef30e64bdc1404e5658ea31e [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
zhanyong.wan652540a2009-02-23 23:37:29 +0000195#if GTEST_HAS_DEATH_TEST
shiqiane35fdd92008-12-10 05:08:54 +0000196
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
zhanyong.wan652540a2009-02-23 23:37:29 +0000990#if GTEST_HAS_DEATH_TEST
zhanyong.wan5b95fa72009-01-27 22:28:45 +0000991
992TEST(UndefinedReturnValueTest, ReturnValueIsMandatory) {
993 MockA a;
994 // TODO(wan@google.com): We should really verify the output message,
995 // but we cannot yet due to that EXPECT_DEATH only captures stderr
996 // while Google Mock logs to stdout.
997 EXPECT_DEATH(a.ReturnResult(1), "");
998}
999
1000#endif // GTEST_HAS_DEATH_TEST
1001
shiqiane35fdd92008-12-10 05:08:54 +00001002// Tests that an excessive call (one whose arguments match the
1003// matchers but is called too many times) performs the default action.
1004TEST(ExcessiveCallTest, DoesDefaultAction) {
1005 // When there is an ON_CALL() statement, the action specified by it
1006 // should be taken.
1007 MockA a;
1008 ON_CALL(a, Binary(_, _))
1009 .WillByDefault(Return(true));
1010 EXPECT_CALL(a, Binary(0, 0));
1011 a.Binary(0, 0);
1012 bool result = false;
1013 EXPECT_NONFATAL_FAILURE(result = a.Binary(0, 0),
1014 "Mock function called more times than expected");
1015 EXPECT_TRUE(result);
1016
1017 // When there is no ON_CALL(), the default value for the return type
1018 // should be returned.
1019 MockB b;
1020 EXPECT_CALL(b, DoB(0))
1021 .Times(0);
1022 int n = -1;
1023 EXPECT_NONFATAL_FAILURE(n = b.DoB(0),
1024 "Mock function called more times than expected");
1025 EXPECT_EQ(0, n);
1026}
1027
1028// Tests that when a void function is called too many times,
1029// the failure message contains the argument values.
1030TEST(ExcessiveCallTest, GeneratesFailureForVoidFunction) {
1031 MockA a;
1032 EXPECT_CALL(a, DoA(_))
1033 .Times(0);
1034 EXPECT_NONFATAL_FAILURE(
1035 a.DoA(9),
1036 "Mock function called more times than expected - returning directly.\n"
1037 " Function call: DoA(9)\n"
1038 " Expected: to be never called\n"
1039 " Actual: called once - over-saturated and active");
1040}
1041
1042// Tests that when a non-void function is called too many times, the
1043// failure message contains the argument values and the return value.
1044TEST(ExcessiveCallTest, GeneratesFailureForNonVoidFunction) {
1045 MockB b;
1046 EXPECT_CALL(b, DoB(_));
1047 b.DoB(1);
1048 EXPECT_NONFATAL_FAILURE(
1049 b.DoB(2),
1050 "Mock function called more times than expected - "
1051 "returning default value.\n"
1052 " Function call: DoB(2)\n"
1053 " Returns: 0\n"
1054 " Expected: to be called once\n"
1055 " Actual: called twice - over-saturated and active");
1056}
1057
1058// Tests using sequences.
1059
1060TEST(InSequenceTest, AllExpectationInScopeAreInSequence) {
1061 MockA a;
1062 {
1063 InSequence dummy;
1064
1065 EXPECT_CALL(a, DoA(1));
1066 EXPECT_CALL(a, DoA(2));
1067 }
1068
1069 EXPECT_NONFATAL_FAILURE({ // NOLINT
1070 a.DoA(2);
1071 }, "Unexpected mock function call");
1072
1073 a.DoA(1);
1074 a.DoA(2);
1075}
1076
1077TEST(InSequenceTest, NestedInSequence) {
1078 MockA a;
1079 {
1080 InSequence dummy;
1081
1082 EXPECT_CALL(a, DoA(1));
1083 {
1084 InSequence dummy2;
1085
1086 EXPECT_CALL(a, DoA(2));
1087 EXPECT_CALL(a, DoA(3));
1088 }
1089 }
1090
1091 EXPECT_NONFATAL_FAILURE({ // NOLINT
1092 a.DoA(1);
1093 a.DoA(3);
1094 }, "Unexpected mock function call");
1095
1096 a.DoA(2);
1097 a.DoA(3);
1098}
1099
1100TEST(InSequenceTest, ExpectationsOutOfScopeAreNotAffected) {
1101 MockA a;
1102 {
1103 InSequence dummy;
1104
1105 EXPECT_CALL(a, DoA(1));
1106 EXPECT_CALL(a, DoA(2));
1107 }
1108 EXPECT_CALL(a, DoA(3));
1109
1110 EXPECT_NONFATAL_FAILURE({ // NOLINT
1111 a.DoA(2);
1112 }, "Unexpected mock function call");
1113
1114 a.DoA(3);
1115 a.DoA(1);
1116 a.DoA(2);
1117}
1118
1119// Tests that any order is allowed when no sequence is used.
1120TEST(SequenceTest, AnyOrderIsOkByDefault) {
1121 {
1122 MockA a;
1123 MockB b;
1124
1125 EXPECT_CALL(a, DoA(1));
1126 EXPECT_CALL(b, DoB())
1127 .Times(AnyNumber());
1128
1129 a.DoA(1);
1130 b.DoB();
1131 }
1132
1133 { // NOLINT
1134 MockA a;
1135 MockB b;
1136
1137 EXPECT_CALL(a, DoA(1));
1138 EXPECT_CALL(b, DoB())
1139 .Times(AnyNumber());
1140
1141 b.DoB();
1142 a.DoA(1);
1143 }
1144}
1145
zhanyong.wan652540a2009-02-23 23:37:29 +00001146#if GTEST_HAS_DEATH_TEST
shiqiane35fdd92008-12-10 05:08:54 +00001147
1148// Tests that the calls must be in strict order when a complete order
1149// is specified.
1150TEST(SequenceTest, CallsMustBeInStrictOrderWhenSaidSo) {
1151 MockA a;
1152 Sequence s;
1153
1154 EXPECT_CALL(a, ReturnResult(1))
1155 .InSequence(s)
1156 .WillOnce(Return(Result()));
1157
1158 EXPECT_CALL(a, ReturnResult(2))
1159 .InSequence(s)
1160 .WillOnce(Return(Result()));
1161
1162 EXPECT_CALL(a, ReturnResult(3))
1163 .InSequence(s)
1164 .WillOnce(Return(Result()));
1165
1166 EXPECT_DEATH({ // NOLINT
1167 a.ReturnResult(1);
1168 a.ReturnResult(3);
1169 a.ReturnResult(2);
1170 }, "");
1171
1172 EXPECT_DEATH({ // NOLINT
1173 a.ReturnResult(2);
1174 a.ReturnResult(1);
1175 a.ReturnResult(3);
1176 }, "");
1177
1178 a.ReturnResult(1);
1179 a.ReturnResult(2);
1180 a.ReturnResult(3);
1181}
1182
1183// Tests specifying a DAG using multiple sequences.
1184TEST(SequenceTest, CallsMustConformToSpecifiedDag) {
1185 MockA a;
1186 MockB b;
1187 Sequence x, y;
1188
1189 EXPECT_CALL(a, ReturnResult(1))
1190 .InSequence(x)
1191 .WillOnce(Return(Result()));
1192
1193 EXPECT_CALL(b, DoB())
1194 .Times(2)
1195 .InSequence(y);
1196
1197 EXPECT_CALL(a, ReturnResult(2))
1198 .InSequence(x, y)
1199 .WillRepeatedly(Return(Result()));
1200
1201 EXPECT_CALL(a, ReturnResult(3))
1202 .InSequence(x)
1203 .WillOnce(Return(Result()));
1204
1205 EXPECT_DEATH({ // NOLINT
1206 a.ReturnResult(1);
1207 b.DoB();
1208 a.ReturnResult(2);
1209 }, "");
1210
1211 EXPECT_DEATH({ // NOLINT
1212 a.ReturnResult(2);
1213 }, "");
1214
1215 EXPECT_DEATH({ // NOLINT
1216 a.ReturnResult(3);
1217 }, "");
1218
1219 EXPECT_DEATH({ // NOLINT
1220 a.ReturnResult(1);
1221 b.DoB();
1222 b.DoB();
1223 a.ReturnResult(3);
1224 a.ReturnResult(2);
1225 }, "");
1226
1227 b.DoB();
1228 a.ReturnResult(1);
1229 b.DoB();
1230 a.ReturnResult(3);
1231}
1232
1233#endif // GTEST_HAS_DEATH_TEST
1234
1235TEST(SequenceTest, Retirement) {
1236 MockA a;
1237 Sequence s;
1238
1239 EXPECT_CALL(a, DoA(1))
1240 .InSequence(s);
1241 EXPECT_CALL(a, DoA(_))
1242 .InSequence(s)
1243 .RetiresOnSaturation();
1244 EXPECT_CALL(a, DoA(1))
1245 .InSequence(s);
1246
1247 a.DoA(1);
1248 a.DoA(2);
1249 a.DoA(1);
1250}
1251
1252// Tests that Google Mock correctly handles calls to mock functions
1253// after a mock object owning one of their pre-requisites has died.
1254
1255// Tests that calls that satisfy the original spec are successful.
1256TEST(DeletingMockEarlyTest, Success1) {
1257 MockB* const b1 = new MockB;
1258 MockA* const a = new MockA;
1259 MockB* const b2 = new MockB;
1260
1261 {
1262 InSequence dummy;
1263 EXPECT_CALL(*b1, DoB(_))
1264 .WillOnce(Return(1));
1265 EXPECT_CALL(*a, Binary(_, _))
1266 .Times(AnyNumber())
1267 .WillRepeatedly(Return(true));
1268 EXPECT_CALL(*b2, DoB(_))
1269 .Times(AnyNumber())
1270 .WillRepeatedly(Return(2));
1271 }
1272
1273 EXPECT_EQ(1, b1->DoB(1));
1274 delete b1;
1275 // a's pre-requisite has died.
1276 EXPECT_TRUE(a->Binary(0, 1));
1277 delete b2;
1278 // a's successor has died.
1279 EXPECT_TRUE(a->Binary(1, 2));
1280 delete a;
1281}
1282
1283// Tests that calls that satisfy the original spec are successful.
1284TEST(DeletingMockEarlyTest, Success2) {
1285 MockB* const b1 = new MockB;
1286 MockA* const a = new MockA;
1287 MockB* const b2 = new MockB;
1288
1289 {
1290 InSequence dummy;
1291 EXPECT_CALL(*b1, DoB(_))
1292 .WillOnce(Return(1));
1293 EXPECT_CALL(*a, Binary(_, _))
1294 .Times(AnyNumber());
1295 EXPECT_CALL(*b2, DoB(_))
1296 .Times(AnyNumber())
1297 .WillRepeatedly(Return(2));
1298 }
1299
1300 delete a; // a is trivially satisfied.
1301 EXPECT_EQ(1, b1->DoB(1));
1302 EXPECT_EQ(2, b2->DoB(2));
1303 delete b1;
1304 delete b2;
1305}
1306
1307// Tests that calls that violates the original spec yield failures.
1308TEST(DeletingMockEarlyTest, Failure1) {
1309 MockB* const b1 = new MockB;
1310 MockA* const a = new MockA;
1311 MockB* const b2 = new MockB;
1312
1313 {
1314 InSequence dummy;
1315 EXPECT_CALL(*b1, DoB(_))
1316 .WillOnce(Return(1));
1317 EXPECT_CALL(*a, Binary(_, _))
1318 .Times(AnyNumber());
1319 EXPECT_CALL(*b2, DoB(_))
1320 .Times(AnyNumber())
1321 .WillRepeatedly(Return(2));
1322 }
1323
1324 delete a; // a is trivially satisfied.
1325 EXPECT_NONFATAL_FAILURE({
1326 b2->DoB(2);
1327 }, "Unexpected mock function call");
1328 EXPECT_EQ(1, b1->DoB(1));
1329 delete b1;
1330 delete b2;
1331}
1332
1333// Tests that calls that violates the original spec yield failures.
1334TEST(DeletingMockEarlyTest, Failure2) {
1335 MockB* const b1 = new MockB;
1336 MockA* const a = new MockA;
1337 MockB* const b2 = new MockB;
1338
1339 {
1340 InSequence dummy;
1341 EXPECT_CALL(*b1, DoB(_));
1342 EXPECT_CALL(*a, Binary(_, _))
1343 .Times(AnyNumber());
1344 EXPECT_CALL(*b2, DoB(_))
1345 .Times(AnyNumber());
1346 }
1347
1348 EXPECT_NONFATAL_FAILURE(delete b1,
1349 "Actual: never called");
1350 EXPECT_NONFATAL_FAILURE(a->Binary(0, 1),
1351 "Unexpected mock function call");
1352 EXPECT_NONFATAL_FAILURE(b2->DoB(1),
1353 "Unexpected mock function call");
1354 delete a;
1355 delete b2;
1356}
1357
1358class EvenNumberCardinality : public CardinalityInterface {
1359 public:
1360 // Returns true iff call_count calls will satisfy this cardinality.
1361 virtual bool IsSatisfiedByCallCount(int call_count) const {
1362 return call_count % 2 == 0;
1363 }
1364
1365 // Returns true iff call_count calls will saturate this cardinality.
1366 virtual bool IsSaturatedByCallCount(int call_count) const { return false; }
1367
1368 // Describes self to an ostream.
1369 virtual void DescribeTo(::std::ostream* os) const {
1370 *os << "called even number of times";
1371 }
1372};
1373
1374Cardinality EvenNumber() {
1375 return Cardinality(new EvenNumberCardinality);
1376}
1377
1378TEST(ExpectationBaseTest,
1379 AllPrerequisitesAreSatisfiedWorksForNonMonotonicCardinality) {
1380 MockA* a = new MockA;
1381 Sequence s;
1382
1383 EXPECT_CALL(*a, DoA(1))
1384 .Times(EvenNumber())
1385 .InSequence(s);
1386 EXPECT_CALL(*a, DoA(2))
1387 .Times(AnyNumber())
1388 .InSequence(s);
1389 EXPECT_CALL(*a, DoA(3))
1390 .Times(AnyNumber());
1391
1392 a->DoA(3);
1393 a->DoA(1);
1394 EXPECT_NONFATAL_FAILURE(a->DoA(2), "Unexpected mock function call");
1395 EXPECT_NONFATAL_FAILURE(delete a, "to be called even number of times");
1396}
1397
1398// The following tests verify the message generated when a mock
1399// function is called.
1400
1401struct Printable {
1402};
1403
1404inline void operator<<(::std::ostream& os, const Printable&) {
1405 os << "Printable";
1406}
1407
1408struct Unprintable {
1409 Unprintable() : value(0) {}
1410 int value;
1411};
1412
1413class MockC {
1414 public:
1415 MOCK_METHOD6(VoidMethod, void(bool cond, int n, string s, void* p,
1416 const Printable& x, Unprintable y));
1417 MOCK_METHOD0(NonVoidMethod, int()); // NOLINT
1418};
1419
1420// TODO(wan@google.com): find a way to re-enable these tests.
1421#if 0
1422
1423// Tests that an uninteresting mock function call generates a warning
1424// containing the stack trace.
1425TEST(FunctionCallMessageTest, UninterestingCallGeneratesFyiWithStackTrace) {
1426 MockC c;
1427 CaptureTestStdout();
1428 c.VoidMethod(false, 5, "Hi", NULL, Printable(), Unprintable());
1429 const string& output = GetCapturedTestStdout();
1430 EXPECT_PRED_FORMAT2(IsSubstring, "GMOCK WARNING", output);
1431 EXPECT_PRED_FORMAT2(IsSubstring, "Stack trace:", output);
1432#ifndef NDEBUG
1433 // We check the stack trace content in dbg-mode only, as opt-mode
1434 // may inline the call we are interested in seeing.
1435
1436 // Verifies that a void mock function's name appears in the stack
1437 // trace.
1438 EXPECT_PRED_FORMAT2(IsSubstring, "::MockC::VoidMethod(", output);
1439
1440 // Verifies that a non-void mock function's name appears in the
1441 // stack trace.
1442 CaptureTestStdout();
1443 c.NonVoidMethod();
1444 const string& output2 = GetCapturedTestStdout();
1445 EXPECT_PRED_FORMAT2(IsSubstring, "::MockC::NonVoidMethod(", output2);
1446#endif // NDEBUG
1447}
1448
1449// Tests that an uninteresting mock function call causes the function
1450// arguments and return value to be printed.
1451TEST(FunctionCallMessageTest, UninterestingCallPrintsArgumentsAndReturnValue) {
1452 // A non-void mock function.
1453 MockB b;
1454 CaptureTestStdout();
1455 b.DoB();
1456 const string& output1 = GetCapturedTestStdout();
1457 EXPECT_PRED_FORMAT2(
1458 IsSubstring,
1459 "Uninteresting mock function call - returning default value.\n"
1460 " Function call: DoB()\n"
1461 " Returns: 0\n", output1);
1462 // Makes sure the return value is printed.
1463
1464 // A void mock function.
1465 MockC c;
1466 CaptureTestStdout();
1467 c.VoidMethod(false, 5, "Hi", NULL, Printable(), Unprintable());
1468 const string& output2 = GetCapturedTestStdout();
1469 EXPECT_PRED2(RE::PartialMatch, output2,
1470 "Uninteresting mock function call - returning directly\\.\n"
1471 " Function call: VoidMethod"
1472 "\\(false, 5, \"Hi\", NULL, @0x\\w+ "
1473 "Printable, 4-byte object <0000 0000>\\)");
1474 // A void function has no return value to print.
1475}
1476
1477// Tests how the --gmock_verbose flag affects Google Mock's output.
1478
1479class GMockVerboseFlagTest : public testing::Test {
1480 public:
1481 // Verifies that the given Google Mock output is correct. (When
1482 // should_print is true, the output should match the given regex and
1483 // contain the given function name in the stack trace. When it's
1484 // false, the output should be empty.)
1485 void VerifyOutput(const string& output, bool should_print,
1486 const string& regex,
1487 const string& function_name) {
1488 if (should_print) {
1489 EXPECT_PRED2(RE::PartialMatch, output, regex);
1490#ifndef NDEBUG
1491 // We check the stack trace content in dbg-mode only, as opt-mode
1492 // may inline the call we are interested in seeing.
1493 EXPECT_PRED_FORMAT2(IsSubstring, function_name, output);
1494#endif // NDEBUG
1495 } else {
1496 EXPECT_EQ("", output);
1497 }
1498 }
1499
1500 // Tests how the flag affects expected calls.
1501 void TestExpectedCall(bool should_print) {
1502 MockA a;
1503 EXPECT_CALL(a, DoA(5));
1504 EXPECT_CALL(a, Binary(_, 1))
1505 .WillOnce(Return(true));
1506
1507 // A void-returning function.
1508 CaptureTestStdout();
1509 a.DoA(5);
1510 VerifyOutput(
1511 GetCapturedTestStdout(),
1512 should_print,
1513 "Expected mock function call\\.\n"
1514 " Function call: DoA\\(5\\)\n"
1515 "Stack trace:",
1516 "MockA::DoA");
1517
1518 // A non-void-returning function.
1519 CaptureTestStdout();
1520 a.Binary(2, 1);
1521 VerifyOutput(
1522 GetCapturedTestStdout(),
1523 should_print,
1524 "Expected mock function call\\.\n"
1525 " Function call: Binary\\(2, 1\\)\n"
1526 " Returns: true\n"
1527 "Stack trace:",
1528 "MockA::Binary");
1529 }
1530
1531 // Tests how the flag affects uninteresting calls.
1532 void TestUninterestingCall(bool should_print) {
1533 MockA a;
1534
1535 // A void-returning function.
1536 CaptureTestStdout();
1537 a.DoA(5);
1538 VerifyOutput(
1539 GetCapturedTestStdout(),
1540 should_print,
1541 "\nGMOCK WARNING:\n"
1542 "Uninteresting mock function call - returning directly\\.\n"
1543 " Function call: DoA\\(5\\)\n"
1544 "Stack trace:\n"
1545 "[\\s\\S]*",
1546 "MockA::DoA");
1547
1548 // A non-void-returning function.
1549 CaptureTestStdout();
1550 a.Binary(2, 1);
1551 VerifyOutput(
1552 GetCapturedTestStdout(),
1553 should_print,
1554 "\nGMOCK WARNING:\n"
1555 "Uninteresting mock function call - returning default value\\.\n"
1556 " Function call: Binary\\(2, 1\\)\n"
1557 " Returns: false\n"
1558 "Stack trace:\n"
1559 "[\\s\\S]*",
1560 "MockA::Binary");
1561 }
1562};
1563
1564// Tests that --gmock_verbose=info causes both expected and
1565// uninteresting calls to be reported.
1566TEST_F(GMockVerboseFlagTest, Info) {
1567 GMOCK_FLAG(verbose) = kInfoVerbosity;
1568 TestExpectedCall(true);
1569 TestUninterestingCall(true);
1570}
1571
1572// Tests that --gmock_verbose=warning causes uninteresting calls to be
1573// reported.
1574TEST_F(GMockVerboseFlagTest, Warning) {
1575 GMOCK_FLAG(verbose) = kWarningVerbosity;
1576 TestExpectedCall(false);
1577 TestUninterestingCall(true);
1578}
1579
1580// Tests that --gmock_verbose=warning causes neither expected nor
1581// uninteresting calls to be reported.
1582TEST_F(GMockVerboseFlagTest, Error) {
1583 GMOCK_FLAG(verbose) = kErrorVerbosity;
1584 TestExpectedCall(false);
1585 TestUninterestingCall(false);
1586}
1587
1588// Tests that --gmock_verbose=SOME_INVALID_VALUE has the same effect
1589// as --gmock_verbose=warning.
1590TEST_F(GMockVerboseFlagTest, InvalidFlagIsTreatedAsWarning) {
1591 GMOCK_FLAG(verbose) = "invalid"; // Treated as "warning".
1592 TestExpectedCall(false);
1593 TestUninterestingCall(true);
1594}
1595
1596#endif // 0
1597
1598
1599// Tests that we can verify and clear a mock object's expectations
1600// when none of its methods has expectations.
1601TEST(VerifyAndClearExpectationsTest, NoMethodHasExpectations) {
1602 MockB b;
1603 ASSERT_TRUE(Mock::VerifyAndClearExpectations(&b));
1604
1605 // There should be no expectations on the methods now, so we can
1606 // freely call them.
1607 EXPECT_EQ(0, b.DoB());
1608 EXPECT_EQ(0, b.DoB(1));
1609}
1610
1611// Tests that we can verify and clear a mock object's expectations
1612// when some, but not all, of its methods have expectations *and* the
1613// verification succeeds.
1614TEST(VerifyAndClearExpectationsTest, SomeMethodsHaveExpectationsAndSucceed) {
1615 MockB b;
1616 EXPECT_CALL(b, DoB())
1617 .WillOnce(Return(1));
1618 b.DoB();
1619 ASSERT_TRUE(Mock::VerifyAndClearExpectations(&b));
1620
1621 // There should be no expectations on the methods now, so we can
1622 // freely call them.
1623 EXPECT_EQ(0, b.DoB());
1624 EXPECT_EQ(0, b.DoB(1));
1625}
1626
1627// Tests that we can verify and clear a mock object's expectations
1628// when some, but not all, of its methods have expectations *and* the
1629// verification fails.
1630TEST(VerifyAndClearExpectationsTest, SomeMethodsHaveExpectationsAndFail) {
1631 MockB b;
1632 EXPECT_CALL(b, DoB())
1633 .WillOnce(Return(1));
1634 bool result;
1635 EXPECT_NONFATAL_FAILURE(result = Mock::VerifyAndClearExpectations(&b),
1636 "Actual: never called");
1637 ASSERT_FALSE(result);
1638
1639 // There should be no expectations on the methods now, so we can
1640 // freely call them.
1641 EXPECT_EQ(0, b.DoB());
1642 EXPECT_EQ(0, b.DoB(1));
1643}
1644
1645// Tests that we can verify and clear a mock object's expectations
1646// when all of its methods have expectations.
1647TEST(VerifyAndClearExpectationsTest, AllMethodsHaveExpectations) {
1648 MockB b;
1649 EXPECT_CALL(b, DoB())
1650 .WillOnce(Return(1));
1651 EXPECT_CALL(b, DoB(_))
1652 .WillOnce(Return(2));
1653 b.DoB();
1654 b.DoB(1);
1655 ASSERT_TRUE(Mock::VerifyAndClearExpectations(&b));
1656
1657 // There should be no expectations on the methods now, so we can
1658 // freely call them.
1659 EXPECT_EQ(0, b.DoB());
1660 EXPECT_EQ(0, b.DoB(1));
1661}
1662
1663// Tests that we can verify and clear a mock object's expectations
1664// when a method has more than one expectation.
1665TEST(VerifyAndClearExpectationsTest, AMethodHasManyExpectations) {
1666 MockB b;
1667 EXPECT_CALL(b, DoB(0))
1668 .WillOnce(Return(1));
1669 EXPECT_CALL(b, DoB(_))
1670 .WillOnce(Return(2));
1671 b.DoB(1);
1672 bool result;
1673 EXPECT_NONFATAL_FAILURE(result = Mock::VerifyAndClearExpectations(&b),
1674 "Actual: never called");
1675 ASSERT_FALSE(result);
1676
1677 // There should be no expectations on the methods now, so we can
1678 // freely call them.
1679 EXPECT_EQ(0, b.DoB());
1680 EXPECT_EQ(0, b.DoB(1));
1681}
1682
1683// Tests that we can call VerifyAndClearExpectations() on the same
1684// mock object multiple times.
1685TEST(VerifyAndClearExpectationsTest, CanCallManyTimes) {
1686 MockB b;
1687 EXPECT_CALL(b, DoB());
1688 b.DoB();
1689 Mock::VerifyAndClearExpectations(&b);
1690
1691 EXPECT_CALL(b, DoB(_))
1692 .WillOnce(Return(1));
1693 b.DoB(1);
1694 Mock::VerifyAndClearExpectations(&b);
1695 Mock::VerifyAndClearExpectations(&b);
1696
1697 // There should be no expectations on the methods now, so we can
1698 // freely call them.
1699 EXPECT_EQ(0, b.DoB());
1700 EXPECT_EQ(0, b.DoB(1));
1701}
1702
1703// Tests that we can clear a mock object's default actions when none
1704// of its methods has default actions.
1705TEST(VerifyAndClearTest, NoMethodHasDefaultActions) {
1706 MockB b;
1707 // If this crashes or generates a failure, the test will catch it.
1708 Mock::VerifyAndClear(&b);
1709 EXPECT_EQ(0, b.DoB());
1710}
1711
1712// Tests that we can clear a mock object's default actions when some,
1713// but not all of its methods have default actions.
1714TEST(VerifyAndClearTest, SomeMethodsHaveDefaultActions) {
1715 MockB b;
1716 ON_CALL(b, DoB())
1717 .WillByDefault(Return(1));
1718
1719 Mock::VerifyAndClear(&b);
1720
1721 // Verifies that the default action of int DoB() was removed.
1722 EXPECT_EQ(0, b.DoB());
1723}
1724
1725// Tests that we can clear a mock object's default actions when all of
1726// its methods have default actions.
1727TEST(VerifyAndClearTest, AllMethodsHaveDefaultActions) {
1728 MockB b;
1729 ON_CALL(b, DoB())
1730 .WillByDefault(Return(1));
1731 ON_CALL(b, DoB(_))
1732 .WillByDefault(Return(2));
1733
1734 Mock::VerifyAndClear(&b);
1735
1736 // Verifies that the default action of int DoB() was removed.
1737 EXPECT_EQ(0, b.DoB());
1738
1739 // Verifies that the default action of int DoB(int) was removed.
1740 EXPECT_EQ(0, b.DoB(0));
1741}
1742
1743// Tests that we can clear a mock object's default actions when a
1744// method has more than one ON_CALL() set on it.
1745TEST(VerifyAndClearTest, AMethodHasManyDefaultActions) {
1746 MockB b;
1747 ON_CALL(b, DoB(0))
1748 .WillByDefault(Return(1));
1749 ON_CALL(b, DoB(_))
1750 .WillByDefault(Return(2));
1751
1752 Mock::VerifyAndClear(&b);
1753
1754 // Verifies that the default actions (there are two) of int DoB(int)
1755 // were removed.
1756 EXPECT_EQ(0, b.DoB(0));
1757 EXPECT_EQ(0, b.DoB(1));
1758}
1759
1760// Tests that we can call VerifyAndClear() on a mock object multiple
1761// times.
1762TEST(VerifyAndClearTest, CanCallManyTimes) {
1763 MockB b;
1764 ON_CALL(b, DoB())
1765 .WillByDefault(Return(1));
1766 Mock::VerifyAndClear(&b);
1767 Mock::VerifyAndClear(&b);
1768
1769 ON_CALL(b, DoB(_))
1770 .WillByDefault(Return(1));
1771 Mock::VerifyAndClear(&b);
1772
1773 EXPECT_EQ(0, b.DoB());
1774 EXPECT_EQ(0, b.DoB(1));
1775}
1776
1777// Tests that VerifyAndClear() works when the verification succeeds.
1778TEST(VerifyAndClearTest, Success) {
1779 MockB b;
1780 ON_CALL(b, DoB())
1781 .WillByDefault(Return(1));
1782 EXPECT_CALL(b, DoB(1))
1783 .WillOnce(Return(2));
1784
1785 b.DoB();
1786 b.DoB(1);
1787 ASSERT_TRUE(Mock::VerifyAndClear(&b));
1788
1789 // There should be no expectations on the methods now, so we can
1790 // freely call them.
1791 EXPECT_EQ(0, b.DoB());
1792 EXPECT_EQ(0, b.DoB(1));
1793}
1794
1795// Tests that VerifyAndClear() works when the verification fails.
1796TEST(VerifyAndClearTest, Failure) {
1797 MockB b;
1798 ON_CALL(b, DoB(_))
1799 .WillByDefault(Return(1));
1800 EXPECT_CALL(b, DoB())
1801 .WillOnce(Return(2));
1802
1803 b.DoB(1);
1804 bool result;
1805 EXPECT_NONFATAL_FAILURE(result = Mock::VerifyAndClear(&b),
1806 "Actual: never called");
1807 ASSERT_FALSE(result);
1808
1809 // There should be no expectations on the methods now, so we can
1810 // freely call them.
1811 EXPECT_EQ(0, b.DoB());
1812 EXPECT_EQ(0, b.DoB(1));
1813}
1814
1815// Tests that VerifyAndClear() works when the default actions and
1816// expectations are set on a const mock object.
1817TEST(VerifyAndClearTest, Const) {
1818 MockB b;
1819 ON_CALL(Const(b), DoB())
1820 .WillByDefault(Return(1));
1821
1822 EXPECT_CALL(Const(b), DoB())
1823 .WillOnce(DoDefault())
1824 .WillOnce(Return(2));
1825
1826 b.DoB();
1827 b.DoB();
1828 ASSERT_TRUE(Mock::VerifyAndClear(&b));
1829
1830 // There should be no expectations on the methods now, so we can
1831 // freely call them.
1832 EXPECT_EQ(0, b.DoB());
1833 EXPECT_EQ(0, b.DoB(1));
1834}
1835
1836// Tests that we can set default actions and expectations on a mock
1837// object after VerifyAndClear() has been called on it.
1838TEST(VerifyAndClearTest, CanSetDefaultActionsAndExpectationsAfterwards) {
1839 MockB b;
1840 ON_CALL(b, DoB())
1841 .WillByDefault(Return(1));
1842 EXPECT_CALL(b, DoB(_))
1843 .WillOnce(Return(2));
1844 b.DoB(1);
1845
1846 Mock::VerifyAndClear(&b);
1847
1848 EXPECT_CALL(b, DoB())
1849 .WillOnce(Return(3));
1850 ON_CALL(b, DoB(_))
1851 .WillByDefault(Return(4));
1852
1853 EXPECT_EQ(3, b.DoB());
1854 EXPECT_EQ(4, b.DoB(1));
1855}
1856
1857// Tests that calling VerifyAndClear() on one mock object does not
1858// affect other mock objects (either of the same type or not).
1859TEST(VerifyAndClearTest, DoesNotAffectOtherMockObjects) {
1860 MockA a;
1861 MockB b1;
1862 MockB b2;
1863
1864 ON_CALL(a, Binary(_, _))
1865 .WillByDefault(Return(true));
1866 EXPECT_CALL(a, Binary(_, _))
1867 .WillOnce(DoDefault())
1868 .WillOnce(Return(false));
1869
1870 ON_CALL(b1, DoB())
1871 .WillByDefault(Return(1));
1872 EXPECT_CALL(b1, DoB(_))
1873 .WillOnce(Return(2));
1874
1875 ON_CALL(b2, DoB())
1876 .WillByDefault(Return(3));
1877 EXPECT_CALL(b2, DoB(_));
1878
1879 b2.DoB(0);
1880 Mock::VerifyAndClear(&b2);
1881
1882 // Verifies that the default actions and expectations of a and b1
1883 // are still in effect.
1884 EXPECT_TRUE(a.Binary(0, 0));
1885 EXPECT_FALSE(a.Binary(0, 0));
1886
1887 EXPECT_EQ(1, b1.DoB());
1888 EXPECT_EQ(2, b1.DoB(0));
1889}
1890
1891// Tests that a mock function's action can call a mock function
1892// (either the same function or a different one) either as an explicit
1893// action or as a default action without causing a dead lock. It
1894// verifies that the action is not performed inside the critical
1895// section.
1896
1897void Helper(MockC* c) {
1898 c->NonVoidMethod();
1899}
1900
1901} // namespace