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