blob: de05c574fdf0849dbfee3136c96e4080976cb845 [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;
zhanyong.wan41b9b0b2009-07-01 19:04:51 +000074using testing::Eq;
75using testing::Expectation;
76using testing::ExpectationSet;
shiqiane35fdd92008-12-10 05:08:54 +000077using testing::GMOCK_FLAG(verbose);
zhanyong.wanbf550852009-06-09 06:09:53 +000078using testing::Gt;
shiqiane35fdd92008-12-10 05:08:54 +000079using testing::InSequence;
80using testing::Invoke;
81using testing::InvokeWithoutArgs;
82using testing::IsSubstring;
83using testing::Lt;
84using testing::Message;
85using testing::Mock;
zhanyong.wan41b9b0b2009-07-01 19:04:51 +000086using testing::Ne;
shiqiane35fdd92008-12-10 05:08:54 +000087using testing::Return;
88using testing::Sequence;
89using testing::internal::g_gmock_mutex;
90using testing::internal::kErrorVerbosity;
91using testing::internal::kInfoVerbosity;
92using testing::internal::kWarningVerbosity;
shiqiane35fdd92008-12-10 05:08:54 +000093using testing::internal::ExpectationTester;
94using testing::internal::string;
95
96class Result {};
97
98class MockA {
99 public:
100 MOCK_METHOD1(DoA, void(int n)); // NOLINT
101 MOCK_METHOD1(ReturnResult, Result(int n)); // NOLINT
102 MOCK_METHOD2(Binary, bool(int x, int y)); // NOLINT
zhanyong.wanbf550852009-06-09 06:09:53 +0000103 MOCK_METHOD2(ReturnInt, int(int x, int y)); // NOLINT
shiqiane35fdd92008-12-10 05:08:54 +0000104};
105
106class MockB {
107 public:
108 MOCK_CONST_METHOD0(DoB, int()); // NOLINT
109 MOCK_METHOD1(DoB, int(int n)); // NOLINT
110};
111
112// Tests that EXPECT_CALL and ON_CALL compile in a presence of macro
113// redefining a mock method name. This could happen, for example, when
114// the tested code #includes Win32 API headers which define many APIs
115// as macros, e.g. #define TextOut TextOutW.
116
117#define Method MethodW
118
119class CC {
120 public:
121 virtual ~CC() {}
122 virtual int Method() = 0;
123};
124class MockCC : public CC {
125 public:
126 MOCK_METHOD0(Method, int());
127};
128
129// Tests that a method with expanded name compiles.
130TEST(OnCallSyntaxTest, CompilesWithMethodNameExpandedFromMacro) {
131 MockCC cc;
132 ON_CALL(cc, Method());
133}
134
135// Tests that the method with expanded name not only compiles but runs
136// and returns a correct value, too.
137TEST(OnCallSyntaxTest, WorksWithMethodNameExpandedFromMacro) {
138 MockCC cc;
139 ON_CALL(cc, Method()).WillByDefault(Return(42));
140 EXPECT_EQ(42, cc.Method());
141}
142
143// Tests that a method with expanded name compiles.
144TEST(ExpectCallSyntaxTest, CompilesWithMethodNameExpandedFromMacro) {
145 MockCC cc;
146 EXPECT_CALL(cc, Method());
147 cc.Method();
148}
149
150// Tests that it works, too.
151TEST(ExpectCallSyntaxTest, WorksWithMethodNameExpandedFromMacro) {
152 MockCC cc;
153 EXPECT_CALL(cc, Method()).WillOnce(Return(42));
154 EXPECT_EQ(42, cc.Method());
155}
156
157#undef Method // Done with macro redefinition tests.
158
159// Tests that ON_CALL evaluates its arguments exactly once as promised
160// by Google Mock.
161TEST(OnCallSyntaxTest, EvaluatesFirstArgumentOnce) {
162 MockA a;
163 MockA* pa = &a;
164
165 ON_CALL(*pa++, DoA(_));
166 EXPECT_EQ(&a + 1, pa);
167}
168
169TEST(OnCallSyntaxTest, EvaluatesSecondArgumentOnce) {
170 MockA a;
171 int n = 0;
172
173 ON_CALL(a, DoA(n++));
174 EXPECT_EQ(1, n);
175}
176
177// Tests that the syntax of ON_CALL() is enforced at run time.
178
zhanyong.wanbf550852009-06-09 06:09:53 +0000179TEST(OnCallSyntaxTest, WithIsOptional) {
shiqiane35fdd92008-12-10 05:08:54 +0000180 MockA a;
181
182 ON_CALL(a, DoA(5))
183 .WillByDefault(Return());
184 ON_CALL(a, DoA(_))
zhanyong.wanbf550852009-06-09 06:09:53 +0000185 .With(_)
shiqiane35fdd92008-12-10 05:08:54 +0000186 .WillByDefault(Return());
187}
188
zhanyong.wanbf550852009-06-09 06:09:53 +0000189TEST(OnCallSyntaxTest, WithCanAppearAtMostOnce) {
shiqiane35fdd92008-12-10 05:08:54 +0000190 MockA a;
191
192 EXPECT_NONFATAL_FAILURE({ // NOLINT
193 ON_CALL(a, ReturnResult(_))
zhanyong.wanbf550852009-06-09 06:09:53 +0000194 .With(_)
195 .With(_)
shiqiane35fdd92008-12-10 05:08:54 +0000196 .WillByDefault(Return(Result()));
zhanyong.wanbf550852009-06-09 06:09:53 +0000197 }, ".With() cannot appear more than once in an ON_CALL()");
198}
199
zhanyong.wan652540a2009-02-23 23:37:29 +0000200#if GTEST_HAS_DEATH_TEST
shiqiane35fdd92008-12-10 05:08:54 +0000201
202TEST(OnCallSyntaxTest, WillByDefaultIsMandatory) {
203 MockA a;
204
205 EXPECT_DEATH({ // NOLINT
206 ON_CALL(a, DoA(5));
207 a.DoA(5);
208 }, "");
209}
210
211#endif // GTEST_HAS_DEATH_TEST
212
213TEST(OnCallSyntaxTest, WillByDefaultCanAppearAtMostOnce) {
214 MockA a;
215
216 EXPECT_NONFATAL_FAILURE({ // NOLINT
217 ON_CALL(a, DoA(5))
218 .WillByDefault(Return())
219 .WillByDefault(Return());
220 }, ".WillByDefault() must appear exactly once in an ON_CALL()");
221}
222
223// Tests that EXPECT_CALL evaluates its arguments exactly once as
224// promised by Google Mock.
225TEST(ExpectCallSyntaxTest, EvaluatesFirstArgumentOnce) {
226 MockA a;
227 MockA* pa = &a;
228
229 EXPECT_CALL(*pa++, DoA(_));
230 a.DoA(0);
231 EXPECT_EQ(&a + 1, pa);
232}
233
234TEST(ExpectCallSyntaxTest, EvaluatesSecondArgumentOnce) {
235 MockA a;
236 int n = 0;
237
238 EXPECT_CALL(a, DoA(n++));
239 a.DoA(0);
240 EXPECT_EQ(1, n);
241}
242
243// Tests that the syntax of EXPECT_CALL() is enforced at run time.
244
zhanyong.wanbf550852009-06-09 06:09:53 +0000245TEST(ExpectCallSyntaxTest, WithIsOptional) {
shiqiane35fdd92008-12-10 05:08:54 +0000246 MockA a;
247
248 EXPECT_CALL(a, DoA(5))
249 .Times(0);
250 EXPECT_CALL(a, DoA(6))
zhanyong.wanbf550852009-06-09 06:09:53 +0000251 .With(_)
shiqiane35fdd92008-12-10 05:08:54 +0000252 .Times(0);
253}
254
zhanyong.wanbf550852009-06-09 06:09:53 +0000255TEST(ExpectCallSyntaxTest, WithCanAppearAtMostOnce) {
shiqiane35fdd92008-12-10 05:08:54 +0000256 MockA a;
257
258 EXPECT_NONFATAL_FAILURE({ // NOLINT
259 EXPECT_CALL(a, DoA(6))
zhanyong.wanbf550852009-06-09 06:09:53 +0000260 .With(_)
261 .With(_);
262 }, ".With() cannot appear more than once in an EXPECT_CALL()");
shiqiane35fdd92008-12-10 05:08:54 +0000263
264 a.DoA(6);
265}
266
zhanyong.wanbf550852009-06-09 06:09:53 +0000267TEST(ExpectCallSyntaxTest, WithMustBeFirstClause) {
shiqiane35fdd92008-12-10 05:08:54 +0000268 MockA a;
269
270 EXPECT_NONFATAL_FAILURE({ // NOLINT
271 EXPECT_CALL(a, DoA(1))
272 .Times(1)
zhanyong.wanbf550852009-06-09 06:09:53 +0000273 .With(_);
274 }, ".With() must be the first clause in an EXPECT_CALL()");
shiqiane35fdd92008-12-10 05:08:54 +0000275
276 a.DoA(1);
277
278 EXPECT_NONFATAL_FAILURE({ // NOLINT
279 EXPECT_CALL(a, DoA(2))
280 .WillOnce(Return())
zhanyong.wanbf550852009-06-09 06:09:53 +0000281 .With(_);
282 }, ".With() must be the first clause in an EXPECT_CALL()");
shiqiane35fdd92008-12-10 05:08:54 +0000283
284 a.DoA(2);
285}
286
287TEST(ExpectCallSyntaxTest, TimesCanBeInferred) {
288 MockA a;
289
290 EXPECT_CALL(a, DoA(1))
291 .WillOnce(Return());
292
293 EXPECT_CALL(a, DoA(2))
294 .WillOnce(Return())
295 .WillRepeatedly(Return());
296
297 a.DoA(1);
298 a.DoA(2);
299 a.DoA(2);
300}
301
302TEST(ExpectCallSyntaxTest, TimesCanAppearAtMostOnce) {
303 MockA a;
304
305 EXPECT_NONFATAL_FAILURE({ // NOLINT
306 EXPECT_CALL(a, DoA(1))
307 .Times(1)
308 .Times(2);
309 }, ".Times() cannot appear more than once in an EXPECT_CALL()");
310
311 a.DoA(1);
312 a.DoA(1);
313}
314
315TEST(ExpectCallSyntaxTest, TimesMustBeBeforeInSequence) {
316 MockA a;
317 Sequence s;
318
319 EXPECT_NONFATAL_FAILURE({ // NOLINT
320 EXPECT_CALL(a, DoA(1))
321 .InSequence(s)
322 .Times(1);
323 }, ".Times() cannot appear after ");
324
325 a.DoA(1);
326}
327
328TEST(ExpectCallSyntaxTest, InSequenceIsOptional) {
329 MockA a;
330 Sequence s;
331
332 EXPECT_CALL(a, DoA(1));
333 EXPECT_CALL(a, DoA(2))
334 .InSequence(s);
335
336 a.DoA(1);
337 a.DoA(2);
338}
339
340TEST(ExpectCallSyntaxTest, InSequenceCanAppearMultipleTimes) {
341 MockA a;
342 Sequence s1, s2;
343
344 EXPECT_CALL(a, DoA(1))
345 .InSequence(s1, s2)
346 .InSequence(s1);
347
348 a.DoA(1);
349}
350
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000351TEST(ExpectCallSyntaxTest, InSequenceMustBeBeforeAfter) {
352 MockA a;
353 Sequence s;
354
355 Expectation e = EXPECT_CALL(a, DoA(1))
356 .Times(AnyNumber());
357 EXPECT_NONFATAL_FAILURE({ // NOLINT
358 EXPECT_CALL(a, DoA(2))
359 .After(e)
360 .InSequence(s);
361 }, ".InSequence() cannot appear after ");
362
363 a.DoA(2);
364}
365
366TEST(ExpectCallSyntaxTest, InSequenceMustBeBeforeWillOnce) {
shiqiane35fdd92008-12-10 05:08:54 +0000367 MockA a;
368 Sequence s;
369
370 EXPECT_NONFATAL_FAILURE({ // NOLINT
371 EXPECT_CALL(a, DoA(1))
372 .WillOnce(Return())
373 .InSequence(s);
374 }, ".InSequence() cannot appear after ");
375
376 a.DoA(1);
377}
378
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000379TEST(ExpectCallSyntaxTest, AfterMustBeBeforeWillOnce) {
380 MockA a;
381
382 Expectation e = EXPECT_CALL(a, DoA(1));
383 EXPECT_NONFATAL_FAILURE({
384 EXPECT_CALL(a, DoA(2))
385 .WillOnce(Return())
386 .After(e);
387 }, ".After() cannot appear after ");
388
389 a.DoA(1);
390 a.DoA(2);
391}
392
shiqiane35fdd92008-12-10 05:08:54 +0000393TEST(ExpectCallSyntaxTest, WillIsOptional) {
394 MockA a;
395
396 EXPECT_CALL(a, DoA(1));
397 EXPECT_CALL(a, DoA(2))
398 .WillOnce(Return());
399
400 a.DoA(1);
401 a.DoA(2);
402}
403
404TEST(ExpectCallSyntaxTest, WillCanAppearMultipleTimes) {
405 MockA a;
406
407 EXPECT_CALL(a, DoA(1))
408 .Times(AnyNumber())
409 .WillOnce(Return())
410 .WillOnce(Return())
411 .WillOnce(Return());
412}
413
414TEST(ExpectCallSyntaxTest, WillMustBeBeforeWillRepeatedly) {
415 MockA a;
416
417 EXPECT_NONFATAL_FAILURE({ // NOLINT
418 EXPECT_CALL(a, DoA(1))
419 .WillRepeatedly(Return())
420 .WillOnce(Return());
421 }, ".WillOnce() cannot appear after ");
422
423 a.DoA(1);
424}
425
426TEST(ExpectCallSyntaxTest, WillRepeatedlyIsOptional) {
427 MockA a;
428
429 EXPECT_CALL(a, DoA(1))
430 .WillOnce(Return());
431 EXPECT_CALL(a, DoA(2))
432 .WillOnce(Return())
433 .WillRepeatedly(Return());
434
435 a.DoA(1);
436 a.DoA(2);
437 a.DoA(2);
438}
439
440TEST(ExpectCallSyntaxTest, WillRepeatedlyCannotAppearMultipleTimes) {
441 MockA a;
442
443 EXPECT_NONFATAL_FAILURE({ // NOLINT
444 EXPECT_CALL(a, DoA(1))
445 .WillRepeatedly(Return())
446 .WillRepeatedly(Return());
447 }, ".WillRepeatedly() cannot appear more than once in an "
448 "EXPECT_CALL()");
449}
450
451TEST(ExpectCallSyntaxTest, WillRepeatedlyMustBeBeforeRetiresOnSaturation) {
452 MockA a;
453
454 EXPECT_NONFATAL_FAILURE({ // NOLINT
455 EXPECT_CALL(a, DoA(1))
456 .RetiresOnSaturation()
457 .WillRepeatedly(Return());
458 }, ".WillRepeatedly() cannot appear after ");
459}
460
461TEST(ExpectCallSyntaxTest, RetiresOnSaturationIsOptional) {
462 MockA a;
463
464 EXPECT_CALL(a, DoA(1));
465 EXPECT_CALL(a, DoA(1))
466 .RetiresOnSaturation();
467
468 a.DoA(1);
469 a.DoA(1);
470}
471
472TEST(ExpectCallSyntaxTest, RetiresOnSaturationCannotAppearMultipleTimes) {
473 MockA a;
474
475 EXPECT_NONFATAL_FAILURE({ // NOLINT
476 EXPECT_CALL(a, DoA(1))
477 .RetiresOnSaturation()
478 .RetiresOnSaturation();
479 }, ".RetiresOnSaturation() cannot appear more than once");
480
481 a.DoA(1);
482}
483
484TEST(ExpectCallSyntaxTest, DefaultCardinalityIsOnce) {
485 {
486 MockA a;
487 EXPECT_CALL(a, DoA(1));
488 a.DoA(1);
489 }
490 EXPECT_NONFATAL_FAILURE({ // NOLINT
491 MockA a;
492 EXPECT_CALL(a, DoA(1));
493 }, "to be called once");
494 EXPECT_NONFATAL_FAILURE({ // NOLINT
495 MockA a;
496 EXPECT_CALL(a, DoA(1));
497 a.DoA(1);
498 a.DoA(1);
499 }, "to be called once");
500}
501
502// TODO(wan@google.com): find a way to re-enable these tests.
503#if 0
504
505// Tests that Google Mock doesn't print a warning when the number of
506// WillOnce() is adequate.
507TEST(ExpectCallSyntaxTest, DoesNotWarnOnAdequateActionCount) {
508 CaptureTestStdout();
509 {
510 MockB b;
511
512 // It's always fine to omit WillOnce() entirely.
513 EXPECT_CALL(b, DoB())
514 .Times(0);
515 EXPECT_CALL(b, DoB(1))
516 .Times(AtMost(1));
517 EXPECT_CALL(b, DoB(2))
518 .Times(1)
519 .WillRepeatedly(Return(1));
520
521 // It's fine for the number of WillOnce()s to equal the upper bound.
522 EXPECT_CALL(b, DoB(3))
523 .Times(Between(1, 2))
524 .WillOnce(Return(1))
525 .WillOnce(Return(2));
526
527 // It's fine for the number of WillOnce()s to be smaller than the
528 // upper bound when there is a WillRepeatedly().
529 EXPECT_CALL(b, DoB(4))
530 .Times(AtMost(3))
531 .WillOnce(Return(1))
532 .WillRepeatedly(Return(2));
533
534 // Satisfies the above expectations.
535 b.DoB(2);
536 b.DoB(3);
537 }
538 const string& output = GetCapturedTestStdout();
539 EXPECT_EQ("", output);
540}
541
542// Tests that Google Mock warns on having too many actions in an
543// expectation compared to its cardinality.
544TEST(ExpectCallSyntaxTest, WarnsOnTooManyActions) {
545 CaptureTestStdout();
546 {
547 MockB b;
548
549 // Warns when the number of WillOnce()s is larger than the upper bound.
550 EXPECT_CALL(b, DoB())
551 .Times(0)
552 .WillOnce(Return(1)); // #1
553 EXPECT_CALL(b, DoB())
554 .Times(AtMost(1))
555 .WillOnce(Return(1))
556 .WillOnce(Return(2)); // #2
557 EXPECT_CALL(b, DoB(1))
558 .Times(1)
559 .WillOnce(Return(1))
560 .WillOnce(Return(2))
561 .RetiresOnSaturation(); // #3
562
563 // Warns when the number of WillOnce()s equals the upper bound and
564 // there is a WillRepeatedly().
565 EXPECT_CALL(b, DoB())
566 .Times(0)
567 .WillRepeatedly(Return(1)); // #4
568 EXPECT_CALL(b, DoB(2))
569 .Times(1)
570 .WillOnce(Return(1))
571 .WillRepeatedly(Return(2)); // #5
572
573 // Satisfies the above expectations.
574 b.DoB(1);
575 b.DoB(2);
576 }
577 const string& output = GetCapturedTestStdout();
578 EXPECT_PRED_FORMAT2(IsSubstring,
579 "Too many actions specified.\n"
580 "Expected to be never called, but has 1 WillOnce().",
581 output); // #1
582 EXPECT_PRED_FORMAT2(IsSubstring,
583 "Too many actions specified.\n"
584 "Expected to be called at most once, "
585 "but has 2 WillOnce()s.",
586 output); // #2
587 EXPECT_PRED_FORMAT2(IsSubstring,
588 "Too many actions specified.\n"
589 "Expected to be called once, but has 2 WillOnce()s.",
590 output); // #3
591 EXPECT_PRED_FORMAT2(IsSubstring,
592 "Too many actions specified.\n"
593 "Expected to be never called, but has 0 WillOnce()s "
594 "and a WillRepeatedly().",
595 output); // #4
596 EXPECT_PRED_FORMAT2(IsSubstring,
597 "Too many actions specified.\n"
598 "Expected to be called once, but has 1 WillOnce() "
599 "and a WillRepeatedly().",
600 output); // #5
601}
602
603// Tests that Google Mock warns on having too few actions in an
604// expectation compared to its cardinality.
605TEST(ExpectCallSyntaxTest, WarnsOnTooFewActions) {
606 MockB b;
607
608 EXPECT_CALL(b, DoB())
609 .Times(Between(2, 3))
610 .WillOnce(Return(1));
611
612 CaptureTestStdout();
613 b.DoB();
614 const string& output = GetCapturedTestStdout();
615 EXPECT_PRED_FORMAT2(IsSubstring,
616 "Too few actions specified.\n"
617 "Expected to be called between 2 and 3 times, "
618 "but has only 1 WillOnce().",
619 output);
620 b.DoB();
621}
622
623#endif // 0
624
625// Tests the semantics of ON_CALL().
626
627// Tests that the built-in default action is taken when no ON_CALL()
628// is specified.
629TEST(OnCallTest, TakesBuiltInDefaultActionWhenNoOnCall) {
630 MockB b;
631 EXPECT_CALL(b, DoB());
632
633 EXPECT_EQ(0, b.DoB());
634}
635
636// Tests that the built-in default action is taken when no ON_CALL()
637// matches the invocation.
638TEST(OnCallTest, TakesBuiltInDefaultActionWhenNoOnCallMatches) {
639 MockB b;
640 ON_CALL(b, DoB(1))
641 .WillByDefault(Return(1));
642 EXPECT_CALL(b, DoB(_));
643
644 EXPECT_EQ(0, b.DoB(2));
645}
646
647// Tests that the last matching ON_CALL() action is taken.
648TEST(OnCallTest, PicksLastMatchingOnCall) {
649 MockB b;
650 ON_CALL(b, DoB(_))
651 .WillByDefault(Return(3));
652 ON_CALL(b, DoB(2))
653 .WillByDefault(Return(2));
654 ON_CALL(b, DoB(1))
655 .WillByDefault(Return(1));
656 EXPECT_CALL(b, DoB(_));
657
658 EXPECT_EQ(2, b.DoB(2));
659}
660
661// Tests the semantics of EXPECT_CALL().
662
663// Tests that any call is allowed when no EXPECT_CALL() is specified.
664TEST(ExpectCallTest, AllowsAnyCallWhenNoSpec) {
665 MockB b;
666 EXPECT_CALL(b, DoB());
667 // There is no expectation on DoB(int).
668
669 b.DoB();
670
671 // DoB(int) can be called any number of times.
672 b.DoB(1);
673 b.DoB(2);
674}
675
676// Tests that the last matching EXPECT_CALL() fires.
677TEST(ExpectCallTest, PicksLastMatchingExpectCall) {
678 MockB b;
679 EXPECT_CALL(b, DoB(_))
680 .WillRepeatedly(Return(2));
681 EXPECT_CALL(b, DoB(1))
682 .WillRepeatedly(Return(1));
683
684 EXPECT_EQ(1, b.DoB(1));
685}
686
687// Tests lower-bound violation.
688TEST(ExpectCallTest, CatchesTooFewCalls) {
689 EXPECT_NONFATAL_FAILURE({ // NOLINT
690 MockB b;
691 EXPECT_CALL(b, DoB(5))
692 .Times(AtLeast(2));
693
694 b.DoB(5);
695 }, "Actual function call count doesn't match this expectation.\n"
696 " Expected: to be called at least twice\n"
697 " Actual: called once - unsatisfied and active");
698}
699
700// Tests that the cardinality can be inferred when no Times(...) is
701// specified.
702TEST(ExpectCallTest, InfersCardinalityWhenThereIsNoWillRepeatedly) {
703 {
704 MockB b;
705 EXPECT_CALL(b, DoB())
706 .WillOnce(Return(1))
707 .WillOnce(Return(2));
708
709 EXPECT_EQ(1, b.DoB());
710 EXPECT_EQ(2, b.DoB());
711 }
712
713 EXPECT_NONFATAL_FAILURE({ // NOLINT
714 MockB b;
715 EXPECT_CALL(b, DoB())
716 .WillOnce(Return(1))
717 .WillOnce(Return(2));
718
719 EXPECT_EQ(1, b.DoB());
720 }, "to be called twice");
721
722 { // NOLINT
723 MockB b;
724 EXPECT_CALL(b, DoB())
725 .WillOnce(Return(1))
726 .WillOnce(Return(2));
727
728 EXPECT_EQ(1, b.DoB());
729 EXPECT_EQ(2, b.DoB());
730 EXPECT_NONFATAL_FAILURE(b.DoB(), "to be called twice");
731 }
732}
733
734TEST(ExpectCallTest, InfersCardinality1WhenThereIsWillRepeatedly) {
735 {
736 MockB b;
737 EXPECT_CALL(b, DoB())
738 .WillOnce(Return(1))
739 .WillRepeatedly(Return(2));
740
741 EXPECT_EQ(1, b.DoB());
742 }
743
744 { // NOLINT
745 MockB b;
746 EXPECT_CALL(b, DoB())
747 .WillOnce(Return(1))
748 .WillRepeatedly(Return(2));
749
750 EXPECT_EQ(1, b.DoB());
751 EXPECT_EQ(2, b.DoB());
752 EXPECT_EQ(2, b.DoB());
753 }
754
755 EXPECT_NONFATAL_FAILURE({ // NOLINT
756 MockB b;
757 EXPECT_CALL(b, DoB())
758 .WillOnce(Return(1))
759 .WillRepeatedly(Return(2));
760 }, "to be called at least once");
761}
762
763// Tests that the n-th action is taken for the n-th matching
764// invocation.
765TEST(ExpectCallTest, NthMatchTakesNthAction) {
766 MockB b;
767 EXPECT_CALL(b, DoB())
768 .WillOnce(Return(1))
769 .WillOnce(Return(2))
770 .WillOnce(Return(3));
771
772 EXPECT_EQ(1, b.DoB());
773 EXPECT_EQ(2, b.DoB());
774 EXPECT_EQ(3, b.DoB());
775}
776
777// TODO(wan@google.com): find a way to re-enable these tests.
778#if 0
779
780// Tests that the default action is taken when the WillOnce(...) list is
781// exhausted and there is no WillRepeatedly().
782TEST(ExpectCallTest, TakesDefaultActionWhenWillListIsExhausted) {
783 MockB b;
784 EXPECT_CALL(b, DoB(_))
785 .Times(1);
786 EXPECT_CALL(b, DoB())
787 .Times(AnyNumber())
788 .WillOnce(Return(1))
789 .WillOnce(Return(2));
790
791 CaptureTestStdout();
792 EXPECT_EQ(0, b.DoB(1)); // Shouldn't generate a warning as the
793 // expectation has no action clause at all.
794 EXPECT_EQ(1, b.DoB());
795 EXPECT_EQ(2, b.DoB());
796 const string& output1 = GetCapturedTestStdout();
797 EXPECT_EQ("", output1);
798
799 CaptureTestStdout();
800 EXPECT_EQ(0, b.DoB());
801 EXPECT_EQ(0, b.DoB());
802 const string& output2 = GetCapturedTestStdout();
803 EXPECT_PRED2(RE::PartialMatch, output2,
804 "Actions ran out\\.\n"
805 "Called 3 times, but only 2 WillOnce\\(\\)s are specified - "
806 "returning default value\\.");
807 EXPECT_PRED2(RE::PartialMatch, output2,
808 "Actions ran out\\.\n"
809 "Called 4 times, but only 2 WillOnce\\(\\)s are specified - "
810 "returning default value\\.");
811}
812
813#endif // 0
814
815// Tests that the WillRepeatedly() action is taken when the WillOnce(...)
816// list is exhausted.
817TEST(ExpectCallTest, TakesRepeatedActionWhenWillListIsExhausted) {
818 MockB b;
819 EXPECT_CALL(b, DoB())
820 .WillOnce(Return(1))
821 .WillRepeatedly(Return(2));
822
823 EXPECT_EQ(1, b.DoB());
824 EXPECT_EQ(2, b.DoB());
825 EXPECT_EQ(2, b.DoB());
826}
827
828// Tests that an uninteresting call performs the default action.
829TEST(UninterestingCallTest, DoesDefaultAction) {
830 // When there is an ON_CALL() statement, the action specified by it
831 // should be taken.
832 MockA a;
833 ON_CALL(a, Binary(_, _))
834 .WillByDefault(Return(true));
835 EXPECT_TRUE(a.Binary(1, 2));
836
837 // When there is no ON_CALL(), the default value for the return type
838 // should be returned.
839 MockB b;
840 EXPECT_EQ(0, b.DoB());
841}
842
843// Tests that an unexpected call performs the default action.
844TEST(UnexpectedCallTest, DoesDefaultAction) {
845 // When there is an ON_CALL() statement, the action specified by it
846 // should be taken.
847 MockA a;
848 ON_CALL(a, Binary(_, _))
849 .WillByDefault(Return(true));
850 EXPECT_CALL(a, Binary(0, 0));
851 a.Binary(0, 0);
852 bool result = false;
853 EXPECT_NONFATAL_FAILURE(result = a.Binary(1, 2),
854 "Unexpected mock function call");
855 EXPECT_TRUE(result);
856
857 // When there is no ON_CALL(), the default value for the return type
858 // should be returned.
859 MockB b;
860 EXPECT_CALL(b, DoB(0))
861 .Times(0);
862 int n = -1;
863 EXPECT_NONFATAL_FAILURE(n = b.DoB(1),
864 "Unexpected mock function call");
865 EXPECT_EQ(0, n);
866}
867
868// Tests that when an unexpected void function generates the right
869// failure message.
870TEST(UnexpectedCallTest, GeneratesFailureForVoidFunction) {
871 // First, tests the message when there is only one EXPECT_CALL().
872 MockA a1;
873 EXPECT_CALL(a1, DoA(1));
874 a1.DoA(1);
875 // Ideally we should match the failure message against a regex, but
876 // EXPECT_NONFATAL_FAILURE doesn't support that, so we test for
877 // multiple sub-strings instead.
878 EXPECT_NONFATAL_FAILURE(
879 a1.DoA(9),
880 "Unexpected mock function call - returning directly.\n"
881 " Function call: DoA(9)\n"
882 "Google Mock tried the following 1 expectation, but it didn't match:");
883 EXPECT_NONFATAL_FAILURE(
884 a1.DoA(9),
885 " Expected arg #0: is equal to 1\n"
886 " Actual: 9\n"
887 " Expected: to be called once\n"
888 " Actual: called once - saturated and active");
889
890 // Next, tests the message when there are more than one EXPECT_CALL().
891 MockA a2;
892 EXPECT_CALL(a2, DoA(1));
893 EXPECT_CALL(a2, DoA(3));
894 a2.DoA(1);
895 EXPECT_NONFATAL_FAILURE(
896 a2.DoA(2),
897 "Unexpected mock function call - returning directly.\n"
898 " Function call: DoA(2)\n"
899 "Google Mock tried the following 2 expectations, but none matched:");
900 EXPECT_NONFATAL_FAILURE(
901 a2.DoA(2),
902 "tried expectation #0\n"
903 " Expected arg #0: is equal to 1\n"
904 " Actual: 2\n"
905 " Expected: to be called once\n"
906 " Actual: called once - saturated and active");
907 EXPECT_NONFATAL_FAILURE(
908 a2.DoA(2),
909 "tried expectation #1\n"
910 " Expected arg #0: is equal to 3\n"
911 " Actual: 2\n"
912 " Expected: to be called once\n"
913 " Actual: never called - unsatisfied and active");
914 a2.DoA(3);
915}
916
917// Tests that an unexpected non-void function generates the right
918// failure message.
919TEST(UnexpectedCallTest, GeneartesFailureForNonVoidFunction) {
920 MockB b1;
921 EXPECT_CALL(b1, DoB(1));
922 b1.DoB(1);
923 EXPECT_NONFATAL_FAILURE(
924 b1.DoB(2),
925 "Unexpected mock function call - returning default value.\n"
926 " Function call: DoB(2)\n"
927 " Returns: 0\n"
928 "Google Mock tried the following 1 expectation, but it didn't match:");
929 EXPECT_NONFATAL_FAILURE(
930 b1.DoB(2),
931 " Expected arg #0: is equal to 1\n"
932 " Actual: 2\n"
933 " Expected: to be called once\n"
934 " Actual: called once - saturated and active");
935}
936
937// Tests that Google Mock explains that an retired expectation doesn't
938// match the call.
939TEST(UnexpectedCallTest, RetiredExpectation) {
940 MockB b;
941 EXPECT_CALL(b, DoB(1))
942 .RetiresOnSaturation();
943
944 b.DoB(1);
945 EXPECT_NONFATAL_FAILURE(
946 b.DoB(1),
947 " Expected: the expectation is active\n"
948 " Actual: it is retired");
949}
950
951// Tests that Google Mock explains that an expectation that doesn't
952// match the arguments doesn't match the call.
953TEST(UnexpectedCallTest, UnmatchedArguments) {
954 MockB b;
955 EXPECT_CALL(b, DoB(1));
956
957 EXPECT_NONFATAL_FAILURE(
958 b.DoB(2),
959 " Expected arg #0: is equal to 1\n"
960 " Actual: 2\n");
961 b.DoB(1);
962}
963
964#ifdef GMOCK_HAS_REGEX
965
966// Tests that Google Mock explains that an expectation with
967// unsatisfied pre-requisites doesn't match the call.
968TEST(UnexpectedCallTest, UnsatisifiedPrerequisites) {
969 Sequence s1, s2;
970 MockB b;
971 EXPECT_CALL(b, DoB(1))
972 .InSequence(s1);
973 EXPECT_CALL(b, DoB(2))
974 .Times(AnyNumber())
975 .InSequence(s1);
976 EXPECT_CALL(b, DoB(3))
977 .InSequence(s2);
978 EXPECT_CALL(b, DoB(4))
979 .InSequence(s1, s2);
980
981 ::testing::TestPartResultArray failures;
982 {
983 ::testing::ScopedFakeTestPartResultReporter reporter(&failures);
984 b.DoB(4);
985 // Now 'failures' contains the Google Test failures generated by
986 // the above statement.
987 }
988
989 // There should be one non-fatal failure.
990 ASSERT_EQ(1, failures.size());
991 const ::testing::TestPartResult& r = failures.GetTestPartResult(0);
992 EXPECT_EQ(::testing::TPRT_NONFATAL_FAILURE, r.type());
993
994 // Verifies that the failure message contains the two unsatisfied
995 // pre-requisites but not the satisfied one.
996 const char* const pattern =
997#if GMOCK_USES_PCRE
998 // PCRE has trouble using (.|\n) to match any character, but
999 // supports the (?s) prefix for using . to match any character.
1000 "(?s)the following immediate pre-requisites are not satisfied:\n"
1001 ".*: pre-requisite #0\n"
1002 ".*: pre-requisite #1";
1003#else
1004 // POSIX RE doesn't understand the (?s) prefix, but has no trouble
1005 // with (.|\n).
1006 "the following immediate pre-requisites are not satisfied:\n"
1007 "(.|\n)*: pre-requisite #0\n"
1008 "(.|\n)*: pre-requisite #1";
1009#endif // GMOCK_USES_PCRE
1010
1011 EXPECT_TRUE(
1012 ::testing::internal::RE::PartialMatch(r.message(), pattern))
1013 << " where the message is " << r.message();
1014 b.DoB(1);
1015 b.DoB(3);
1016 b.DoB(4);
1017}
1018
1019#endif // GMOCK_HAS_REGEX
1020
zhanyong.wan652540a2009-02-23 23:37:29 +00001021#if GTEST_HAS_DEATH_TEST
zhanyong.wan5b95fa72009-01-27 22:28:45 +00001022
1023TEST(UndefinedReturnValueTest, ReturnValueIsMandatory) {
1024 MockA a;
1025 // TODO(wan@google.com): We should really verify the output message,
1026 // but we cannot yet due to that EXPECT_DEATH only captures stderr
1027 // while Google Mock logs to stdout.
1028 EXPECT_DEATH(a.ReturnResult(1), "");
1029}
1030
1031#endif // GTEST_HAS_DEATH_TEST
1032
shiqiane35fdd92008-12-10 05:08:54 +00001033// Tests that an excessive call (one whose arguments match the
1034// matchers but is called too many times) performs the default action.
1035TEST(ExcessiveCallTest, DoesDefaultAction) {
1036 // When there is an ON_CALL() statement, the action specified by it
1037 // should be taken.
1038 MockA a;
1039 ON_CALL(a, Binary(_, _))
1040 .WillByDefault(Return(true));
1041 EXPECT_CALL(a, Binary(0, 0));
1042 a.Binary(0, 0);
1043 bool result = false;
1044 EXPECT_NONFATAL_FAILURE(result = a.Binary(0, 0),
1045 "Mock function called more times than expected");
1046 EXPECT_TRUE(result);
1047
1048 // When there is no ON_CALL(), the default value for the return type
1049 // should be returned.
1050 MockB b;
1051 EXPECT_CALL(b, DoB(0))
1052 .Times(0);
1053 int n = -1;
1054 EXPECT_NONFATAL_FAILURE(n = b.DoB(0),
1055 "Mock function called more times than expected");
1056 EXPECT_EQ(0, n);
1057}
1058
1059// Tests that when a void function is called too many times,
1060// the failure message contains the argument values.
1061TEST(ExcessiveCallTest, GeneratesFailureForVoidFunction) {
1062 MockA a;
1063 EXPECT_CALL(a, DoA(_))
1064 .Times(0);
1065 EXPECT_NONFATAL_FAILURE(
1066 a.DoA(9),
1067 "Mock function called more times than expected - returning directly.\n"
1068 " Function call: DoA(9)\n"
1069 " Expected: to be never called\n"
1070 " Actual: called once - over-saturated and active");
1071}
1072
1073// Tests that when a non-void function is called too many times, the
1074// failure message contains the argument values and the return value.
1075TEST(ExcessiveCallTest, GeneratesFailureForNonVoidFunction) {
1076 MockB b;
1077 EXPECT_CALL(b, DoB(_));
1078 b.DoB(1);
1079 EXPECT_NONFATAL_FAILURE(
1080 b.DoB(2),
1081 "Mock function called more times than expected - "
1082 "returning default value.\n"
1083 " Function call: DoB(2)\n"
1084 " Returns: 0\n"
1085 " Expected: to be called once\n"
1086 " Actual: called twice - over-saturated and active");
1087}
1088
1089// Tests using sequences.
1090
1091TEST(InSequenceTest, AllExpectationInScopeAreInSequence) {
1092 MockA a;
1093 {
1094 InSequence dummy;
1095
1096 EXPECT_CALL(a, DoA(1));
1097 EXPECT_CALL(a, DoA(2));
1098 }
1099
1100 EXPECT_NONFATAL_FAILURE({ // NOLINT
1101 a.DoA(2);
1102 }, "Unexpected mock function call");
1103
1104 a.DoA(1);
1105 a.DoA(2);
1106}
1107
1108TEST(InSequenceTest, NestedInSequence) {
1109 MockA a;
1110 {
1111 InSequence dummy;
1112
1113 EXPECT_CALL(a, DoA(1));
1114 {
1115 InSequence dummy2;
1116
1117 EXPECT_CALL(a, DoA(2));
1118 EXPECT_CALL(a, DoA(3));
1119 }
1120 }
1121
1122 EXPECT_NONFATAL_FAILURE({ // NOLINT
1123 a.DoA(1);
1124 a.DoA(3);
1125 }, "Unexpected mock function call");
1126
1127 a.DoA(2);
1128 a.DoA(3);
1129}
1130
1131TEST(InSequenceTest, ExpectationsOutOfScopeAreNotAffected) {
1132 MockA a;
1133 {
1134 InSequence dummy;
1135
1136 EXPECT_CALL(a, DoA(1));
1137 EXPECT_CALL(a, DoA(2));
1138 }
1139 EXPECT_CALL(a, DoA(3));
1140
1141 EXPECT_NONFATAL_FAILURE({ // NOLINT
1142 a.DoA(2);
1143 }, "Unexpected mock function call");
1144
1145 a.DoA(3);
1146 a.DoA(1);
1147 a.DoA(2);
1148}
1149
1150// Tests that any order is allowed when no sequence is used.
1151TEST(SequenceTest, AnyOrderIsOkByDefault) {
1152 {
1153 MockA a;
1154 MockB b;
1155
1156 EXPECT_CALL(a, DoA(1));
1157 EXPECT_CALL(b, DoB())
1158 .Times(AnyNumber());
1159
1160 a.DoA(1);
1161 b.DoB();
1162 }
1163
1164 { // NOLINT
1165 MockA a;
1166 MockB b;
1167
1168 EXPECT_CALL(a, DoA(1));
1169 EXPECT_CALL(b, DoB())
1170 .Times(AnyNumber());
1171
1172 b.DoB();
1173 a.DoA(1);
1174 }
1175}
1176
zhanyong.wan652540a2009-02-23 23:37:29 +00001177#if GTEST_HAS_DEATH_TEST
shiqiane35fdd92008-12-10 05:08:54 +00001178
1179// Tests that the calls must be in strict order when a complete order
1180// is specified.
1181TEST(SequenceTest, CallsMustBeInStrictOrderWhenSaidSo) {
1182 MockA a;
1183 Sequence s;
1184
1185 EXPECT_CALL(a, ReturnResult(1))
1186 .InSequence(s)
1187 .WillOnce(Return(Result()));
1188
1189 EXPECT_CALL(a, ReturnResult(2))
1190 .InSequence(s)
1191 .WillOnce(Return(Result()));
1192
1193 EXPECT_CALL(a, ReturnResult(3))
1194 .InSequence(s)
1195 .WillOnce(Return(Result()));
1196
1197 EXPECT_DEATH({ // NOLINT
1198 a.ReturnResult(1);
1199 a.ReturnResult(3);
1200 a.ReturnResult(2);
1201 }, "");
1202
1203 EXPECT_DEATH({ // NOLINT
1204 a.ReturnResult(2);
1205 a.ReturnResult(1);
1206 a.ReturnResult(3);
1207 }, "");
1208
1209 a.ReturnResult(1);
1210 a.ReturnResult(2);
1211 a.ReturnResult(3);
1212}
1213
1214// Tests specifying a DAG using multiple sequences.
1215TEST(SequenceTest, CallsMustConformToSpecifiedDag) {
1216 MockA a;
1217 MockB b;
1218 Sequence x, y;
1219
1220 EXPECT_CALL(a, ReturnResult(1))
1221 .InSequence(x)
1222 .WillOnce(Return(Result()));
1223
1224 EXPECT_CALL(b, DoB())
1225 .Times(2)
1226 .InSequence(y);
1227
1228 EXPECT_CALL(a, ReturnResult(2))
1229 .InSequence(x, y)
1230 .WillRepeatedly(Return(Result()));
1231
1232 EXPECT_CALL(a, ReturnResult(3))
1233 .InSequence(x)
1234 .WillOnce(Return(Result()));
1235
1236 EXPECT_DEATH({ // NOLINT
1237 a.ReturnResult(1);
1238 b.DoB();
1239 a.ReturnResult(2);
1240 }, "");
1241
1242 EXPECT_DEATH({ // NOLINT
1243 a.ReturnResult(2);
1244 }, "");
1245
1246 EXPECT_DEATH({ // NOLINT
1247 a.ReturnResult(3);
1248 }, "");
1249
1250 EXPECT_DEATH({ // NOLINT
1251 a.ReturnResult(1);
1252 b.DoB();
1253 b.DoB();
1254 a.ReturnResult(3);
1255 a.ReturnResult(2);
1256 }, "");
1257
1258 b.DoB();
1259 a.ReturnResult(1);
1260 b.DoB();
1261 a.ReturnResult(3);
1262}
1263
1264#endif // GTEST_HAS_DEATH_TEST
1265
1266TEST(SequenceTest, Retirement) {
1267 MockA a;
1268 Sequence s;
1269
1270 EXPECT_CALL(a, DoA(1))
1271 .InSequence(s);
1272 EXPECT_CALL(a, DoA(_))
1273 .InSequence(s)
1274 .RetiresOnSaturation();
1275 EXPECT_CALL(a, DoA(1))
1276 .InSequence(s);
1277
1278 a.DoA(1);
1279 a.DoA(2);
1280 a.DoA(1);
1281}
1282
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001283// Tests Expectation.
1284
1285TEST(ExpectationTest, ConstrutorsWork) {
1286 MockA a;
1287 Expectation e1; // Default ctor.
1288 Expectation e2 = EXPECT_CALL(a, DoA(1)); // Ctor from EXPECT_CALL.
1289 Expectation e3 = e2; // Copy ctor.
1290
1291 EXPECT_THAT(e1, Ne(e2));
1292 EXPECT_THAT(e2, Eq(e3));
1293 a.DoA(1);
1294}
1295
1296TEST(ExpectationTest, AssignmentWorks) {
1297 MockA a;
1298 Expectation e1;
1299 Expectation e2 = EXPECT_CALL(a, DoA(1));
1300
1301 EXPECT_THAT(e1, Ne(e2));
1302
1303 e1 = e2;
1304 EXPECT_THAT(e1, Eq(e2));
1305
1306 a.DoA(1);
1307}
1308
1309// Tests ExpectationSet.
1310
1311TEST(ExpectationSetTest, MemberTypesAreCorrect) {
1312 ::testing::StaticAssertTypeEq<Expectation, ExpectationSet::value_type>();
1313}
1314
1315TEST(ExpectationSetTest, ConstructorsWork) {
1316 MockA a;
1317
1318 Expectation e1;
1319 const Expectation e2;
1320 ExpectationSet es1; // Default ctor.
1321 ExpectationSet es2 = EXPECT_CALL(a, DoA(1)); // Ctor from EXPECT_CALL.
1322 ExpectationSet es3 = e1; // Ctor from Expectation.
1323 ExpectationSet es4(e1); // Ctor from Expectation; alternative syntax.
1324 ExpectationSet es5 = e2; // Ctor from const Expectation.
1325 ExpectationSet es6(e2); // Ctor from const Expectation; alternative syntax.
1326 ExpectationSet es7 = es2; // Copy ctor.
1327
1328 EXPECT_EQ(0, es1.size());
1329 EXPECT_EQ(1, es2.size());
1330 EXPECT_EQ(1, es3.size());
1331 EXPECT_EQ(1, es4.size());
1332 EXPECT_EQ(1, es5.size());
1333 EXPECT_EQ(1, es6.size());
1334 EXPECT_EQ(1, es7.size());
1335
1336 EXPECT_THAT(es3, Ne(es2));
1337 EXPECT_THAT(es4, Eq(es3));
1338 EXPECT_THAT(es5, Eq(es4));
1339 EXPECT_THAT(es6, Eq(es5));
1340 EXPECT_THAT(es7, Eq(es2));
1341 a.DoA(1);
1342}
1343
1344TEST(ExpectationSetTest, AssignmentWorks) {
1345 ExpectationSet es1;
1346 ExpectationSet es2 = Expectation();
1347
1348 es1 = es2;
1349 EXPECT_EQ(1, es1.size());
1350 EXPECT_THAT(*(es1.begin()), Eq(Expectation()));
1351 EXPECT_THAT(es1, Eq(es2));
1352}
1353
1354TEST(ExpectationSetTest, InsertionWorks) {
1355 ExpectationSet es1;
1356 Expectation e1;
1357 es1 += e1;
1358 EXPECT_EQ(1, es1.size());
1359 EXPECT_THAT(*(es1.begin()), Eq(e1));
1360
1361 MockA a;
1362 Expectation e2 = EXPECT_CALL(a, DoA(1));
1363 es1 += e2;
1364 EXPECT_EQ(2, es1.size());
1365
1366 ExpectationSet::const_iterator it1 = es1.begin();
1367 ExpectationSet::const_iterator it2 = it1;
1368 ++it2;
1369 EXPECT_TRUE(*it1 == e1 || *it2 == e1); // e1 must be in the set.
1370 EXPECT_TRUE(*it1 == e2 || *it2 == e2); // e2 must be in the set too.
1371 a.DoA(1);
1372}
1373
1374TEST(ExpectationSetTest, SizeWorks) {
1375 ExpectationSet es;
1376 EXPECT_EQ(0, es.size());
1377
1378 es += Expectation();
1379 EXPECT_EQ(1, es.size());
1380
1381 MockA a;
1382 es += EXPECT_CALL(a, DoA(1));
1383 EXPECT_EQ(2, es.size());
1384
1385 a.DoA(1);
1386}
1387
1388TEST(ExpectationSetTest, IsEnumerable) {
1389 ExpectationSet es;
1390 EXPECT_THAT(es.begin(), Eq(es.end()));
1391
1392 es += Expectation();
1393 ExpectationSet::const_iterator it = es.begin();
1394 EXPECT_THAT(it, Ne(es.end()));
1395 EXPECT_THAT(*it, Eq(Expectation()));
1396 ++it;
1397 EXPECT_THAT(it, Eq(es.end()));
1398}
1399
1400// Tests the .After() clause.
1401
1402TEST(AfterTest, SucceedsWhenPartialOrderIsSatisfied) {
1403 MockA a;
1404 ExpectationSet es;
1405 es += EXPECT_CALL(a, DoA(1));
1406 es += EXPECT_CALL(a, DoA(2));
1407 EXPECT_CALL(a, DoA(3))
1408 .After(es);
1409
1410 a.DoA(1);
1411 a.DoA(2);
1412 a.DoA(3);
1413}
1414
1415TEST(AfterTest, SucceedsWhenTotalOrderIsSatisfied) {
1416 MockA a;
1417 MockB b;
1418 // The following also verifies that const Expectation objects work
1419 // too. Do not remove the const modifiers.
1420 const Expectation e1 = EXPECT_CALL(a, DoA(1));
1421 const Expectation e2 = EXPECT_CALL(b, DoB())
1422 .Times(2)
1423 .After(e1);
1424 EXPECT_CALL(a, DoA(2)).After(e2);
1425
1426 a.DoA(1);
1427 b.DoB();
1428 b.DoB();
1429 a.DoA(2);
1430}
1431
zhanyong.wan9571b282009-08-07 07:15:56 +00001432#if GTEST_HAS_DEATH_TEST
1433
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001434// Calls must be in strict order when specified so.
1435TEST(AfterTest, CallsMustBeInStrictOrderWhenSpecifiedSo) {
1436 MockA a;
1437 MockB b;
1438 Expectation e1 = EXPECT_CALL(a, DoA(1));
1439 Expectation e2 = EXPECT_CALL(b, DoB())
1440 .Times(2)
1441 .After(e1);
1442 EXPECT_CALL(a, ReturnResult(2))
1443 .After(e2)
1444 .WillOnce(Return(Result()));
1445
1446 a.DoA(1);
1447 // If a call to ReturnResult() violates the specified order, no
1448 // matching expectation will be found, and thus the default action
1449 // will be done. Since the return type of ReturnResult() is not a
1450 // built-in type, gmock won't know what to return and will thus
1451 // abort the program. Therefore a death test can tell us whether
1452 // gmock catches the order violation correctly.
1453 //
1454 // gtest and gmock print messages to stdout, which isn't captured by
1455 // death tests. Therefore we have to match with an empty regular
1456 // expression in all the EXPECT_DEATH()s.
1457 EXPECT_DEATH(a.ReturnResult(2), "");
1458
1459 b.DoB();
1460 EXPECT_DEATH(a.ReturnResult(2), "");
1461
1462 b.DoB();
1463 a.ReturnResult(2);
1464}
1465
1466// Calls must satisfy the partial order when specified so.
1467TEST(AfterTest, CallsMustSatisfyPartialOrderWhenSpecifiedSo) {
1468 MockA a;
1469 Expectation e = EXPECT_CALL(a, DoA(1));
1470 const ExpectationSet es = EXPECT_CALL(a, DoA(2));
1471 EXPECT_CALL(a, ReturnResult(3))
1472 .After(e, es)
1473 .WillOnce(Return(Result()));
1474
1475 EXPECT_DEATH(a.ReturnResult(3), "");
1476
1477 a.DoA(2);
1478 EXPECT_DEATH(a.ReturnResult(3), "");
1479
1480 a.DoA(1);
1481 a.ReturnResult(3);
1482}
1483
1484// .After() can be combined with .InSequence().
1485TEST(AfterTest, CanBeUsedWithInSequence) {
1486 MockA a;
1487 Sequence s;
1488 Expectation e = EXPECT_CALL(a, DoA(1));
1489 EXPECT_CALL(a, DoA(2)).InSequence(s);
1490 EXPECT_CALL(a, ReturnResult(3))
1491 .InSequence(s).After(e)
1492 .WillOnce(Return(Result()));
1493
1494 a.DoA(1);
1495 EXPECT_DEATH(a.ReturnResult(3), "");
1496
1497 a.DoA(2);
1498 a.ReturnResult(3);
1499}
1500
zhanyong.wan9571b282009-08-07 07:15:56 +00001501#endif // GTEST_HAS_DEATH_TEST
1502
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001503// .After() can be called multiple times.
1504TEST(AfterTest, CanBeCalledManyTimes) {
1505 MockA a;
1506 Expectation e1 = EXPECT_CALL(a, DoA(1));
1507 Expectation e2 = EXPECT_CALL(a, DoA(2));
1508 Expectation e3 = EXPECT_CALL(a, DoA(3));
1509 EXPECT_CALL(a, DoA(4))
1510 .After(e1)
1511 .After(e2)
1512 .After(e3);
1513
1514 a.DoA(3);
1515 a.DoA(1);
1516 a.DoA(2);
1517 a.DoA(4);
1518}
1519
1520// .After() accepts up to 5 arguments.
1521TEST(AfterTest, AcceptsUpToFiveArguments) {
1522 MockA a;
1523 Expectation e1 = EXPECT_CALL(a, DoA(1));
1524 Expectation e2 = EXPECT_CALL(a, DoA(2));
1525 Expectation e3 = EXPECT_CALL(a, DoA(3));
1526 ExpectationSet es1 = EXPECT_CALL(a, DoA(4));
1527 ExpectationSet es2 = EXPECT_CALL(a, DoA(5));
1528 EXPECT_CALL(a, DoA(6))
1529 .After(e1, e2, e3, es1, es2);
1530
1531 a.DoA(5);
1532 a.DoA(2);
1533 a.DoA(4);
1534 a.DoA(1);
1535 a.DoA(3);
1536 a.DoA(6);
1537}
1538
zhanyong.wan9571b282009-08-07 07:15:56 +00001539#if GTEST_HAS_DEATH_TEST
1540
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001541// .After() allows input to contain duplicated Expectations.
1542TEST(AfterTest, AcceptsDuplicatedInput) {
1543 MockA a;
1544 Expectation e1 = EXPECT_CALL(a, DoA(1));
1545 Expectation e2 = EXPECT_CALL(a, DoA(2));
1546 ExpectationSet es;
1547 es += e1;
1548 es += e2;
1549 EXPECT_CALL(a, ReturnResult(3))
1550 .After(e1, e2, es, e1)
1551 .WillOnce(Return(Result()));
1552
1553 a.DoA(1);
1554 EXPECT_DEATH(a.ReturnResult(3), "");
1555
1556 a.DoA(2);
1557 a.ReturnResult(3);
1558}
1559
zhanyong.wan9571b282009-08-07 07:15:56 +00001560#endif // GTEST_HAS_DEATH_TEST
1561
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001562// An Expectation added to an ExpectationSet after it has been used in
1563// an .After() has no effect.
1564TEST(AfterTest, ChangesToExpectationSetHaveNoEffectAfterwards) {
1565 MockA a;
1566 ExpectationSet es1 = EXPECT_CALL(a, DoA(1));
1567 Expectation e2 = EXPECT_CALL(a, DoA(2));
1568 EXPECT_CALL(a, DoA(3))
1569 .After(es1);
1570 es1 += e2;
1571
1572 a.DoA(1);
1573 a.DoA(3);
1574 a.DoA(2);
1575}
1576
shiqiane35fdd92008-12-10 05:08:54 +00001577// Tests that Google Mock correctly handles calls to mock functions
1578// after a mock object owning one of their pre-requisites has died.
1579
1580// Tests that calls that satisfy the original spec are successful.
1581TEST(DeletingMockEarlyTest, Success1) {
1582 MockB* const b1 = new MockB;
1583 MockA* const a = new MockA;
1584 MockB* const b2 = new MockB;
1585
1586 {
1587 InSequence dummy;
1588 EXPECT_CALL(*b1, DoB(_))
1589 .WillOnce(Return(1));
1590 EXPECT_CALL(*a, Binary(_, _))
1591 .Times(AnyNumber())
1592 .WillRepeatedly(Return(true));
1593 EXPECT_CALL(*b2, DoB(_))
1594 .Times(AnyNumber())
1595 .WillRepeatedly(Return(2));
1596 }
1597
1598 EXPECT_EQ(1, b1->DoB(1));
1599 delete b1;
1600 // a's pre-requisite has died.
1601 EXPECT_TRUE(a->Binary(0, 1));
1602 delete b2;
1603 // a's successor has died.
1604 EXPECT_TRUE(a->Binary(1, 2));
1605 delete a;
1606}
1607
1608// Tests that calls that satisfy the original spec are successful.
1609TEST(DeletingMockEarlyTest, Success2) {
1610 MockB* const b1 = new MockB;
1611 MockA* const a = new MockA;
1612 MockB* const b2 = new MockB;
1613
1614 {
1615 InSequence dummy;
1616 EXPECT_CALL(*b1, DoB(_))
1617 .WillOnce(Return(1));
1618 EXPECT_CALL(*a, Binary(_, _))
1619 .Times(AnyNumber());
1620 EXPECT_CALL(*b2, DoB(_))
1621 .Times(AnyNumber())
1622 .WillRepeatedly(Return(2));
1623 }
1624
1625 delete a; // a is trivially satisfied.
1626 EXPECT_EQ(1, b1->DoB(1));
1627 EXPECT_EQ(2, b2->DoB(2));
1628 delete b1;
1629 delete b2;
1630}
1631
zhanyong.wan6f147692009-03-03 06:44:08 +00001632// Tests that it's OK to delete a mock object itself in its action.
1633
1634ACTION_P(Delete, ptr) { delete ptr; }
1635
1636TEST(DeletingMockEarlyTest, CanDeleteSelfInActionReturningVoid) {
1637 MockA* const a = new MockA;
1638 EXPECT_CALL(*a, DoA(_)).WillOnce(Delete(a));
1639 a->DoA(42); // This will cause a to be deleted.
1640}
1641
1642TEST(DeletingMockEarlyTest, CanDeleteSelfInActionReturningValue) {
1643 MockA* const a = new MockA;
1644 EXPECT_CALL(*a, ReturnResult(_))
1645 .WillOnce(DoAll(Delete(a), Return(Result())));
1646 a->ReturnResult(42); // This will cause a to be deleted.
1647}
1648
1649// Tests that calls that violate the original spec yield failures.
shiqiane35fdd92008-12-10 05:08:54 +00001650TEST(DeletingMockEarlyTest, Failure1) {
1651 MockB* const b1 = new MockB;
1652 MockA* const a = new MockA;
1653 MockB* const b2 = new MockB;
1654
1655 {
1656 InSequence dummy;
1657 EXPECT_CALL(*b1, DoB(_))
1658 .WillOnce(Return(1));
1659 EXPECT_CALL(*a, Binary(_, _))
1660 .Times(AnyNumber());
1661 EXPECT_CALL(*b2, DoB(_))
1662 .Times(AnyNumber())
1663 .WillRepeatedly(Return(2));
1664 }
1665
1666 delete a; // a is trivially satisfied.
1667 EXPECT_NONFATAL_FAILURE({
1668 b2->DoB(2);
1669 }, "Unexpected mock function call");
1670 EXPECT_EQ(1, b1->DoB(1));
1671 delete b1;
1672 delete b2;
1673}
1674
zhanyong.wan6f147692009-03-03 06:44:08 +00001675// Tests that calls that violate the original spec yield failures.
shiqiane35fdd92008-12-10 05:08:54 +00001676TEST(DeletingMockEarlyTest, Failure2) {
1677 MockB* const b1 = new MockB;
1678 MockA* const a = new MockA;
1679 MockB* const b2 = new MockB;
1680
1681 {
1682 InSequence dummy;
1683 EXPECT_CALL(*b1, DoB(_));
1684 EXPECT_CALL(*a, Binary(_, _))
1685 .Times(AnyNumber());
1686 EXPECT_CALL(*b2, DoB(_))
1687 .Times(AnyNumber());
1688 }
1689
1690 EXPECT_NONFATAL_FAILURE(delete b1,
1691 "Actual: never called");
1692 EXPECT_NONFATAL_FAILURE(a->Binary(0, 1),
1693 "Unexpected mock function call");
1694 EXPECT_NONFATAL_FAILURE(b2->DoB(1),
1695 "Unexpected mock function call");
1696 delete a;
1697 delete b2;
1698}
1699
1700class EvenNumberCardinality : public CardinalityInterface {
1701 public:
1702 // Returns true iff call_count calls will satisfy this cardinality.
1703 virtual bool IsSatisfiedByCallCount(int call_count) const {
1704 return call_count % 2 == 0;
1705 }
1706
1707 // Returns true iff call_count calls will saturate this cardinality.
1708 virtual bool IsSaturatedByCallCount(int call_count) const { return false; }
1709
1710 // Describes self to an ostream.
1711 virtual void DescribeTo(::std::ostream* os) const {
1712 *os << "called even number of times";
1713 }
1714};
1715
1716Cardinality EvenNumber() {
1717 return Cardinality(new EvenNumberCardinality);
1718}
1719
1720TEST(ExpectationBaseTest,
1721 AllPrerequisitesAreSatisfiedWorksForNonMonotonicCardinality) {
1722 MockA* a = new MockA;
1723 Sequence s;
1724
1725 EXPECT_CALL(*a, DoA(1))
1726 .Times(EvenNumber())
1727 .InSequence(s);
1728 EXPECT_CALL(*a, DoA(2))
1729 .Times(AnyNumber())
1730 .InSequence(s);
1731 EXPECT_CALL(*a, DoA(3))
1732 .Times(AnyNumber());
1733
1734 a->DoA(3);
1735 a->DoA(1);
1736 EXPECT_NONFATAL_FAILURE(a->DoA(2), "Unexpected mock function call");
1737 EXPECT_NONFATAL_FAILURE(delete a, "to be called even number of times");
1738}
1739
1740// The following tests verify the message generated when a mock
1741// function is called.
1742
1743struct Printable {
1744};
1745
1746inline void operator<<(::std::ostream& os, const Printable&) {
1747 os << "Printable";
1748}
1749
1750struct Unprintable {
1751 Unprintable() : value(0) {}
1752 int value;
1753};
1754
1755class MockC {
1756 public:
1757 MOCK_METHOD6(VoidMethod, void(bool cond, int n, string s, void* p,
1758 const Printable& x, Unprintable y));
1759 MOCK_METHOD0(NonVoidMethod, int()); // NOLINT
1760};
1761
1762// TODO(wan@google.com): find a way to re-enable these tests.
1763#if 0
1764
1765// Tests that an uninteresting mock function call generates a warning
1766// containing the stack trace.
1767TEST(FunctionCallMessageTest, UninterestingCallGeneratesFyiWithStackTrace) {
1768 MockC c;
1769 CaptureTestStdout();
1770 c.VoidMethod(false, 5, "Hi", NULL, Printable(), Unprintable());
1771 const string& output = GetCapturedTestStdout();
1772 EXPECT_PRED_FORMAT2(IsSubstring, "GMOCK WARNING", output);
1773 EXPECT_PRED_FORMAT2(IsSubstring, "Stack trace:", output);
1774#ifndef NDEBUG
1775 // We check the stack trace content in dbg-mode only, as opt-mode
1776 // may inline the call we are interested in seeing.
1777
1778 // Verifies that a void mock function's name appears in the stack
1779 // trace.
1780 EXPECT_PRED_FORMAT2(IsSubstring, "::MockC::VoidMethod(", output);
1781
1782 // Verifies that a non-void mock function's name appears in the
1783 // stack trace.
1784 CaptureTestStdout();
1785 c.NonVoidMethod();
1786 const string& output2 = GetCapturedTestStdout();
1787 EXPECT_PRED_FORMAT2(IsSubstring, "::MockC::NonVoidMethod(", output2);
1788#endif // NDEBUG
1789}
1790
1791// Tests that an uninteresting mock function call causes the function
1792// arguments and return value to be printed.
1793TEST(FunctionCallMessageTest, UninterestingCallPrintsArgumentsAndReturnValue) {
1794 // A non-void mock function.
1795 MockB b;
1796 CaptureTestStdout();
1797 b.DoB();
1798 const string& output1 = GetCapturedTestStdout();
1799 EXPECT_PRED_FORMAT2(
1800 IsSubstring,
1801 "Uninteresting mock function call - returning default value.\n"
1802 " Function call: DoB()\n"
1803 " Returns: 0\n", output1);
1804 // Makes sure the return value is printed.
1805
1806 // A void mock function.
1807 MockC c;
1808 CaptureTestStdout();
1809 c.VoidMethod(false, 5, "Hi", NULL, Printable(), Unprintable());
1810 const string& output2 = GetCapturedTestStdout();
1811 EXPECT_PRED2(RE::PartialMatch, output2,
1812 "Uninteresting mock function call - returning directly\\.\n"
1813 " Function call: VoidMethod"
1814 "\\(false, 5, \"Hi\", NULL, @0x\\w+ "
1815 "Printable, 4-byte object <0000 0000>\\)");
1816 // A void function has no return value to print.
1817}
1818
1819// Tests how the --gmock_verbose flag affects Google Mock's output.
1820
1821class GMockVerboseFlagTest : public testing::Test {
1822 public:
1823 // Verifies that the given Google Mock output is correct. (When
1824 // should_print is true, the output should match the given regex and
1825 // contain the given function name in the stack trace. When it's
1826 // false, the output should be empty.)
1827 void VerifyOutput(const string& output, bool should_print,
1828 const string& regex,
1829 const string& function_name) {
1830 if (should_print) {
1831 EXPECT_PRED2(RE::PartialMatch, output, regex);
1832#ifndef NDEBUG
1833 // We check the stack trace content in dbg-mode only, as opt-mode
1834 // may inline the call we are interested in seeing.
1835 EXPECT_PRED_FORMAT2(IsSubstring, function_name, output);
1836#endif // NDEBUG
1837 } else {
1838 EXPECT_EQ("", output);
1839 }
1840 }
1841
1842 // Tests how the flag affects expected calls.
1843 void TestExpectedCall(bool should_print) {
1844 MockA a;
1845 EXPECT_CALL(a, DoA(5));
1846 EXPECT_CALL(a, Binary(_, 1))
1847 .WillOnce(Return(true));
1848
1849 // A void-returning function.
1850 CaptureTestStdout();
1851 a.DoA(5);
1852 VerifyOutput(
1853 GetCapturedTestStdout(),
1854 should_print,
1855 "Expected mock function call\\.\n"
1856 " Function call: DoA\\(5\\)\n"
1857 "Stack trace:",
1858 "MockA::DoA");
1859
1860 // A non-void-returning function.
1861 CaptureTestStdout();
1862 a.Binary(2, 1);
1863 VerifyOutput(
1864 GetCapturedTestStdout(),
1865 should_print,
1866 "Expected mock function call\\.\n"
1867 " Function call: Binary\\(2, 1\\)\n"
1868 " Returns: true\n"
1869 "Stack trace:",
1870 "MockA::Binary");
1871 }
1872
1873 // Tests how the flag affects uninteresting calls.
1874 void TestUninterestingCall(bool should_print) {
1875 MockA a;
1876
1877 // A void-returning function.
1878 CaptureTestStdout();
1879 a.DoA(5);
1880 VerifyOutput(
1881 GetCapturedTestStdout(),
1882 should_print,
1883 "\nGMOCK WARNING:\n"
1884 "Uninteresting mock function call - returning directly\\.\n"
1885 " Function call: DoA\\(5\\)\n"
1886 "Stack trace:\n"
1887 "[\\s\\S]*",
1888 "MockA::DoA");
1889
1890 // A non-void-returning function.
1891 CaptureTestStdout();
1892 a.Binary(2, 1);
1893 VerifyOutput(
1894 GetCapturedTestStdout(),
1895 should_print,
1896 "\nGMOCK WARNING:\n"
1897 "Uninteresting mock function call - returning default value\\.\n"
1898 " Function call: Binary\\(2, 1\\)\n"
1899 " Returns: false\n"
1900 "Stack trace:\n"
1901 "[\\s\\S]*",
1902 "MockA::Binary");
1903 }
1904};
1905
1906// Tests that --gmock_verbose=info causes both expected and
1907// uninteresting calls to be reported.
1908TEST_F(GMockVerboseFlagTest, Info) {
1909 GMOCK_FLAG(verbose) = kInfoVerbosity;
1910 TestExpectedCall(true);
1911 TestUninterestingCall(true);
1912}
1913
1914// Tests that --gmock_verbose=warning causes uninteresting calls to be
1915// reported.
1916TEST_F(GMockVerboseFlagTest, Warning) {
1917 GMOCK_FLAG(verbose) = kWarningVerbosity;
1918 TestExpectedCall(false);
1919 TestUninterestingCall(true);
1920}
1921
1922// Tests that --gmock_verbose=warning causes neither expected nor
1923// uninteresting calls to be reported.
1924TEST_F(GMockVerboseFlagTest, Error) {
1925 GMOCK_FLAG(verbose) = kErrorVerbosity;
1926 TestExpectedCall(false);
1927 TestUninterestingCall(false);
1928}
1929
1930// Tests that --gmock_verbose=SOME_INVALID_VALUE has the same effect
1931// as --gmock_verbose=warning.
1932TEST_F(GMockVerboseFlagTest, InvalidFlagIsTreatedAsWarning) {
1933 GMOCK_FLAG(verbose) = "invalid"; // Treated as "warning".
1934 TestExpectedCall(false);
1935 TestUninterestingCall(true);
1936}
1937
1938#endif // 0
1939
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001940// A helper class that generates a failure when printed. We use it to
1941// ensure that Google Mock doesn't print a value (even to an internal
1942// buffer) when it is not supposed to do so.
1943class PrintMeNot {};
1944
1945void PrintTo(PrintMeNot /* dummy */, ::std::ostream* /* os */) {
1946 ADD_FAILURE() << "Google Mock is printing a value that shouldn't be "
1947 << "printed even to an internal buffer.";
1948}
1949
1950class LogTestHelper {
1951 public:
1952 MOCK_METHOD1(Foo, PrintMeNot(PrintMeNot));
1953};
1954
1955class GMockLogTest : public ::testing::Test {
1956 protected:
zhanyong.wan81476f22009-06-22 23:30:47 +00001957 virtual void SetUp() {
1958 // The code needs to work when both ::string and ::std::string are
1959 // defined and the flag is implemented as a
1960 // testing::internal::String. In this case, without the call to
1961 // c_str(), the compiler will complain that it cannot figure out
1962 // whether the String flag should be converted to a ::string or an
1963 // ::std::string before being assigned to original_verbose_.
1964 original_verbose_ = GMOCK_FLAG(verbose).c_str();
1965 }
1966
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001967 virtual void TearDown() { GMOCK_FLAG(verbose) = original_verbose_; }
1968
1969 LogTestHelper helper_;
1970 string original_verbose_;
1971};
1972
1973TEST_F(GMockLogTest, DoesNotPrintGoodCallInternallyIfVerbosityIsWarning) {
1974 GMOCK_FLAG(verbose) = kWarningVerbosity;
1975 EXPECT_CALL(helper_, Foo(_))
1976 .WillOnce(Return(PrintMeNot()));
1977 helper_.Foo(PrintMeNot()); // This is an expected call.
1978}
1979
1980TEST_F(GMockLogTest, DoesNotPrintGoodCallInternallyIfVerbosityIsError) {
1981 GMOCK_FLAG(verbose) = kErrorVerbosity;
1982 EXPECT_CALL(helper_, Foo(_))
1983 .WillOnce(Return(PrintMeNot()));
1984 helper_.Foo(PrintMeNot()); // This is an expected call.
1985}
1986
1987TEST_F(GMockLogTest, DoesNotPrintWarningInternallyIfVerbosityIsError) {
1988 GMOCK_FLAG(verbose) = kErrorVerbosity;
1989 ON_CALL(helper_, Foo(_))
1990 .WillByDefault(Return(PrintMeNot()));
1991 helper_.Foo(PrintMeNot()); // This should generate a warning.
1992}
1993
1994// Tests Mock::AllowLeak().
1995
zhanyong.wandf35a762009-04-22 22:25:31 +00001996TEST(AllowLeakTest, AllowsLeakingUnusedMockObject) {
1997 MockA* a = new MockA;
1998 Mock::AllowLeak(a);
1999}
2000
2001TEST(AllowLeakTest, CanBeCalledBeforeOnCall) {
2002 MockA* a = new MockA;
2003 Mock::AllowLeak(a);
2004 ON_CALL(*a, DoA(_)).WillByDefault(Return());
2005 a->DoA(0);
2006}
2007
2008TEST(AllowLeakTest, CanBeCalledAfterOnCall) {
2009 MockA* a = new MockA;
2010 ON_CALL(*a, DoA(_)).WillByDefault(Return());
2011 Mock::AllowLeak(a);
2012}
2013
2014TEST(AllowLeakTest, CanBeCalledBeforeExpectCall) {
2015 MockA* a = new MockA;
2016 Mock::AllowLeak(a);
2017 EXPECT_CALL(*a, DoA(_));
2018 a->DoA(0);
2019}
2020
2021TEST(AllowLeakTest, CanBeCalledAfterExpectCall) {
2022 MockA* a = new MockA;
2023 EXPECT_CALL(*a, DoA(_)).Times(AnyNumber());
2024 Mock::AllowLeak(a);
2025}
2026
2027TEST(AllowLeakTest, WorksWhenBothOnCallAndExpectCallArePresent) {
2028 MockA* a = new MockA;
2029 ON_CALL(*a, DoA(_)).WillByDefault(Return());
2030 EXPECT_CALL(*a, DoA(_)).Times(AnyNumber());
2031 Mock::AllowLeak(a);
2032}
shiqiane35fdd92008-12-10 05:08:54 +00002033
2034// Tests that we can verify and clear a mock object's expectations
2035// when none of its methods has expectations.
2036TEST(VerifyAndClearExpectationsTest, NoMethodHasExpectations) {
2037 MockB b;
2038 ASSERT_TRUE(Mock::VerifyAndClearExpectations(&b));
2039
2040 // There should be no expectations on the methods now, so we can
2041 // freely call them.
2042 EXPECT_EQ(0, b.DoB());
2043 EXPECT_EQ(0, b.DoB(1));
2044}
2045
2046// Tests that we can verify and clear a mock object's expectations
2047// when some, but not all, of its methods have expectations *and* the
2048// verification succeeds.
2049TEST(VerifyAndClearExpectationsTest, SomeMethodsHaveExpectationsAndSucceed) {
2050 MockB b;
2051 EXPECT_CALL(b, DoB())
2052 .WillOnce(Return(1));
2053 b.DoB();
2054 ASSERT_TRUE(Mock::VerifyAndClearExpectations(&b));
2055
2056 // There should be no expectations on the methods now, so we can
2057 // freely call them.
2058 EXPECT_EQ(0, b.DoB());
2059 EXPECT_EQ(0, b.DoB(1));
2060}
2061
2062// Tests that we can verify and clear a mock object's expectations
2063// when some, but not all, of its methods have expectations *and* the
2064// verification fails.
2065TEST(VerifyAndClearExpectationsTest, SomeMethodsHaveExpectationsAndFail) {
2066 MockB b;
2067 EXPECT_CALL(b, DoB())
2068 .WillOnce(Return(1));
2069 bool result;
2070 EXPECT_NONFATAL_FAILURE(result = Mock::VerifyAndClearExpectations(&b),
2071 "Actual: never called");
2072 ASSERT_FALSE(result);
2073
2074 // There should be no expectations on the methods now, so we can
2075 // freely call them.
2076 EXPECT_EQ(0, b.DoB());
2077 EXPECT_EQ(0, b.DoB(1));
2078}
2079
2080// Tests that we can verify and clear a mock object's expectations
2081// when all of its methods have expectations.
2082TEST(VerifyAndClearExpectationsTest, AllMethodsHaveExpectations) {
2083 MockB b;
2084 EXPECT_CALL(b, DoB())
2085 .WillOnce(Return(1));
2086 EXPECT_CALL(b, DoB(_))
2087 .WillOnce(Return(2));
2088 b.DoB();
2089 b.DoB(1);
2090 ASSERT_TRUE(Mock::VerifyAndClearExpectations(&b));
2091
2092 // There should be no expectations on the methods now, so we can
2093 // freely call them.
2094 EXPECT_EQ(0, b.DoB());
2095 EXPECT_EQ(0, b.DoB(1));
2096}
2097
2098// Tests that we can verify and clear a mock object's expectations
2099// when a method has more than one expectation.
2100TEST(VerifyAndClearExpectationsTest, AMethodHasManyExpectations) {
2101 MockB b;
2102 EXPECT_CALL(b, DoB(0))
2103 .WillOnce(Return(1));
2104 EXPECT_CALL(b, DoB(_))
2105 .WillOnce(Return(2));
2106 b.DoB(1);
2107 bool result;
2108 EXPECT_NONFATAL_FAILURE(result = Mock::VerifyAndClearExpectations(&b),
2109 "Actual: never called");
2110 ASSERT_FALSE(result);
2111
2112 // There should be no expectations on the methods now, so we can
2113 // freely call them.
2114 EXPECT_EQ(0, b.DoB());
2115 EXPECT_EQ(0, b.DoB(1));
2116}
2117
2118// Tests that we can call VerifyAndClearExpectations() on the same
2119// mock object multiple times.
2120TEST(VerifyAndClearExpectationsTest, CanCallManyTimes) {
2121 MockB b;
2122 EXPECT_CALL(b, DoB());
2123 b.DoB();
2124 Mock::VerifyAndClearExpectations(&b);
2125
2126 EXPECT_CALL(b, DoB(_))
2127 .WillOnce(Return(1));
2128 b.DoB(1);
2129 Mock::VerifyAndClearExpectations(&b);
2130 Mock::VerifyAndClearExpectations(&b);
2131
2132 // There should be no expectations on the methods now, so we can
2133 // freely call them.
2134 EXPECT_EQ(0, b.DoB());
2135 EXPECT_EQ(0, b.DoB(1));
2136}
2137
2138// Tests that we can clear a mock object's default actions when none
2139// of its methods has default actions.
2140TEST(VerifyAndClearTest, NoMethodHasDefaultActions) {
2141 MockB b;
2142 // If this crashes or generates a failure, the test will catch it.
2143 Mock::VerifyAndClear(&b);
2144 EXPECT_EQ(0, b.DoB());
2145}
2146
2147// Tests that we can clear a mock object's default actions when some,
2148// but not all of its methods have default actions.
2149TEST(VerifyAndClearTest, SomeMethodsHaveDefaultActions) {
2150 MockB b;
2151 ON_CALL(b, DoB())
2152 .WillByDefault(Return(1));
2153
2154 Mock::VerifyAndClear(&b);
2155
2156 // Verifies that the default action of int DoB() was removed.
2157 EXPECT_EQ(0, b.DoB());
2158}
2159
2160// Tests that we can clear a mock object's default actions when all of
2161// its methods have default actions.
2162TEST(VerifyAndClearTest, AllMethodsHaveDefaultActions) {
2163 MockB b;
2164 ON_CALL(b, DoB())
2165 .WillByDefault(Return(1));
2166 ON_CALL(b, DoB(_))
2167 .WillByDefault(Return(2));
2168
2169 Mock::VerifyAndClear(&b);
2170
2171 // Verifies that the default action of int DoB() was removed.
2172 EXPECT_EQ(0, b.DoB());
2173
2174 // Verifies that the default action of int DoB(int) was removed.
2175 EXPECT_EQ(0, b.DoB(0));
2176}
2177
2178// Tests that we can clear a mock object's default actions when a
2179// method has more than one ON_CALL() set on it.
2180TEST(VerifyAndClearTest, AMethodHasManyDefaultActions) {
2181 MockB b;
2182 ON_CALL(b, DoB(0))
2183 .WillByDefault(Return(1));
2184 ON_CALL(b, DoB(_))
2185 .WillByDefault(Return(2));
2186
2187 Mock::VerifyAndClear(&b);
2188
2189 // Verifies that the default actions (there are two) of int DoB(int)
2190 // were removed.
2191 EXPECT_EQ(0, b.DoB(0));
2192 EXPECT_EQ(0, b.DoB(1));
2193}
2194
2195// Tests that we can call VerifyAndClear() on a mock object multiple
2196// times.
2197TEST(VerifyAndClearTest, CanCallManyTimes) {
2198 MockB b;
2199 ON_CALL(b, DoB())
2200 .WillByDefault(Return(1));
2201 Mock::VerifyAndClear(&b);
2202 Mock::VerifyAndClear(&b);
2203
2204 ON_CALL(b, DoB(_))
2205 .WillByDefault(Return(1));
2206 Mock::VerifyAndClear(&b);
2207
2208 EXPECT_EQ(0, b.DoB());
2209 EXPECT_EQ(0, b.DoB(1));
2210}
2211
2212// Tests that VerifyAndClear() works when the verification succeeds.
2213TEST(VerifyAndClearTest, Success) {
2214 MockB b;
2215 ON_CALL(b, DoB())
2216 .WillByDefault(Return(1));
2217 EXPECT_CALL(b, DoB(1))
2218 .WillOnce(Return(2));
2219
2220 b.DoB();
2221 b.DoB(1);
2222 ASSERT_TRUE(Mock::VerifyAndClear(&b));
2223
2224 // There should be no expectations on the methods now, so we can
2225 // freely call them.
2226 EXPECT_EQ(0, b.DoB());
2227 EXPECT_EQ(0, b.DoB(1));
2228}
2229
2230// Tests that VerifyAndClear() works when the verification fails.
2231TEST(VerifyAndClearTest, Failure) {
2232 MockB b;
2233 ON_CALL(b, DoB(_))
2234 .WillByDefault(Return(1));
2235 EXPECT_CALL(b, DoB())
2236 .WillOnce(Return(2));
2237
2238 b.DoB(1);
2239 bool result;
2240 EXPECT_NONFATAL_FAILURE(result = Mock::VerifyAndClear(&b),
2241 "Actual: never called");
2242 ASSERT_FALSE(result);
2243
2244 // There should be no expectations on the methods now, so we can
2245 // freely call them.
2246 EXPECT_EQ(0, b.DoB());
2247 EXPECT_EQ(0, b.DoB(1));
2248}
2249
2250// Tests that VerifyAndClear() works when the default actions and
2251// expectations are set on a const mock object.
2252TEST(VerifyAndClearTest, Const) {
2253 MockB b;
2254 ON_CALL(Const(b), DoB())
2255 .WillByDefault(Return(1));
2256
2257 EXPECT_CALL(Const(b), DoB())
2258 .WillOnce(DoDefault())
2259 .WillOnce(Return(2));
2260
2261 b.DoB();
2262 b.DoB();
2263 ASSERT_TRUE(Mock::VerifyAndClear(&b));
2264
2265 // There should be no expectations on the methods now, so we can
2266 // freely call them.
2267 EXPECT_EQ(0, b.DoB());
2268 EXPECT_EQ(0, b.DoB(1));
2269}
2270
2271// Tests that we can set default actions and expectations on a mock
2272// object after VerifyAndClear() has been called on it.
2273TEST(VerifyAndClearTest, CanSetDefaultActionsAndExpectationsAfterwards) {
2274 MockB b;
2275 ON_CALL(b, DoB())
2276 .WillByDefault(Return(1));
2277 EXPECT_CALL(b, DoB(_))
2278 .WillOnce(Return(2));
2279 b.DoB(1);
2280
2281 Mock::VerifyAndClear(&b);
2282
2283 EXPECT_CALL(b, DoB())
2284 .WillOnce(Return(3));
2285 ON_CALL(b, DoB(_))
2286 .WillByDefault(Return(4));
2287
2288 EXPECT_EQ(3, b.DoB());
2289 EXPECT_EQ(4, b.DoB(1));
2290}
2291
2292// Tests that calling VerifyAndClear() on one mock object does not
2293// affect other mock objects (either of the same type or not).
2294TEST(VerifyAndClearTest, DoesNotAffectOtherMockObjects) {
2295 MockA a;
2296 MockB b1;
2297 MockB b2;
2298
2299 ON_CALL(a, Binary(_, _))
2300 .WillByDefault(Return(true));
2301 EXPECT_CALL(a, Binary(_, _))
2302 .WillOnce(DoDefault())
2303 .WillOnce(Return(false));
2304
2305 ON_CALL(b1, DoB())
2306 .WillByDefault(Return(1));
2307 EXPECT_CALL(b1, DoB(_))
2308 .WillOnce(Return(2));
2309
2310 ON_CALL(b2, DoB())
2311 .WillByDefault(Return(3));
2312 EXPECT_CALL(b2, DoB(_));
2313
2314 b2.DoB(0);
2315 Mock::VerifyAndClear(&b2);
2316
2317 // Verifies that the default actions and expectations of a and b1
2318 // are still in effect.
2319 EXPECT_TRUE(a.Binary(0, 0));
2320 EXPECT_FALSE(a.Binary(0, 0));
2321
2322 EXPECT_EQ(1, b1.DoB());
2323 EXPECT_EQ(2, b1.DoB(0));
2324}
2325
2326// Tests that a mock function's action can call a mock function
2327// (either the same function or a different one) either as an explicit
2328// action or as a default action without causing a dead lock. It
2329// verifies that the action is not performed inside the critical
2330// section.
2331
2332void Helper(MockC* c) {
2333 c->NonVoidMethod();
2334}
2335
2336} // namespace
zhanyong.wandf35a762009-04-22 22:25:31 +00002337
zhanyong.wan9571b282009-08-07 07:15:56 +00002338// Allows the user to define his own main and then invoke gmock_main
2339// from it. This might be necessary on some platforms which require
2340// specific setup and teardown.
2341#if GMOCK_RENAME_MAIN
2342int gmock_main(int argc, char **argv) {
2343#else
zhanyong.wandf35a762009-04-22 22:25:31 +00002344int main(int argc, char **argv) {
zhanyong.wan9571b282009-08-07 07:15:56 +00002345#endif // GMOCK_RENAME_MAIN
zhanyong.wandf35a762009-04-22 22:25:31 +00002346 testing::InitGoogleMock(&argc, argv);
2347
2348 // Ensures that the tests pass no matter what value of
2349 // --gmock_catch_leaked_mocks and --gmock_verbose the user specifies.
2350 testing::GMOCK_FLAG(catch_leaked_mocks) = true;
2351 testing::GMOCK_FLAG(verbose) = testing::internal::kWarningVerbosity;
2352
2353 return RUN_ALL_TESTS();
2354}