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