blob: 0e2e0090be408b8ffbab3153c10c5ea72a08944c [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
zhanyong.wan53e08c42010-09-14 05:38:21 +000036#include "gmock/gmock-spec-builders.h"
shiqiane35fdd92008-12-10 05:08:54 +000037
38#include <ostream> // NOLINT
39#include <sstream>
40#include <string>
41
zhanyong.wan53e08c42010-09-14 05:38:21 +000042#include "gmock/gmock.h"
43#include "gmock/internal/gmock-port.h"
44#include "gtest/gtest.h"
45#include "gtest/gtest-spi.h"
vladloseve5121b52011-02-11 23:50:38 +000046#include "gtest/internal/gtest-port.h"
shiqiane35fdd92008-12-10 05:08:54 +000047
48namespace testing {
49namespace internal {
50
51// Helper class for testing the Expectation class template.
52class ExpectationTester {
53 public:
54 // Sets the call count of the given expectation to the given number.
55 void SetCallCount(int n, ExpectationBase* exp) {
56 exp->call_count_ = n;
57 }
58};
59
60} // namespace internal
61} // namespace testing
62
63namespace {
64
65using testing::_;
66using testing::AnyNumber;
67using testing::AtLeast;
68using testing::AtMost;
69using testing::Between;
70using testing::Cardinality;
71using testing::CardinalityInterface;
zhanyong.wand14aaed2010-01-14 05:36:32 +000072using testing::ContainsRegex;
shiqiane35fdd92008-12-10 05:08:54 +000073using testing::Const;
74using testing::DoAll;
75using testing::DoDefault;
zhanyong.wan41b9b0b2009-07-01 19:04:51 +000076using testing::Eq;
77using testing::Expectation;
78using testing::ExpectationSet;
shiqiane35fdd92008-12-10 05:08:54 +000079using testing::GMOCK_FLAG(verbose);
zhanyong.wanbf550852009-06-09 06:09:53 +000080using testing::Gt;
shiqiane35fdd92008-12-10 05:08:54 +000081using testing::InSequence;
82using testing::Invoke;
83using testing::InvokeWithoutArgs;
84using testing::IsSubstring;
85using testing::Lt;
86using testing::Message;
87using testing::Mock;
zhanyong.wan41b9b0b2009-07-01 19:04:51 +000088using testing::Ne;
shiqiane35fdd92008-12-10 05:08:54 +000089using testing::Return;
90using testing::Sequence;
vladlosev9bcb5f92011-10-24 23:41:07 +000091using testing::SetArgPointee;
zhanyong.wan470df422010-02-02 22:34:58 +000092using testing::internal::ExpectationTester;
vladloseve5121b52011-02-11 23:50:38 +000093using testing::internal::FormatFileLocation;
shiqiane35fdd92008-12-10 05:08:54 +000094using testing::internal::kErrorVerbosity;
95using testing::internal::kInfoVerbosity;
96using testing::internal::kWarningVerbosity;
vladlosev9bcb5f92011-10-24 23:41:07 +000097using testing::internal::linked_ptr;
shiqiane35fdd92008-12-10 05:08:54 +000098using testing::internal::string;
99
zhanyong.wan2516f602010-08-31 18:28:02 +0000100#if GTEST_HAS_STREAM_REDIRECTION
zhanyong.wan470df422010-02-02 22:34:58 +0000101using testing::HasSubstr;
102using testing::internal::CaptureStdout;
103using testing::internal::GetCapturedStdout;
zhanyong.wan2516f602010-08-31 18:28:02 +0000104#endif
zhanyong.wan470df422010-02-02 22:34:58 +0000105
zhanyong.waned6c9272011-02-23 19:39:27 +0000106class Incomplete;
107
108class MockIncomplete {
109 public:
110 // This line verifies that a mock method can take a by-reference
111 // argument of an incomplete type.
112 MOCK_METHOD1(ByRefFunc, void(const Incomplete& x));
113};
114
115// Tells Google Mock how to print a value of type Incomplete.
116void PrintTo(const Incomplete& x, ::std::ostream* os);
117
118TEST(MockMethodTest, CanInstantiateWithIncompleteArgType) {
119 // Even though this mock class contains a mock method that takes
120 // by-reference an argument whose type is incomplete, we can still
121 // use the mock, as long as Google Mock knows how to print the
122 // argument.
123 MockIncomplete incomplete;
124 EXPECT_CALL(incomplete, ByRefFunc(_))
125 .Times(AnyNumber());
126}
127
128// The definition of the printer for the argument type doesn't have to
129// be visible where the mock is used.
130void PrintTo(const Incomplete& /* x */, ::std::ostream* os) {
131 *os << "incomplete";
132}
133
shiqiane35fdd92008-12-10 05:08:54 +0000134class Result {};
135
136class MockA {
137 public:
zhanyong.wan32de5f52009-12-23 00:13:23 +0000138 MockA() {}
139
shiqiane35fdd92008-12-10 05:08:54 +0000140 MOCK_METHOD1(DoA, void(int n)); // NOLINT
141 MOCK_METHOD1(ReturnResult, Result(int n)); // NOLINT
142 MOCK_METHOD2(Binary, bool(int x, int y)); // NOLINT
zhanyong.wanbf550852009-06-09 06:09:53 +0000143 MOCK_METHOD2(ReturnInt, int(int x, int y)); // NOLINT
zhanyong.wan32de5f52009-12-23 00:13:23 +0000144
145 private:
146 GTEST_DISALLOW_COPY_AND_ASSIGN_(MockA);
shiqiane35fdd92008-12-10 05:08:54 +0000147};
148
149class MockB {
150 public:
zhanyong.wan32de5f52009-12-23 00:13:23 +0000151 MockB() {}
152
shiqiane35fdd92008-12-10 05:08:54 +0000153 MOCK_CONST_METHOD0(DoB, int()); // NOLINT
154 MOCK_METHOD1(DoB, int(int n)); // NOLINT
zhanyong.wan32de5f52009-12-23 00:13:23 +0000155
156 private:
157 GTEST_DISALLOW_COPY_AND_ASSIGN_(MockB);
shiqiane35fdd92008-12-10 05:08:54 +0000158};
159
vladlosev9bcb5f92011-10-24 23:41:07 +0000160class ReferenceHoldingMock {
161 public:
162 ReferenceHoldingMock() {}
163
164 MOCK_METHOD1(AcceptReference, void(linked_ptr<MockA>*));
165
166 private:
167 GTEST_DISALLOW_COPY_AND_ASSIGN_(ReferenceHoldingMock);
168};
169
shiqiane35fdd92008-12-10 05:08:54 +0000170// Tests that EXPECT_CALL and ON_CALL compile in a presence of macro
171// redefining a mock method name. This could happen, for example, when
172// the tested code #includes Win32 API headers which define many APIs
173// as macros, e.g. #define TextOut TextOutW.
174
175#define Method MethodW
176
177class CC {
178 public:
179 virtual ~CC() {}
180 virtual int Method() = 0;
181};
182class MockCC : public CC {
183 public:
zhanyong.wan32de5f52009-12-23 00:13:23 +0000184 MockCC() {}
185
shiqiane35fdd92008-12-10 05:08:54 +0000186 MOCK_METHOD0(Method, int());
zhanyong.wan32de5f52009-12-23 00:13:23 +0000187
188 private:
189 GTEST_DISALLOW_COPY_AND_ASSIGN_(MockCC);
shiqiane35fdd92008-12-10 05:08:54 +0000190};
191
192// Tests that a method with expanded name compiles.
193TEST(OnCallSyntaxTest, CompilesWithMethodNameExpandedFromMacro) {
194 MockCC cc;
195 ON_CALL(cc, Method());
196}
197
198// Tests that the method with expanded name not only compiles but runs
199// and returns a correct value, too.
200TEST(OnCallSyntaxTest, WorksWithMethodNameExpandedFromMacro) {
201 MockCC cc;
202 ON_CALL(cc, Method()).WillByDefault(Return(42));
203 EXPECT_EQ(42, cc.Method());
204}
205
206// Tests that a method with expanded name compiles.
207TEST(ExpectCallSyntaxTest, CompilesWithMethodNameExpandedFromMacro) {
208 MockCC cc;
209 EXPECT_CALL(cc, Method());
210 cc.Method();
211}
212
213// Tests that it works, too.
214TEST(ExpectCallSyntaxTest, WorksWithMethodNameExpandedFromMacro) {
215 MockCC cc;
216 EXPECT_CALL(cc, Method()).WillOnce(Return(42));
217 EXPECT_EQ(42, cc.Method());
218}
219
220#undef Method // Done with macro redefinition tests.
221
222// Tests that ON_CALL evaluates its arguments exactly once as promised
223// by Google Mock.
224TEST(OnCallSyntaxTest, EvaluatesFirstArgumentOnce) {
225 MockA a;
226 MockA* pa = &a;
227
228 ON_CALL(*pa++, DoA(_));
229 EXPECT_EQ(&a + 1, pa);
230}
231
232TEST(OnCallSyntaxTest, EvaluatesSecondArgumentOnce) {
233 MockA a;
234 int n = 0;
235
236 ON_CALL(a, DoA(n++));
237 EXPECT_EQ(1, n);
238}
239
240// Tests that the syntax of ON_CALL() is enforced at run time.
241
zhanyong.wanbf550852009-06-09 06:09:53 +0000242TEST(OnCallSyntaxTest, WithIsOptional) {
shiqiane35fdd92008-12-10 05:08:54 +0000243 MockA a;
244
245 ON_CALL(a, DoA(5))
246 .WillByDefault(Return());
247 ON_CALL(a, DoA(_))
zhanyong.wanbf550852009-06-09 06:09:53 +0000248 .With(_)
shiqiane35fdd92008-12-10 05:08:54 +0000249 .WillByDefault(Return());
250}
251
zhanyong.wanbf550852009-06-09 06:09:53 +0000252TEST(OnCallSyntaxTest, WithCanAppearAtMostOnce) {
shiqiane35fdd92008-12-10 05:08:54 +0000253 MockA a;
254
255 EXPECT_NONFATAL_FAILURE({ // NOLINT
256 ON_CALL(a, ReturnResult(_))
zhanyong.wanbf550852009-06-09 06:09:53 +0000257 .With(_)
258 .With(_)
shiqiane35fdd92008-12-10 05:08:54 +0000259 .WillByDefault(Return(Result()));
zhanyong.wanbf550852009-06-09 06:09:53 +0000260 }, ".With() cannot appear more than once in an ON_CALL()");
261}
262
shiqiane35fdd92008-12-10 05:08:54 +0000263TEST(OnCallSyntaxTest, WillByDefaultIsMandatory) {
264 MockA a;
265
zhanyong.wan04d6ed82009-09-11 07:01:08 +0000266 EXPECT_DEATH_IF_SUPPORTED({
shiqiane35fdd92008-12-10 05:08:54 +0000267 ON_CALL(a, DoA(5));
268 a.DoA(5);
269 }, "");
270}
271
shiqiane35fdd92008-12-10 05:08:54 +0000272TEST(OnCallSyntaxTest, WillByDefaultCanAppearAtMostOnce) {
273 MockA a;
274
275 EXPECT_NONFATAL_FAILURE({ // NOLINT
276 ON_CALL(a, DoA(5))
277 .WillByDefault(Return())
278 .WillByDefault(Return());
279 }, ".WillByDefault() must appear exactly once in an ON_CALL()");
280}
281
282// Tests that EXPECT_CALL evaluates its arguments exactly once as
283// promised by Google Mock.
284TEST(ExpectCallSyntaxTest, EvaluatesFirstArgumentOnce) {
285 MockA a;
286 MockA* pa = &a;
287
288 EXPECT_CALL(*pa++, DoA(_));
289 a.DoA(0);
290 EXPECT_EQ(&a + 1, pa);
291}
292
293TEST(ExpectCallSyntaxTest, EvaluatesSecondArgumentOnce) {
294 MockA a;
295 int n = 0;
296
297 EXPECT_CALL(a, DoA(n++));
298 a.DoA(0);
299 EXPECT_EQ(1, n);
300}
301
302// Tests that the syntax of EXPECT_CALL() is enforced at run time.
303
zhanyong.wanbf550852009-06-09 06:09:53 +0000304TEST(ExpectCallSyntaxTest, WithIsOptional) {
shiqiane35fdd92008-12-10 05:08:54 +0000305 MockA a;
306
307 EXPECT_CALL(a, DoA(5))
308 .Times(0);
309 EXPECT_CALL(a, DoA(6))
zhanyong.wanbf550852009-06-09 06:09:53 +0000310 .With(_)
shiqiane35fdd92008-12-10 05:08:54 +0000311 .Times(0);
312}
313
zhanyong.wanbf550852009-06-09 06:09:53 +0000314TEST(ExpectCallSyntaxTest, WithCanAppearAtMostOnce) {
shiqiane35fdd92008-12-10 05:08:54 +0000315 MockA a;
316
317 EXPECT_NONFATAL_FAILURE({ // NOLINT
318 EXPECT_CALL(a, DoA(6))
zhanyong.wanbf550852009-06-09 06:09:53 +0000319 .With(_)
320 .With(_);
321 }, ".With() cannot appear more than once in an EXPECT_CALL()");
shiqiane35fdd92008-12-10 05:08:54 +0000322
323 a.DoA(6);
324}
325
zhanyong.wanbf550852009-06-09 06:09:53 +0000326TEST(ExpectCallSyntaxTest, WithMustBeFirstClause) {
shiqiane35fdd92008-12-10 05:08:54 +0000327 MockA a;
328
329 EXPECT_NONFATAL_FAILURE({ // NOLINT
330 EXPECT_CALL(a, DoA(1))
331 .Times(1)
zhanyong.wanbf550852009-06-09 06:09:53 +0000332 .With(_);
333 }, ".With() must be the first clause in an EXPECT_CALL()");
shiqiane35fdd92008-12-10 05:08:54 +0000334
335 a.DoA(1);
336
337 EXPECT_NONFATAL_FAILURE({ // NOLINT
338 EXPECT_CALL(a, DoA(2))
339 .WillOnce(Return())
zhanyong.wanbf550852009-06-09 06:09:53 +0000340 .With(_);
341 }, ".With() must be the first clause in an EXPECT_CALL()");
shiqiane35fdd92008-12-10 05:08:54 +0000342
343 a.DoA(2);
344}
345
346TEST(ExpectCallSyntaxTest, TimesCanBeInferred) {
347 MockA a;
348
349 EXPECT_CALL(a, DoA(1))
350 .WillOnce(Return());
351
352 EXPECT_CALL(a, DoA(2))
353 .WillOnce(Return())
354 .WillRepeatedly(Return());
355
356 a.DoA(1);
357 a.DoA(2);
358 a.DoA(2);
359}
360
361TEST(ExpectCallSyntaxTest, TimesCanAppearAtMostOnce) {
362 MockA a;
363
364 EXPECT_NONFATAL_FAILURE({ // NOLINT
365 EXPECT_CALL(a, DoA(1))
366 .Times(1)
367 .Times(2);
368 }, ".Times() cannot appear more than once in an EXPECT_CALL()");
369
370 a.DoA(1);
371 a.DoA(1);
372}
373
374TEST(ExpectCallSyntaxTest, TimesMustBeBeforeInSequence) {
375 MockA a;
376 Sequence s;
377
378 EXPECT_NONFATAL_FAILURE({ // NOLINT
379 EXPECT_CALL(a, DoA(1))
380 .InSequence(s)
381 .Times(1);
382 }, ".Times() cannot appear after ");
383
384 a.DoA(1);
385}
386
387TEST(ExpectCallSyntaxTest, InSequenceIsOptional) {
388 MockA a;
389 Sequence s;
390
391 EXPECT_CALL(a, DoA(1));
392 EXPECT_CALL(a, DoA(2))
393 .InSequence(s);
394
395 a.DoA(1);
396 a.DoA(2);
397}
398
399TEST(ExpectCallSyntaxTest, InSequenceCanAppearMultipleTimes) {
400 MockA a;
401 Sequence s1, s2;
402
403 EXPECT_CALL(a, DoA(1))
404 .InSequence(s1, s2)
405 .InSequence(s1);
406
407 a.DoA(1);
408}
409
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000410TEST(ExpectCallSyntaxTest, InSequenceMustBeBeforeAfter) {
411 MockA a;
412 Sequence s;
413
414 Expectation e = EXPECT_CALL(a, DoA(1))
415 .Times(AnyNumber());
416 EXPECT_NONFATAL_FAILURE({ // NOLINT
417 EXPECT_CALL(a, DoA(2))
418 .After(e)
419 .InSequence(s);
420 }, ".InSequence() cannot appear after ");
421
422 a.DoA(2);
423}
424
425TEST(ExpectCallSyntaxTest, InSequenceMustBeBeforeWillOnce) {
shiqiane35fdd92008-12-10 05:08:54 +0000426 MockA a;
427 Sequence s;
428
429 EXPECT_NONFATAL_FAILURE({ // NOLINT
430 EXPECT_CALL(a, DoA(1))
431 .WillOnce(Return())
432 .InSequence(s);
433 }, ".InSequence() cannot appear after ");
434
435 a.DoA(1);
436}
437
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000438TEST(ExpectCallSyntaxTest, AfterMustBeBeforeWillOnce) {
439 MockA a;
440
441 Expectation e = EXPECT_CALL(a, DoA(1));
442 EXPECT_NONFATAL_FAILURE({
443 EXPECT_CALL(a, DoA(2))
444 .WillOnce(Return())
445 .After(e);
446 }, ".After() cannot appear after ");
447
448 a.DoA(1);
449 a.DoA(2);
450}
451
shiqiane35fdd92008-12-10 05:08:54 +0000452TEST(ExpectCallSyntaxTest, WillIsOptional) {
453 MockA a;
454
455 EXPECT_CALL(a, DoA(1));
456 EXPECT_CALL(a, DoA(2))
457 .WillOnce(Return());
458
459 a.DoA(1);
460 a.DoA(2);
461}
462
463TEST(ExpectCallSyntaxTest, WillCanAppearMultipleTimes) {
464 MockA a;
465
466 EXPECT_CALL(a, DoA(1))
467 .Times(AnyNumber())
468 .WillOnce(Return())
469 .WillOnce(Return())
470 .WillOnce(Return());
471}
472
473TEST(ExpectCallSyntaxTest, WillMustBeBeforeWillRepeatedly) {
474 MockA a;
475
476 EXPECT_NONFATAL_FAILURE({ // NOLINT
477 EXPECT_CALL(a, DoA(1))
478 .WillRepeatedly(Return())
479 .WillOnce(Return());
480 }, ".WillOnce() cannot appear after ");
481
482 a.DoA(1);
483}
484
485TEST(ExpectCallSyntaxTest, WillRepeatedlyIsOptional) {
486 MockA a;
487
488 EXPECT_CALL(a, DoA(1))
489 .WillOnce(Return());
490 EXPECT_CALL(a, DoA(2))
491 .WillOnce(Return())
492 .WillRepeatedly(Return());
493
494 a.DoA(1);
495 a.DoA(2);
496 a.DoA(2);
497}
498
499TEST(ExpectCallSyntaxTest, WillRepeatedlyCannotAppearMultipleTimes) {
500 MockA a;
501
502 EXPECT_NONFATAL_FAILURE({ // NOLINT
503 EXPECT_CALL(a, DoA(1))
504 .WillRepeatedly(Return())
505 .WillRepeatedly(Return());
506 }, ".WillRepeatedly() cannot appear more than once in an "
507 "EXPECT_CALL()");
508}
509
510TEST(ExpectCallSyntaxTest, WillRepeatedlyMustBeBeforeRetiresOnSaturation) {
511 MockA a;
512
513 EXPECT_NONFATAL_FAILURE({ // NOLINT
514 EXPECT_CALL(a, DoA(1))
515 .RetiresOnSaturation()
516 .WillRepeatedly(Return());
517 }, ".WillRepeatedly() cannot appear after ");
518}
519
520TEST(ExpectCallSyntaxTest, RetiresOnSaturationIsOptional) {
521 MockA a;
522
523 EXPECT_CALL(a, DoA(1));
524 EXPECT_CALL(a, DoA(1))
525 .RetiresOnSaturation();
526
527 a.DoA(1);
528 a.DoA(1);
529}
530
531TEST(ExpectCallSyntaxTest, RetiresOnSaturationCannotAppearMultipleTimes) {
532 MockA a;
533
534 EXPECT_NONFATAL_FAILURE({ // NOLINT
535 EXPECT_CALL(a, DoA(1))
536 .RetiresOnSaturation()
537 .RetiresOnSaturation();
538 }, ".RetiresOnSaturation() cannot appear more than once");
539
540 a.DoA(1);
541}
542
543TEST(ExpectCallSyntaxTest, DefaultCardinalityIsOnce) {
544 {
545 MockA a;
546 EXPECT_CALL(a, DoA(1));
547 a.DoA(1);
548 }
549 EXPECT_NONFATAL_FAILURE({ // NOLINT
550 MockA a;
551 EXPECT_CALL(a, DoA(1));
552 }, "to be called once");
553 EXPECT_NONFATAL_FAILURE({ // NOLINT
554 MockA a;
555 EXPECT_CALL(a, DoA(1));
556 a.DoA(1);
557 a.DoA(1);
558 }, "to be called once");
559}
560
zhanyong.wan2516f602010-08-31 18:28:02 +0000561#if GTEST_HAS_STREAM_REDIRECTION
shiqiane35fdd92008-12-10 05:08:54 +0000562
563// Tests that Google Mock doesn't print a warning when the number of
564// WillOnce() is adequate.
565TEST(ExpectCallSyntaxTest, DoesNotWarnOnAdequateActionCount) {
zhanyong.wan470df422010-02-02 22:34:58 +0000566 CaptureStdout();
shiqiane35fdd92008-12-10 05:08:54 +0000567 {
568 MockB b;
569
570 // It's always fine to omit WillOnce() entirely.
571 EXPECT_CALL(b, DoB())
572 .Times(0);
573 EXPECT_CALL(b, DoB(1))
574 .Times(AtMost(1));
575 EXPECT_CALL(b, DoB(2))
576 .Times(1)
577 .WillRepeatedly(Return(1));
578
579 // It's fine for the number of WillOnce()s to equal the upper bound.
580 EXPECT_CALL(b, DoB(3))
581 .Times(Between(1, 2))
582 .WillOnce(Return(1))
583 .WillOnce(Return(2));
584
585 // It's fine for the number of WillOnce()s to be smaller than the
586 // upper bound when there is a WillRepeatedly().
587 EXPECT_CALL(b, DoB(4))
588 .Times(AtMost(3))
589 .WillOnce(Return(1))
590 .WillRepeatedly(Return(2));
591
592 // Satisfies the above expectations.
593 b.DoB(2);
594 b.DoB(3);
595 }
zhanyong.wan470df422010-02-02 22:34:58 +0000596 EXPECT_STREQ("", GetCapturedStdout().c_str());
shiqiane35fdd92008-12-10 05:08:54 +0000597}
598
599// Tests that Google Mock warns on having too many actions in an
600// expectation compared to its cardinality.
601TEST(ExpectCallSyntaxTest, WarnsOnTooManyActions) {
zhanyong.wan470df422010-02-02 22:34:58 +0000602 CaptureStdout();
shiqiane35fdd92008-12-10 05:08:54 +0000603 {
604 MockB b;
605
606 // Warns when the number of WillOnce()s is larger than the upper bound.
607 EXPECT_CALL(b, DoB())
608 .Times(0)
609 .WillOnce(Return(1)); // #1
610 EXPECT_CALL(b, DoB())
611 .Times(AtMost(1))
612 .WillOnce(Return(1))
613 .WillOnce(Return(2)); // #2
614 EXPECT_CALL(b, DoB(1))
615 .Times(1)
616 .WillOnce(Return(1))
617 .WillOnce(Return(2))
618 .RetiresOnSaturation(); // #3
619
620 // Warns when the number of WillOnce()s equals the upper bound and
621 // there is a WillRepeatedly().
622 EXPECT_CALL(b, DoB())
623 .Times(0)
624 .WillRepeatedly(Return(1)); // #4
625 EXPECT_CALL(b, DoB(2))
626 .Times(1)
627 .WillOnce(Return(1))
628 .WillRepeatedly(Return(2)); // #5
629
630 // Satisfies the above expectations.
631 b.DoB(1);
632 b.DoB(2);
633 }
jgm38513a82012-11-15 15:50:36 +0000634 const std::string output = GetCapturedStdout();
vladlosev6c54a5e2009-10-21 06:15:34 +0000635 EXPECT_PRED_FORMAT2(
636 IsSubstring,
637 "Too many actions specified in EXPECT_CALL(b, DoB())...\n"
638 "Expected to be never called, but has 1 WillOnce().",
639 output); // #1
640 EXPECT_PRED_FORMAT2(
641 IsSubstring,
642 "Too many actions specified in EXPECT_CALL(b, DoB())...\n"
643 "Expected to be called at most once, "
644 "but has 2 WillOnce()s.",
645 output); // #2
646 EXPECT_PRED_FORMAT2(
647 IsSubstring,
648 "Too many actions specified in EXPECT_CALL(b, DoB(1))...\n"
649 "Expected to be called once, but has 2 WillOnce()s.",
650 output); // #3
651 EXPECT_PRED_FORMAT2(
652 IsSubstring,
653 "Too many actions specified in EXPECT_CALL(b, DoB())...\n"
654 "Expected to be never called, but has 0 WillOnce()s "
655 "and a WillRepeatedly().",
656 output); // #4
657 EXPECT_PRED_FORMAT2(
658 IsSubstring,
659 "Too many actions specified in EXPECT_CALL(b, DoB(2))...\n"
660 "Expected to be called once, but has 1 WillOnce() "
661 "and a WillRepeatedly().",
662 output); // #5
shiqiane35fdd92008-12-10 05:08:54 +0000663}
664
665// Tests that Google Mock warns on having too few actions in an
666// expectation compared to its cardinality.
667TEST(ExpectCallSyntaxTest, WarnsOnTooFewActions) {
668 MockB b;
669
670 EXPECT_CALL(b, DoB())
671 .Times(Between(2, 3))
672 .WillOnce(Return(1));
673
zhanyong.wan470df422010-02-02 22:34:58 +0000674 CaptureStdout();
shiqiane35fdd92008-12-10 05:08:54 +0000675 b.DoB();
jgm38513a82012-11-15 15:50:36 +0000676 const std::string output = GetCapturedStdout();
vladlosev6c54a5e2009-10-21 06:15:34 +0000677 EXPECT_PRED_FORMAT2(
678 IsSubstring,
679 "Too few actions specified in EXPECT_CALL(b, DoB())...\n"
680 "Expected to be called between 2 and 3 times, "
681 "but has only 1 WillOnce().",
682 output);
shiqiane35fdd92008-12-10 05:08:54 +0000683 b.DoB();
684}
685
zhanyong.wan2516f602010-08-31 18:28:02 +0000686#endif // GTEST_HAS_STREAM_REDIRECTION
shiqiane35fdd92008-12-10 05:08:54 +0000687
688// Tests the semantics of ON_CALL().
689
690// Tests that the built-in default action is taken when no ON_CALL()
691// is specified.
692TEST(OnCallTest, TakesBuiltInDefaultActionWhenNoOnCall) {
693 MockB b;
694 EXPECT_CALL(b, DoB());
695
696 EXPECT_EQ(0, b.DoB());
697}
698
699// Tests that the built-in default action is taken when no ON_CALL()
700// matches the invocation.
701TEST(OnCallTest, TakesBuiltInDefaultActionWhenNoOnCallMatches) {
702 MockB b;
703 ON_CALL(b, DoB(1))
704 .WillByDefault(Return(1));
705 EXPECT_CALL(b, DoB(_));
706
707 EXPECT_EQ(0, b.DoB(2));
708}
709
710// Tests that the last matching ON_CALL() action is taken.
711TEST(OnCallTest, PicksLastMatchingOnCall) {
712 MockB b;
713 ON_CALL(b, DoB(_))
714 .WillByDefault(Return(3));
715 ON_CALL(b, DoB(2))
716 .WillByDefault(Return(2));
717 ON_CALL(b, DoB(1))
718 .WillByDefault(Return(1));
719 EXPECT_CALL(b, DoB(_));
720
721 EXPECT_EQ(2, b.DoB(2));
722}
723
724// Tests the semantics of EXPECT_CALL().
725
726// Tests that any call is allowed when no EXPECT_CALL() is specified.
727TEST(ExpectCallTest, AllowsAnyCallWhenNoSpec) {
728 MockB b;
729 EXPECT_CALL(b, DoB());
730 // There is no expectation on DoB(int).
731
732 b.DoB();
733
734 // DoB(int) can be called any number of times.
735 b.DoB(1);
736 b.DoB(2);
737}
738
739// Tests that the last matching EXPECT_CALL() fires.
740TEST(ExpectCallTest, PicksLastMatchingExpectCall) {
741 MockB b;
742 EXPECT_CALL(b, DoB(_))
743 .WillRepeatedly(Return(2));
744 EXPECT_CALL(b, DoB(1))
745 .WillRepeatedly(Return(1));
746
747 EXPECT_EQ(1, b.DoB(1));
748}
749
750// Tests lower-bound violation.
751TEST(ExpectCallTest, CatchesTooFewCalls) {
752 EXPECT_NONFATAL_FAILURE({ // NOLINT
753 MockB b;
754 EXPECT_CALL(b, DoB(5))
755 .Times(AtLeast(2));
756
757 b.DoB(5);
vladlosev6c54a5e2009-10-21 06:15:34 +0000758 }, "Actual function call count doesn't match EXPECT_CALL(b, DoB(5))...\n"
shiqiane35fdd92008-12-10 05:08:54 +0000759 " Expected: to be called at least twice\n"
760 " Actual: called once - unsatisfied and active");
761}
762
763// Tests that the cardinality can be inferred when no Times(...) is
764// specified.
765TEST(ExpectCallTest, InfersCardinalityWhenThereIsNoWillRepeatedly) {
766 {
767 MockB b;
768 EXPECT_CALL(b, DoB())
769 .WillOnce(Return(1))
770 .WillOnce(Return(2));
771
772 EXPECT_EQ(1, b.DoB());
773 EXPECT_EQ(2, b.DoB());
774 }
775
776 EXPECT_NONFATAL_FAILURE({ // NOLINT
777 MockB b;
778 EXPECT_CALL(b, DoB())
779 .WillOnce(Return(1))
780 .WillOnce(Return(2));
781
782 EXPECT_EQ(1, b.DoB());
783 }, "to be called twice");
784
785 { // NOLINT
786 MockB b;
787 EXPECT_CALL(b, DoB())
788 .WillOnce(Return(1))
789 .WillOnce(Return(2));
790
791 EXPECT_EQ(1, b.DoB());
792 EXPECT_EQ(2, b.DoB());
793 EXPECT_NONFATAL_FAILURE(b.DoB(), "to be called twice");
794 }
795}
796
797TEST(ExpectCallTest, InfersCardinality1WhenThereIsWillRepeatedly) {
798 {
799 MockB b;
800 EXPECT_CALL(b, DoB())
801 .WillOnce(Return(1))
802 .WillRepeatedly(Return(2));
803
804 EXPECT_EQ(1, b.DoB());
805 }
806
807 { // NOLINT
808 MockB b;
809 EXPECT_CALL(b, DoB())
810 .WillOnce(Return(1))
811 .WillRepeatedly(Return(2));
812
813 EXPECT_EQ(1, b.DoB());
814 EXPECT_EQ(2, b.DoB());
815 EXPECT_EQ(2, b.DoB());
816 }
817
818 EXPECT_NONFATAL_FAILURE({ // NOLINT
819 MockB b;
820 EXPECT_CALL(b, DoB())
821 .WillOnce(Return(1))
822 .WillRepeatedly(Return(2));
823 }, "to be called at least once");
824}
825
826// Tests that the n-th action is taken for the n-th matching
827// invocation.
828TEST(ExpectCallTest, NthMatchTakesNthAction) {
829 MockB b;
830 EXPECT_CALL(b, DoB())
831 .WillOnce(Return(1))
832 .WillOnce(Return(2))
833 .WillOnce(Return(3));
834
835 EXPECT_EQ(1, b.DoB());
836 EXPECT_EQ(2, b.DoB());
837 EXPECT_EQ(3, b.DoB());
838}
839
vladloseve5121b52011-02-11 23:50:38 +0000840// Tests that the WillRepeatedly() action is taken when the WillOnce(...)
841// list is exhausted.
842TEST(ExpectCallTest, TakesRepeatedActionWhenWillListIsExhausted) {
843 MockB b;
844 EXPECT_CALL(b, DoB())
845 .WillOnce(Return(1))
846 .WillRepeatedly(Return(2));
847
848 EXPECT_EQ(1, b.DoB());
849 EXPECT_EQ(2, b.DoB());
850 EXPECT_EQ(2, b.DoB());
851}
852
zhanyong.wan2516f602010-08-31 18:28:02 +0000853#if GTEST_HAS_STREAM_REDIRECTION
shiqiane35fdd92008-12-10 05:08:54 +0000854
855// Tests that the default action is taken when the WillOnce(...) list is
856// exhausted and there is no WillRepeatedly().
857TEST(ExpectCallTest, TakesDefaultActionWhenWillListIsExhausted) {
858 MockB b;
859 EXPECT_CALL(b, DoB(_))
860 .Times(1);
861 EXPECT_CALL(b, DoB())
862 .Times(AnyNumber())
863 .WillOnce(Return(1))
864 .WillOnce(Return(2));
865
zhanyong.wan470df422010-02-02 22:34:58 +0000866 CaptureStdout();
shiqiane35fdd92008-12-10 05:08:54 +0000867 EXPECT_EQ(0, b.DoB(1)); // Shouldn't generate a warning as the
868 // expectation has no action clause at all.
869 EXPECT_EQ(1, b.DoB());
870 EXPECT_EQ(2, b.DoB());
jgm38513a82012-11-15 15:50:36 +0000871 const std::string output1 = GetCapturedStdout();
zhanyong.wan470df422010-02-02 22:34:58 +0000872 EXPECT_STREQ("", output1.c_str());
shiqiane35fdd92008-12-10 05:08:54 +0000873
zhanyong.wan470df422010-02-02 22:34:58 +0000874 CaptureStdout();
shiqiane35fdd92008-12-10 05:08:54 +0000875 EXPECT_EQ(0, b.DoB());
876 EXPECT_EQ(0, b.DoB());
jgm38513a82012-11-15 15:50:36 +0000877 const std::string output2 = GetCapturedStdout();
zhanyong.wan470df422010-02-02 22:34:58 +0000878 EXPECT_THAT(output2.c_str(),
879 HasSubstr("Actions ran out in EXPECT_CALL(b, DoB())...\n"
880 "Called 3 times, but only 2 WillOnce()s are specified"
881 " - returning default value."));
882 EXPECT_THAT(output2.c_str(),
883 HasSubstr("Actions ran out in EXPECT_CALL(b, DoB())...\n"
884 "Called 4 times, but only 2 WillOnce()s are specified"
885 " - returning default value."));
shiqiane35fdd92008-12-10 05:08:54 +0000886}
887
vladloseve5121b52011-02-11 23:50:38 +0000888TEST(FunctionMockerTest, ReportsExpectCallLocationForExhausedActions) {
shiqiane35fdd92008-12-10 05:08:54 +0000889 MockB b;
vladloseve5121b52011-02-11 23:50:38 +0000890 std::string expect_call_location = FormatFileLocation(__FILE__, __LINE__ + 1);
891 EXPECT_CALL(b, DoB()).Times(AnyNumber()).WillOnce(Return(1));
shiqiane35fdd92008-12-10 05:08:54 +0000892
893 EXPECT_EQ(1, b.DoB());
vladloseve5121b52011-02-11 23:50:38 +0000894
895 CaptureStdout();
896 EXPECT_EQ(0, b.DoB());
jgm38513a82012-11-15 15:50:36 +0000897 const std::string output = GetCapturedStdout();
vladloseve5121b52011-02-11 23:50:38 +0000898 // The warning message should contain the call location.
899 EXPECT_PRED_FORMAT2(IsSubstring, expect_call_location, output);
shiqiane35fdd92008-12-10 05:08:54 +0000900}
901
vladloseve5121b52011-02-11 23:50:38 +0000902TEST(FunctionMockerTest, ReportsDefaultActionLocationOfUninterestingCalls) {
903 std::string on_call_location;
904 CaptureStdout();
905 {
906 MockB b;
907 on_call_location = FormatFileLocation(__FILE__, __LINE__ + 1);
908 ON_CALL(b, DoB(_)).WillByDefault(Return(0));
909 b.DoB(0);
910 }
911 EXPECT_PRED_FORMAT2(IsSubstring, on_call_location, GetCapturedStdout());
912}
913
914#endif // GTEST_HAS_STREAM_REDIRECTION
915
shiqiane35fdd92008-12-10 05:08:54 +0000916// Tests that an uninteresting call performs the default action.
917TEST(UninterestingCallTest, DoesDefaultAction) {
918 // When there is an ON_CALL() statement, the action specified by it
919 // should be taken.
920 MockA a;
921 ON_CALL(a, Binary(_, _))
922 .WillByDefault(Return(true));
923 EXPECT_TRUE(a.Binary(1, 2));
924
925 // When there is no ON_CALL(), the default value for the return type
926 // should be returned.
927 MockB b;
928 EXPECT_EQ(0, b.DoB());
929}
930
931// Tests that an unexpected call performs the default action.
932TEST(UnexpectedCallTest, DoesDefaultAction) {
933 // When there is an ON_CALL() statement, the action specified by it
934 // should be taken.
935 MockA a;
936 ON_CALL(a, Binary(_, _))
937 .WillByDefault(Return(true));
938 EXPECT_CALL(a, Binary(0, 0));
939 a.Binary(0, 0);
940 bool result = false;
941 EXPECT_NONFATAL_FAILURE(result = a.Binary(1, 2),
942 "Unexpected mock function call");
943 EXPECT_TRUE(result);
944
945 // When there is no ON_CALL(), the default value for the return type
946 // should be returned.
947 MockB b;
948 EXPECT_CALL(b, DoB(0))
949 .Times(0);
950 int n = -1;
951 EXPECT_NONFATAL_FAILURE(n = b.DoB(1),
952 "Unexpected mock function call");
953 EXPECT_EQ(0, n);
954}
955
956// Tests that when an unexpected void function generates the right
957// failure message.
958TEST(UnexpectedCallTest, GeneratesFailureForVoidFunction) {
959 // First, tests the message when there is only one EXPECT_CALL().
960 MockA a1;
961 EXPECT_CALL(a1, DoA(1));
962 a1.DoA(1);
963 // Ideally we should match the failure message against a regex, but
964 // EXPECT_NONFATAL_FAILURE doesn't support that, so we test for
965 // multiple sub-strings instead.
966 EXPECT_NONFATAL_FAILURE(
967 a1.DoA(9),
968 "Unexpected mock function call - returning directly.\n"
969 " Function call: DoA(9)\n"
970 "Google Mock tried the following 1 expectation, but it didn't match:");
971 EXPECT_NONFATAL_FAILURE(
972 a1.DoA(9),
973 " Expected arg #0: is equal to 1\n"
974 " Actual: 9\n"
975 " Expected: to be called once\n"
976 " Actual: called once - saturated and active");
977
978 // Next, tests the message when there are more than one EXPECT_CALL().
979 MockA a2;
980 EXPECT_CALL(a2, DoA(1));
981 EXPECT_CALL(a2, DoA(3));
982 a2.DoA(1);
983 EXPECT_NONFATAL_FAILURE(
984 a2.DoA(2),
985 "Unexpected mock function call - returning directly.\n"
986 " Function call: DoA(2)\n"
987 "Google Mock tried the following 2 expectations, but none matched:");
988 EXPECT_NONFATAL_FAILURE(
989 a2.DoA(2),
vladlosev6c54a5e2009-10-21 06:15:34 +0000990 "tried expectation #0: EXPECT_CALL(a2, DoA(1))...\n"
shiqiane35fdd92008-12-10 05:08:54 +0000991 " Expected arg #0: is equal to 1\n"
992 " Actual: 2\n"
993 " Expected: to be called once\n"
994 " Actual: called once - saturated and active");
995 EXPECT_NONFATAL_FAILURE(
996 a2.DoA(2),
vladlosev6c54a5e2009-10-21 06:15:34 +0000997 "tried expectation #1: EXPECT_CALL(a2, DoA(3))...\n"
shiqiane35fdd92008-12-10 05:08:54 +0000998 " Expected arg #0: is equal to 3\n"
999 " Actual: 2\n"
1000 " Expected: to be called once\n"
1001 " Actual: never called - unsatisfied and active");
1002 a2.DoA(3);
1003}
1004
1005// Tests that an unexpected non-void function generates the right
1006// failure message.
1007TEST(UnexpectedCallTest, GeneartesFailureForNonVoidFunction) {
1008 MockB b1;
1009 EXPECT_CALL(b1, DoB(1));
1010 b1.DoB(1);
1011 EXPECT_NONFATAL_FAILURE(
1012 b1.DoB(2),
1013 "Unexpected mock function call - returning default value.\n"
1014 " Function call: DoB(2)\n"
1015 " Returns: 0\n"
1016 "Google Mock tried the following 1 expectation, but it didn't match:");
1017 EXPECT_NONFATAL_FAILURE(
1018 b1.DoB(2),
1019 " Expected arg #0: is equal to 1\n"
1020 " Actual: 2\n"
1021 " Expected: to be called once\n"
1022 " Actual: called once - saturated and active");
1023}
1024
1025// Tests that Google Mock explains that an retired expectation doesn't
1026// match the call.
1027TEST(UnexpectedCallTest, RetiredExpectation) {
1028 MockB b;
1029 EXPECT_CALL(b, DoB(1))
1030 .RetiresOnSaturation();
1031
1032 b.DoB(1);
1033 EXPECT_NONFATAL_FAILURE(
1034 b.DoB(1),
1035 " Expected: the expectation is active\n"
1036 " Actual: it is retired");
1037}
1038
1039// Tests that Google Mock explains that an expectation that doesn't
1040// match the arguments doesn't match the call.
1041TEST(UnexpectedCallTest, UnmatchedArguments) {
1042 MockB b;
1043 EXPECT_CALL(b, DoB(1));
1044
1045 EXPECT_NONFATAL_FAILURE(
1046 b.DoB(2),
1047 " Expected arg #0: is equal to 1\n"
1048 " Actual: 2\n");
1049 b.DoB(1);
1050}
1051
shiqiane35fdd92008-12-10 05:08:54 +00001052// Tests that Google Mock explains that an expectation with
1053// unsatisfied pre-requisites doesn't match the call.
1054TEST(UnexpectedCallTest, UnsatisifiedPrerequisites) {
1055 Sequence s1, s2;
1056 MockB b;
1057 EXPECT_CALL(b, DoB(1))
1058 .InSequence(s1);
1059 EXPECT_CALL(b, DoB(2))
1060 .Times(AnyNumber())
1061 .InSequence(s1);
1062 EXPECT_CALL(b, DoB(3))
1063 .InSequence(s2);
1064 EXPECT_CALL(b, DoB(4))
1065 .InSequence(s1, s2);
1066
1067 ::testing::TestPartResultArray failures;
1068 {
1069 ::testing::ScopedFakeTestPartResultReporter reporter(&failures);
1070 b.DoB(4);
1071 // Now 'failures' contains the Google Test failures generated by
1072 // the above statement.
1073 }
1074
1075 // There should be one non-fatal failure.
1076 ASSERT_EQ(1, failures.size());
1077 const ::testing::TestPartResult& r = failures.GetTestPartResult(0);
zhanyong.wanbbd6e102009-09-18 18:17:19 +00001078 EXPECT_EQ(::testing::TestPartResult::kNonFatalFailure, r.type());
shiqiane35fdd92008-12-10 05:08:54 +00001079
1080 // Verifies that the failure message contains the two unsatisfied
1081 // pre-requisites but not the satisfied one.
zhanyong.wand14aaed2010-01-14 05:36:32 +00001082#if GTEST_USES_PCRE
1083 EXPECT_THAT(r.message(), ContainsRegex(
shiqiane35fdd92008-12-10 05:08:54 +00001084 // PCRE has trouble using (.|\n) to match any character, but
1085 // supports the (?s) prefix for using . to match any character.
1086 "(?s)the following immediate pre-requisites are not satisfied:\n"
1087 ".*: pre-requisite #0\n"
zhanyong.wand14aaed2010-01-14 05:36:32 +00001088 ".*: pre-requisite #1"));
1089#elif GTEST_USES_POSIX_RE
1090 EXPECT_THAT(r.message(), ContainsRegex(
shiqiane35fdd92008-12-10 05:08:54 +00001091 // POSIX RE doesn't understand the (?s) prefix, but has no trouble
1092 // with (.|\n).
1093 "the following immediate pre-requisites are not satisfied:\n"
1094 "(.|\n)*: pre-requisite #0\n"
zhanyong.wand14aaed2010-01-14 05:36:32 +00001095 "(.|\n)*: pre-requisite #1"));
1096#else
1097 // We can only use Google Test's own simple regex.
1098 EXPECT_THAT(r.message(), ContainsRegex(
1099 "the following immediate pre-requisites are not satisfied:"));
1100 EXPECT_THAT(r.message(), ContainsRegex(": pre-requisite #0"));
1101 EXPECT_THAT(r.message(), ContainsRegex(": pre-requisite #1"));
1102#endif // GTEST_USES_PCRE
shiqiane35fdd92008-12-10 05:08:54 +00001103
shiqiane35fdd92008-12-10 05:08:54 +00001104 b.DoB(1);
1105 b.DoB(3);
1106 b.DoB(4);
1107}
1108
zhanyong.wan5b95fa72009-01-27 22:28:45 +00001109TEST(UndefinedReturnValueTest, ReturnValueIsMandatory) {
1110 MockA a;
1111 // TODO(wan@google.com): We should really verify the output message,
1112 // but we cannot yet due to that EXPECT_DEATH only captures stderr
1113 // while Google Mock logs to stdout.
zhanyong.wan04d6ed82009-09-11 07:01:08 +00001114 EXPECT_DEATH_IF_SUPPORTED(a.ReturnResult(1), "");
zhanyong.wan5b95fa72009-01-27 22:28:45 +00001115}
1116
shiqiane35fdd92008-12-10 05:08:54 +00001117// Tests that an excessive call (one whose arguments match the
1118// matchers but is called too many times) performs the default action.
1119TEST(ExcessiveCallTest, DoesDefaultAction) {
1120 // When there is an ON_CALL() statement, the action specified by it
1121 // should be taken.
1122 MockA a;
1123 ON_CALL(a, Binary(_, _))
1124 .WillByDefault(Return(true));
1125 EXPECT_CALL(a, Binary(0, 0));
1126 a.Binary(0, 0);
1127 bool result = false;
1128 EXPECT_NONFATAL_FAILURE(result = a.Binary(0, 0),
1129 "Mock function called more times than expected");
1130 EXPECT_TRUE(result);
1131
1132 // When there is no ON_CALL(), the default value for the return type
1133 // should be returned.
1134 MockB b;
1135 EXPECT_CALL(b, DoB(0))
1136 .Times(0);
1137 int n = -1;
1138 EXPECT_NONFATAL_FAILURE(n = b.DoB(0),
1139 "Mock function called more times than expected");
1140 EXPECT_EQ(0, n);
1141}
1142
1143// Tests that when a void function is called too many times,
1144// the failure message contains the argument values.
1145TEST(ExcessiveCallTest, GeneratesFailureForVoidFunction) {
1146 MockA a;
1147 EXPECT_CALL(a, DoA(_))
1148 .Times(0);
1149 EXPECT_NONFATAL_FAILURE(
1150 a.DoA(9),
1151 "Mock function called more times than expected - returning directly.\n"
1152 " Function call: DoA(9)\n"
1153 " Expected: to be never called\n"
1154 " Actual: called once - over-saturated and active");
1155}
1156
1157// Tests that when a non-void function is called too many times, the
1158// failure message contains the argument values and the return value.
1159TEST(ExcessiveCallTest, GeneratesFailureForNonVoidFunction) {
1160 MockB b;
1161 EXPECT_CALL(b, DoB(_));
1162 b.DoB(1);
1163 EXPECT_NONFATAL_FAILURE(
1164 b.DoB(2),
1165 "Mock function called more times than expected - "
1166 "returning default value.\n"
1167 " Function call: DoB(2)\n"
1168 " Returns: 0\n"
1169 " Expected: to be called once\n"
1170 " Actual: called twice - over-saturated and active");
1171}
1172
1173// Tests using sequences.
1174
1175TEST(InSequenceTest, AllExpectationInScopeAreInSequence) {
1176 MockA a;
1177 {
1178 InSequence dummy;
1179
1180 EXPECT_CALL(a, DoA(1));
1181 EXPECT_CALL(a, DoA(2));
1182 }
1183
1184 EXPECT_NONFATAL_FAILURE({ // NOLINT
1185 a.DoA(2);
1186 }, "Unexpected mock function call");
1187
1188 a.DoA(1);
1189 a.DoA(2);
1190}
1191
1192TEST(InSequenceTest, NestedInSequence) {
1193 MockA a;
1194 {
1195 InSequence dummy;
1196
1197 EXPECT_CALL(a, DoA(1));
1198 {
1199 InSequence dummy2;
1200
1201 EXPECT_CALL(a, DoA(2));
1202 EXPECT_CALL(a, DoA(3));
1203 }
1204 }
1205
1206 EXPECT_NONFATAL_FAILURE({ // NOLINT
1207 a.DoA(1);
1208 a.DoA(3);
1209 }, "Unexpected mock function call");
1210
1211 a.DoA(2);
1212 a.DoA(3);
1213}
1214
1215TEST(InSequenceTest, ExpectationsOutOfScopeAreNotAffected) {
1216 MockA a;
1217 {
1218 InSequence dummy;
1219
1220 EXPECT_CALL(a, DoA(1));
1221 EXPECT_CALL(a, DoA(2));
1222 }
1223 EXPECT_CALL(a, DoA(3));
1224
1225 EXPECT_NONFATAL_FAILURE({ // NOLINT
1226 a.DoA(2);
1227 }, "Unexpected mock function call");
1228
1229 a.DoA(3);
1230 a.DoA(1);
1231 a.DoA(2);
1232}
1233
1234// Tests that any order is allowed when no sequence is used.
1235TEST(SequenceTest, AnyOrderIsOkByDefault) {
1236 {
1237 MockA a;
1238 MockB b;
1239
1240 EXPECT_CALL(a, DoA(1));
1241 EXPECT_CALL(b, DoB())
1242 .Times(AnyNumber());
1243
1244 a.DoA(1);
1245 b.DoB();
1246 }
1247
1248 { // NOLINT
1249 MockA a;
1250 MockB b;
1251
1252 EXPECT_CALL(a, DoA(1));
1253 EXPECT_CALL(b, DoB())
1254 .Times(AnyNumber());
1255
1256 b.DoB();
1257 a.DoA(1);
1258 }
1259}
1260
shiqiane35fdd92008-12-10 05:08:54 +00001261// Tests that the calls must be in strict order when a complete order
1262// is specified.
1263TEST(SequenceTest, CallsMustBeInStrictOrderWhenSaidSo) {
1264 MockA a;
1265 Sequence s;
1266
1267 EXPECT_CALL(a, ReturnResult(1))
1268 .InSequence(s)
1269 .WillOnce(Return(Result()));
1270
1271 EXPECT_CALL(a, ReturnResult(2))
1272 .InSequence(s)
1273 .WillOnce(Return(Result()));
1274
1275 EXPECT_CALL(a, ReturnResult(3))
1276 .InSequence(s)
1277 .WillOnce(Return(Result()));
1278
zhanyong.wan04d6ed82009-09-11 07:01:08 +00001279 EXPECT_DEATH_IF_SUPPORTED({
shiqiane35fdd92008-12-10 05:08:54 +00001280 a.ReturnResult(1);
1281 a.ReturnResult(3);
1282 a.ReturnResult(2);
1283 }, "");
1284
zhanyong.wan04d6ed82009-09-11 07:01:08 +00001285 EXPECT_DEATH_IF_SUPPORTED({
shiqiane35fdd92008-12-10 05:08:54 +00001286 a.ReturnResult(2);
1287 a.ReturnResult(1);
1288 a.ReturnResult(3);
1289 }, "");
1290
1291 a.ReturnResult(1);
1292 a.ReturnResult(2);
1293 a.ReturnResult(3);
1294}
1295
1296// Tests specifying a DAG using multiple sequences.
1297TEST(SequenceTest, CallsMustConformToSpecifiedDag) {
1298 MockA a;
1299 MockB b;
1300 Sequence x, y;
1301
1302 EXPECT_CALL(a, ReturnResult(1))
1303 .InSequence(x)
1304 .WillOnce(Return(Result()));
1305
1306 EXPECT_CALL(b, DoB())
1307 .Times(2)
1308 .InSequence(y);
1309
1310 EXPECT_CALL(a, ReturnResult(2))
1311 .InSequence(x, y)
1312 .WillRepeatedly(Return(Result()));
1313
1314 EXPECT_CALL(a, ReturnResult(3))
1315 .InSequence(x)
1316 .WillOnce(Return(Result()));
1317
zhanyong.wan04d6ed82009-09-11 07:01:08 +00001318 EXPECT_DEATH_IF_SUPPORTED({
shiqiane35fdd92008-12-10 05:08:54 +00001319 a.ReturnResult(1);
1320 b.DoB();
1321 a.ReturnResult(2);
1322 }, "");
1323
zhanyong.wan04d6ed82009-09-11 07:01:08 +00001324 EXPECT_DEATH_IF_SUPPORTED({
shiqiane35fdd92008-12-10 05:08:54 +00001325 a.ReturnResult(2);
1326 }, "");
1327
zhanyong.wan04d6ed82009-09-11 07:01:08 +00001328 EXPECT_DEATH_IF_SUPPORTED({
shiqiane35fdd92008-12-10 05:08:54 +00001329 a.ReturnResult(3);
1330 }, "");
1331
zhanyong.wan04d6ed82009-09-11 07:01:08 +00001332 EXPECT_DEATH_IF_SUPPORTED({
shiqiane35fdd92008-12-10 05:08:54 +00001333 a.ReturnResult(1);
1334 b.DoB();
1335 b.DoB();
1336 a.ReturnResult(3);
1337 a.ReturnResult(2);
1338 }, "");
1339
1340 b.DoB();
1341 a.ReturnResult(1);
1342 b.DoB();
1343 a.ReturnResult(3);
1344}
1345
shiqiane35fdd92008-12-10 05:08:54 +00001346TEST(SequenceTest, Retirement) {
1347 MockA a;
1348 Sequence s;
1349
1350 EXPECT_CALL(a, DoA(1))
1351 .InSequence(s);
1352 EXPECT_CALL(a, DoA(_))
1353 .InSequence(s)
1354 .RetiresOnSaturation();
1355 EXPECT_CALL(a, DoA(1))
1356 .InSequence(s);
1357
1358 a.DoA(1);
1359 a.DoA(2);
1360 a.DoA(1);
1361}
1362
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001363// Tests Expectation.
1364
1365TEST(ExpectationTest, ConstrutorsWork) {
1366 MockA a;
1367 Expectation e1; // Default ctor.
zhanyong.waned6c9272011-02-23 19:39:27 +00001368
1369 // Ctor from various forms of EXPECT_CALL.
1370 Expectation e2 = EXPECT_CALL(a, DoA(2));
1371 Expectation e3 = EXPECT_CALL(a, DoA(3)).With(_);
1372 {
1373 Sequence s;
1374 Expectation e4 = EXPECT_CALL(a, DoA(4)).Times(1);
1375 Expectation e5 = EXPECT_CALL(a, DoA(5)).InSequence(s);
1376 }
1377 Expectation e6 = EXPECT_CALL(a, DoA(6)).After(e2);
1378 Expectation e7 = EXPECT_CALL(a, DoA(7)).WillOnce(Return());
1379 Expectation e8 = EXPECT_CALL(a, DoA(8)).WillRepeatedly(Return());
1380 Expectation e9 = EXPECT_CALL(a, DoA(9)).RetiresOnSaturation();
1381
1382 Expectation e10 = e2; // Copy ctor.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001383
1384 EXPECT_THAT(e1, Ne(e2));
zhanyong.waned6c9272011-02-23 19:39:27 +00001385 EXPECT_THAT(e2, Eq(e10));
1386
1387 a.DoA(2);
1388 a.DoA(3);
1389 a.DoA(4);
1390 a.DoA(5);
1391 a.DoA(6);
1392 a.DoA(7);
1393 a.DoA(8);
1394 a.DoA(9);
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001395}
1396
1397TEST(ExpectationTest, AssignmentWorks) {
1398 MockA a;
1399 Expectation e1;
1400 Expectation e2 = EXPECT_CALL(a, DoA(1));
1401
1402 EXPECT_THAT(e1, Ne(e2));
1403
1404 e1 = e2;
1405 EXPECT_THAT(e1, Eq(e2));
1406
1407 a.DoA(1);
1408}
1409
1410// Tests ExpectationSet.
1411
1412TEST(ExpectationSetTest, MemberTypesAreCorrect) {
1413 ::testing::StaticAssertTypeEq<Expectation, ExpectationSet::value_type>();
1414}
1415
1416TEST(ExpectationSetTest, ConstructorsWork) {
1417 MockA a;
1418
1419 Expectation e1;
1420 const Expectation e2;
1421 ExpectationSet es1; // Default ctor.
1422 ExpectationSet es2 = EXPECT_CALL(a, DoA(1)); // Ctor from EXPECT_CALL.
1423 ExpectationSet es3 = e1; // Ctor from Expectation.
1424 ExpectationSet es4(e1); // Ctor from Expectation; alternative syntax.
1425 ExpectationSet es5 = e2; // Ctor from const Expectation.
1426 ExpectationSet es6(e2); // Ctor from const Expectation; alternative syntax.
1427 ExpectationSet es7 = es2; // Copy ctor.
1428
1429 EXPECT_EQ(0, es1.size());
1430 EXPECT_EQ(1, es2.size());
1431 EXPECT_EQ(1, es3.size());
1432 EXPECT_EQ(1, es4.size());
1433 EXPECT_EQ(1, es5.size());
1434 EXPECT_EQ(1, es6.size());
1435 EXPECT_EQ(1, es7.size());
1436
1437 EXPECT_THAT(es3, Ne(es2));
1438 EXPECT_THAT(es4, Eq(es3));
1439 EXPECT_THAT(es5, Eq(es4));
1440 EXPECT_THAT(es6, Eq(es5));
1441 EXPECT_THAT(es7, Eq(es2));
1442 a.DoA(1);
1443}
1444
1445TEST(ExpectationSetTest, AssignmentWorks) {
1446 ExpectationSet es1;
1447 ExpectationSet es2 = Expectation();
1448
1449 es1 = es2;
1450 EXPECT_EQ(1, es1.size());
1451 EXPECT_THAT(*(es1.begin()), Eq(Expectation()));
1452 EXPECT_THAT(es1, Eq(es2));
1453}
1454
1455TEST(ExpectationSetTest, InsertionWorks) {
1456 ExpectationSet es1;
1457 Expectation e1;
1458 es1 += e1;
1459 EXPECT_EQ(1, es1.size());
1460 EXPECT_THAT(*(es1.begin()), Eq(e1));
1461
1462 MockA a;
1463 Expectation e2 = EXPECT_CALL(a, DoA(1));
1464 es1 += e2;
1465 EXPECT_EQ(2, es1.size());
1466
1467 ExpectationSet::const_iterator it1 = es1.begin();
1468 ExpectationSet::const_iterator it2 = it1;
1469 ++it2;
1470 EXPECT_TRUE(*it1 == e1 || *it2 == e1); // e1 must be in the set.
1471 EXPECT_TRUE(*it1 == e2 || *it2 == e2); // e2 must be in the set too.
1472 a.DoA(1);
1473}
1474
1475TEST(ExpectationSetTest, SizeWorks) {
1476 ExpectationSet es;
1477 EXPECT_EQ(0, es.size());
1478
1479 es += Expectation();
1480 EXPECT_EQ(1, es.size());
1481
1482 MockA a;
1483 es += EXPECT_CALL(a, DoA(1));
1484 EXPECT_EQ(2, es.size());
1485
1486 a.DoA(1);
1487}
1488
1489TEST(ExpectationSetTest, IsEnumerable) {
1490 ExpectationSet es;
1491 EXPECT_THAT(es.begin(), Eq(es.end()));
1492
1493 es += Expectation();
1494 ExpectationSet::const_iterator it = es.begin();
1495 EXPECT_THAT(it, Ne(es.end()));
1496 EXPECT_THAT(*it, Eq(Expectation()));
1497 ++it;
1498 EXPECT_THAT(it, Eq(es.end()));
1499}
1500
1501// Tests the .After() clause.
1502
1503TEST(AfterTest, SucceedsWhenPartialOrderIsSatisfied) {
1504 MockA a;
1505 ExpectationSet es;
1506 es += EXPECT_CALL(a, DoA(1));
1507 es += EXPECT_CALL(a, DoA(2));
1508 EXPECT_CALL(a, DoA(3))
1509 .After(es);
1510
1511 a.DoA(1);
1512 a.DoA(2);
1513 a.DoA(3);
1514}
1515
1516TEST(AfterTest, SucceedsWhenTotalOrderIsSatisfied) {
1517 MockA a;
1518 MockB b;
1519 // The following also verifies that const Expectation objects work
1520 // too. Do not remove the const modifiers.
1521 const Expectation e1 = EXPECT_CALL(a, DoA(1));
1522 const Expectation e2 = EXPECT_CALL(b, DoB())
1523 .Times(2)
1524 .After(e1);
1525 EXPECT_CALL(a, DoA(2)).After(e2);
1526
1527 a.DoA(1);
1528 b.DoB();
1529 b.DoB();
1530 a.DoA(2);
1531}
1532
1533// Calls must be in strict order when specified so.
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00001534TEST(AfterDeathTest, CallsMustBeInStrictOrderWhenSpecifiedSo) {
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001535 MockA a;
1536 MockB b;
1537 Expectation e1 = EXPECT_CALL(a, DoA(1));
1538 Expectation e2 = EXPECT_CALL(b, DoB())
1539 .Times(2)
1540 .After(e1);
1541 EXPECT_CALL(a, ReturnResult(2))
1542 .After(e2)
1543 .WillOnce(Return(Result()));
1544
1545 a.DoA(1);
1546 // If a call to ReturnResult() violates the specified order, no
1547 // matching expectation will be found, and thus the default action
1548 // will be done. Since the return type of ReturnResult() is not a
1549 // built-in type, gmock won't know what to return and will thus
1550 // abort the program. Therefore a death test can tell us whether
1551 // gmock catches the order violation correctly.
1552 //
1553 // gtest and gmock print messages to stdout, which isn't captured by
1554 // death tests. Therefore we have to match with an empty regular
1555 // expression in all the EXPECT_DEATH()s.
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00001556 EXPECT_DEATH_IF_SUPPORTED(a.ReturnResult(2), "");
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001557
1558 b.DoB();
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00001559 EXPECT_DEATH_IF_SUPPORTED(a.ReturnResult(2), "");
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001560
1561 b.DoB();
1562 a.ReturnResult(2);
1563}
1564
1565// Calls must satisfy the partial order when specified so.
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00001566TEST(AfterDeathTest, CallsMustSatisfyPartialOrderWhenSpecifiedSo) {
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001567 MockA a;
1568 Expectation e = EXPECT_CALL(a, DoA(1));
1569 const ExpectationSet es = EXPECT_CALL(a, DoA(2));
1570 EXPECT_CALL(a, ReturnResult(3))
1571 .After(e, es)
1572 .WillOnce(Return(Result()));
1573
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00001574 EXPECT_DEATH_IF_SUPPORTED(a.ReturnResult(3), "");
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001575
1576 a.DoA(2);
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00001577 EXPECT_DEATH_IF_SUPPORTED(a.ReturnResult(3), "");
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001578
1579 a.DoA(1);
1580 a.ReturnResult(3);
1581}
1582
1583// .After() can be combined with .InSequence().
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00001584TEST(AfterDeathTest, CanBeUsedWithInSequence) {
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001585 MockA a;
1586 Sequence s;
1587 Expectation e = EXPECT_CALL(a, DoA(1));
1588 EXPECT_CALL(a, DoA(2)).InSequence(s);
1589 EXPECT_CALL(a, ReturnResult(3))
1590 .InSequence(s).After(e)
1591 .WillOnce(Return(Result()));
1592
1593 a.DoA(1);
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00001594 EXPECT_DEATH_IF_SUPPORTED(a.ReturnResult(3), "");
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001595
1596 a.DoA(2);
1597 a.ReturnResult(3);
1598}
1599
1600// .After() can be called multiple times.
1601TEST(AfterTest, CanBeCalledManyTimes) {
1602 MockA a;
1603 Expectation e1 = EXPECT_CALL(a, DoA(1));
1604 Expectation e2 = EXPECT_CALL(a, DoA(2));
1605 Expectation e3 = EXPECT_CALL(a, DoA(3));
1606 EXPECT_CALL(a, DoA(4))
1607 .After(e1)
1608 .After(e2)
1609 .After(e3);
1610
1611 a.DoA(3);
1612 a.DoA(1);
1613 a.DoA(2);
1614 a.DoA(4);
1615}
1616
1617// .After() accepts up to 5 arguments.
1618TEST(AfterTest, AcceptsUpToFiveArguments) {
1619 MockA a;
1620 Expectation e1 = EXPECT_CALL(a, DoA(1));
1621 Expectation e2 = EXPECT_CALL(a, DoA(2));
1622 Expectation e3 = EXPECT_CALL(a, DoA(3));
1623 ExpectationSet es1 = EXPECT_CALL(a, DoA(4));
1624 ExpectationSet es2 = EXPECT_CALL(a, DoA(5));
1625 EXPECT_CALL(a, DoA(6))
1626 .After(e1, e2, e3, es1, es2);
1627
1628 a.DoA(5);
1629 a.DoA(2);
1630 a.DoA(4);
1631 a.DoA(1);
1632 a.DoA(3);
1633 a.DoA(6);
1634}
1635
1636// .After() allows input to contain duplicated Expectations.
1637TEST(AfterTest, AcceptsDuplicatedInput) {
1638 MockA a;
1639 Expectation e1 = EXPECT_CALL(a, DoA(1));
1640 Expectation e2 = EXPECT_CALL(a, DoA(2));
1641 ExpectationSet es;
1642 es += e1;
1643 es += e2;
1644 EXPECT_CALL(a, ReturnResult(3))
1645 .After(e1, e2, es, e1)
1646 .WillOnce(Return(Result()));
1647
1648 a.DoA(1);
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00001649 EXPECT_DEATH_IF_SUPPORTED(a.ReturnResult(3), "");
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001650
1651 a.DoA(2);
1652 a.ReturnResult(3);
1653}
1654
1655// An Expectation added to an ExpectationSet after it has been used in
1656// an .After() has no effect.
1657TEST(AfterTest, ChangesToExpectationSetHaveNoEffectAfterwards) {
1658 MockA a;
1659 ExpectationSet es1 = EXPECT_CALL(a, DoA(1));
1660 Expectation e2 = EXPECT_CALL(a, DoA(2));
1661 EXPECT_CALL(a, DoA(3))
1662 .After(es1);
1663 es1 += e2;
1664
1665 a.DoA(1);
1666 a.DoA(3);
1667 a.DoA(2);
1668}
1669
shiqiane35fdd92008-12-10 05:08:54 +00001670// Tests that Google Mock correctly handles calls to mock functions
1671// after a mock object owning one of their pre-requisites has died.
1672
1673// Tests that calls that satisfy the original spec are successful.
1674TEST(DeletingMockEarlyTest, Success1) {
1675 MockB* const b1 = new MockB;
1676 MockA* const a = new MockA;
1677 MockB* const b2 = new MockB;
1678
1679 {
1680 InSequence dummy;
1681 EXPECT_CALL(*b1, DoB(_))
1682 .WillOnce(Return(1));
1683 EXPECT_CALL(*a, Binary(_, _))
1684 .Times(AnyNumber())
1685 .WillRepeatedly(Return(true));
1686 EXPECT_CALL(*b2, DoB(_))
1687 .Times(AnyNumber())
1688 .WillRepeatedly(Return(2));
1689 }
1690
1691 EXPECT_EQ(1, b1->DoB(1));
1692 delete b1;
1693 // a's pre-requisite has died.
1694 EXPECT_TRUE(a->Binary(0, 1));
1695 delete b2;
1696 // a's successor has died.
1697 EXPECT_TRUE(a->Binary(1, 2));
1698 delete a;
1699}
1700
1701// Tests that calls that satisfy the original spec are successful.
1702TEST(DeletingMockEarlyTest, Success2) {
1703 MockB* const b1 = new MockB;
1704 MockA* const a = new MockA;
1705 MockB* const b2 = new MockB;
1706
1707 {
1708 InSequence dummy;
1709 EXPECT_CALL(*b1, DoB(_))
1710 .WillOnce(Return(1));
1711 EXPECT_CALL(*a, Binary(_, _))
1712 .Times(AnyNumber());
1713 EXPECT_CALL(*b2, DoB(_))
1714 .Times(AnyNumber())
1715 .WillRepeatedly(Return(2));
1716 }
1717
1718 delete a; // a is trivially satisfied.
1719 EXPECT_EQ(1, b1->DoB(1));
1720 EXPECT_EQ(2, b2->DoB(2));
1721 delete b1;
1722 delete b2;
1723}
1724
zhanyong.wan6f147692009-03-03 06:44:08 +00001725// Tests that it's OK to delete a mock object itself in its action.
1726
zhanyong.wan32de5f52009-12-23 00:13:23 +00001727// Suppresses warning on unreferenced formal parameter in MSVC with
1728// -W4.
1729#ifdef _MSC_VER
zhanyong.wan658ac0b2011-02-24 07:29:13 +00001730# pragma warning(push)
1731# pragma warning(disable:4100)
zhanyong.wan32de5f52009-12-23 00:13:23 +00001732#endif
1733
zhanyong.wan6f147692009-03-03 06:44:08 +00001734ACTION_P(Delete, ptr) { delete ptr; }
1735
zhanyong.wan32de5f52009-12-23 00:13:23 +00001736#ifdef _MSC_VER
zhanyong.wan658ac0b2011-02-24 07:29:13 +00001737# pragma warning(pop)
zhanyong.wan32de5f52009-12-23 00:13:23 +00001738#endif
1739
zhanyong.wan6f147692009-03-03 06:44:08 +00001740TEST(DeletingMockEarlyTest, CanDeleteSelfInActionReturningVoid) {
1741 MockA* const a = new MockA;
1742 EXPECT_CALL(*a, DoA(_)).WillOnce(Delete(a));
1743 a->DoA(42); // This will cause a to be deleted.
1744}
1745
1746TEST(DeletingMockEarlyTest, CanDeleteSelfInActionReturningValue) {
1747 MockA* const a = new MockA;
1748 EXPECT_CALL(*a, ReturnResult(_))
1749 .WillOnce(DoAll(Delete(a), Return(Result())));
1750 a->ReturnResult(42); // This will cause a to be deleted.
1751}
1752
1753// Tests that calls that violate the original spec yield failures.
shiqiane35fdd92008-12-10 05:08:54 +00001754TEST(DeletingMockEarlyTest, Failure1) {
1755 MockB* const b1 = new MockB;
1756 MockA* const a = new MockA;
1757 MockB* const b2 = new MockB;
1758
1759 {
1760 InSequence dummy;
1761 EXPECT_CALL(*b1, DoB(_))
1762 .WillOnce(Return(1));
1763 EXPECT_CALL(*a, Binary(_, _))
1764 .Times(AnyNumber());
1765 EXPECT_CALL(*b2, DoB(_))
1766 .Times(AnyNumber())
1767 .WillRepeatedly(Return(2));
1768 }
1769
1770 delete a; // a is trivially satisfied.
1771 EXPECT_NONFATAL_FAILURE({
1772 b2->DoB(2);
1773 }, "Unexpected mock function call");
1774 EXPECT_EQ(1, b1->DoB(1));
1775 delete b1;
1776 delete b2;
1777}
1778
zhanyong.wan6f147692009-03-03 06:44:08 +00001779// Tests that calls that violate the original spec yield failures.
shiqiane35fdd92008-12-10 05:08:54 +00001780TEST(DeletingMockEarlyTest, Failure2) {
1781 MockB* const b1 = new MockB;
1782 MockA* const a = new MockA;
1783 MockB* const b2 = new MockB;
1784
1785 {
1786 InSequence dummy;
1787 EXPECT_CALL(*b1, DoB(_));
1788 EXPECT_CALL(*a, Binary(_, _))
1789 .Times(AnyNumber());
1790 EXPECT_CALL(*b2, DoB(_))
1791 .Times(AnyNumber());
1792 }
1793
1794 EXPECT_NONFATAL_FAILURE(delete b1,
1795 "Actual: never called");
1796 EXPECT_NONFATAL_FAILURE(a->Binary(0, 1),
1797 "Unexpected mock function call");
1798 EXPECT_NONFATAL_FAILURE(b2->DoB(1),
1799 "Unexpected mock function call");
1800 delete a;
1801 delete b2;
1802}
1803
1804class EvenNumberCardinality : public CardinalityInterface {
1805 public:
1806 // Returns true iff call_count calls will satisfy this cardinality.
1807 virtual bool IsSatisfiedByCallCount(int call_count) const {
1808 return call_count % 2 == 0;
1809 }
1810
1811 // Returns true iff call_count calls will saturate this cardinality.
zhanyong.wan32de5f52009-12-23 00:13:23 +00001812 virtual bool IsSaturatedByCallCount(int /* call_count */) const {
1813 return false;
1814 }
shiqiane35fdd92008-12-10 05:08:54 +00001815
1816 // Describes self to an ostream.
1817 virtual void DescribeTo(::std::ostream* os) const {
1818 *os << "called even number of times";
1819 }
1820};
1821
1822Cardinality EvenNumber() {
1823 return Cardinality(new EvenNumberCardinality);
1824}
1825
1826TEST(ExpectationBaseTest,
1827 AllPrerequisitesAreSatisfiedWorksForNonMonotonicCardinality) {
1828 MockA* a = new MockA;
1829 Sequence s;
1830
1831 EXPECT_CALL(*a, DoA(1))
1832 .Times(EvenNumber())
1833 .InSequence(s);
1834 EXPECT_CALL(*a, DoA(2))
1835 .Times(AnyNumber())
1836 .InSequence(s);
1837 EXPECT_CALL(*a, DoA(3))
1838 .Times(AnyNumber());
1839
1840 a->DoA(3);
1841 a->DoA(1);
1842 EXPECT_NONFATAL_FAILURE(a->DoA(2), "Unexpected mock function call");
1843 EXPECT_NONFATAL_FAILURE(delete a, "to be called even number of times");
1844}
1845
1846// The following tests verify the message generated when a mock
1847// function is called.
1848
1849struct Printable {
1850};
1851
1852inline void operator<<(::std::ostream& os, const Printable&) {
1853 os << "Printable";
1854}
1855
1856struct Unprintable {
1857 Unprintable() : value(0) {}
1858 int value;
1859};
1860
1861class MockC {
1862 public:
zhanyong.wan32de5f52009-12-23 00:13:23 +00001863 MockC() {}
1864
shiqiane35fdd92008-12-10 05:08:54 +00001865 MOCK_METHOD6(VoidMethod, void(bool cond, int n, string s, void* p,
1866 const Printable& x, Unprintable y));
1867 MOCK_METHOD0(NonVoidMethod, int()); // NOLINT
zhanyong.wan32de5f52009-12-23 00:13:23 +00001868
1869 private:
1870 GTEST_DISALLOW_COPY_AND_ASSIGN_(MockC);
shiqiane35fdd92008-12-10 05:08:54 +00001871};
1872
vladlosev76c1c612010-05-05 19:47:46 +00001873class VerboseFlagPreservingFixture : public testing::Test {
1874 protected:
vladlosev76c1c612010-05-05 19:47:46 +00001875 VerboseFlagPreservingFixture()
jgm38513a82012-11-15 15:50:36 +00001876 : saved_verbose_flag_(GMOCK_FLAG(verbose)) {}
vladlosev76c1c612010-05-05 19:47:46 +00001877
1878 ~VerboseFlagPreservingFixture() { GMOCK_FLAG(verbose) = saved_verbose_flag_; }
1879
1880 private:
1881 const string saved_verbose_flag_;
1882
1883 GTEST_DISALLOW_COPY_AND_ASSIGN_(VerboseFlagPreservingFixture);
1884};
1885
zhanyong.wan2516f602010-08-31 18:28:02 +00001886#if GTEST_HAS_STREAM_REDIRECTION
shiqiane35fdd92008-12-10 05:08:54 +00001887
1888// Tests that an uninteresting mock function call generates a warning
1889// containing the stack trace.
1890TEST(FunctionCallMessageTest, UninterestingCallGeneratesFyiWithStackTrace) {
1891 MockC c;
zhanyong.wan470df422010-02-02 22:34:58 +00001892 CaptureStdout();
shiqiane35fdd92008-12-10 05:08:54 +00001893 c.VoidMethod(false, 5, "Hi", NULL, Printable(), Unprintable());
jgm38513a82012-11-15 15:50:36 +00001894 const std::string output = GetCapturedStdout();
shiqiane35fdd92008-12-10 05:08:54 +00001895 EXPECT_PRED_FORMAT2(IsSubstring, "GMOCK WARNING", output);
1896 EXPECT_PRED_FORMAT2(IsSubstring, "Stack trace:", output);
zhanyong.wan658ac0b2011-02-24 07:29:13 +00001897
1898# ifndef NDEBUG
1899
shiqiane35fdd92008-12-10 05:08:54 +00001900 // We check the stack trace content in dbg-mode only, as opt-mode
1901 // may inline the call we are interested in seeing.
1902
1903 // Verifies that a void mock function's name appears in the stack
1904 // trace.
zhanyong.wan470df422010-02-02 22:34:58 +00001905 EXPECT_PRED_FORMAT2(IsSubstring, "VoidMethod(", output);
shiqiane35fdd92008-12-10 05:08:54 +00001906
1907 // Verifies that a non-void mock function's name appears in the
1908 // stack trace.
zhanyong.wan470df422010-02-02 22:34:58 +00001909 CaptureStdout();
shiqiane35fdd92008-12-10 05:08:54 +00001910 c.NonVoidMethod();
jgm38513a82012-11-15 15:50:36 +00001911 const std::string output2 = GetCapturedStdout();
zhanyong.wan470df422010-02-02 22:34:58 +00001912 EXPECT_PRED_FORMAT2(IsSubstring, "NonVoidMethod(", output2);
zhanyong.wan658ac0b2011-02-24 07:29:13 +00001913
1914# endif // NDEBUG
shiqiane35fdd92008-12-10 05:08:54 +00001915}
1916
1917// Tests that an uninteresting mock function call causes the function
1918// arguments and return value to be printed.
1919TEST(FunctionCallMessageTest, UninterestingCallPrintsArgumentsAndReturnValue) {
1920 // A non-void mock function.
1921 MockB b;
zhanyong.wan470df422010-02-02 22:34:58 +00001922 CaptureStdout();
shiqiane35fdd92008-12-10 05:08:54 +00001923 b.DoB();
jgm38513a82012-11-15 15:50:36 +00001924 const std::string output1 = GetCapturedStdout();
shiqiane35fdd92008-12-10 05:08:54 +00001925 EXPECT_PRED_FORMAT2(
1926 IsSubstring,
1927 "Uninteresting mock function call - returning default value.\n"
1928 " Function call: DoB()\n"
zhanyong.wan470df422010-02-02 22:34:58 +00001929 " Returns: 0\n", output1.c_str());
shiqiane35fdd92008-12-10 05:08:54 +00001930 // Makes sure the return value is printed.
1931
1932 // A void mock function.
1933 MockC c;
zhanyong.wan470df422010-02-02 22:34:58 +00001934 CaptureStdout();
shiqiane35fdd92008-12-10 05:08:54 +00001935 c.VoidMethod(false, 5, "Hi", NULL, Printable(), Unprintable());
jgm38513a82012-11-15 15:50:36 +00001936 const std::string output2 = GetCapturedStdout();
zhanyong.wan470df422010-02-02 22:34:58 +00001937 EXPECT_THAT(output2.c_str(),
1938 ContainsRegex(
1939 "Uninteresting mock function call - returning directly\\.\n"
1940 " Function call: VoidMethod"
1941 "\\(false, 5, \"Hi\", NULL, @.+ "
zhanyong.wanc6333dc2010-08-09 18:20:45 +00001942 "Printable, 4-byte object <00-00 00-00>\\)"));
shiqiane35fdd92008-12-10 05:08:54 +00001943 // A void function has no return value to print.
1944}
1945
1946// Tests how the --gmock_verbose flag affects Google Mock's output.
1947
vladlosev76c1c612010-05-05 19:47:46 +00001948class GMockVerboseFlagTest : public VerboseFlagPreservingFixture {
shiqiane35fdd92008-12-10 05:08:54 +00001949 public:
1950 // Verifies that the given Google Mock output is correct. (When
1951 // should_print is true, the output should match the given regex and
1952 // contain the given function name in the stack trace. When it's
1953 // false, the output should be empty.)
jgm38513a82012-11-15 15:50:36 +00001954 void VerifyOutput(const std::string& output, bool should_print,
zhanyong.wan470df422010-02-02 22:34:58 +00001955 const string& expected_substring,
shiqiane35fdd92008-12-10 05:08:54 +00001956 const string& function_name) {
1957 if (should_print) {
zhanyong.wan470df422010-02-02 22:34:58 +00001958 EXPECT_THAT(output.c_str(), HasSubstr(expected_substring));
zhanyong.wan658ac0b2011-02-24 07:29:13 +00001959# ifndef NDEBUG
shiqiane35fdd92008-12-10 05:08:54 +00001960 // We check the stack trace content in dbg-mode only, as opt-mode
1961 // may inline the call we are interested in seeing.
zhanyong.wan470df422010-02-02 22:34:58 +00001962 EXPECT_THAT(output.c_str(), HasSubstr(function_name));
zhanyong.wan658ac0b2011-02-24 07:29:13 +00001963# else
zhanyong.wan470df422010-02-02 22:34:58 +00001964 // Suppresses 'unused function parameter' warnings.
1965 static_cast<void>(function_name);
zhanyong.wan658ac0b2011-02-24 07:29:13 +00001966# endif // NDEBUG
shiqiane35fdd92008-12-10 05:08:54 +00001967 } else {
zhanyong.wan470df422010-02-02 22:34:58 +00001968 EXPECT_STREQ("", output.c_str());
shiqiane35fdd92008-12-10 05:08:54 +00001969 }
1970 }
1971
1972 // Tests how the flag affects expected calls.
1973 void TestExpectedCall(bool should_print) {
1974 MockA a;
1975 EXPECT_CALL(a, DoA(5));
1976 EXPECT_CALL(a, Binary(_, 1))
1977 .WillOnce(Return(true));
1978
1979 // A void-returning function.
zhanyong.wan470df422010-02-02 22:34:58 +00001980 CaptureStdout();
shiqiane35fdd92008-12-10 05:08:54 +00001981 a.DoA(5);
1982 VerifyOutput(
zhanyong.wan470df422010-02-02 22:34:58 +00001983 GetCapturedStdout(),
shiqiane35fdd92008-12-10 05:08:54 +00001984 should_print,
zhanyong.wan470df422010-02-02 22:34:58 +00001985 "Mock function call matches EXPECT_CALL(a, DoA(5))...\n"
1986 " Function call: DoA(5)\n"
1987 "Stack trace:\n",
1988 "DoA");
shiqiane35fdd92008-12-10 05:08:54 +00001989
1990 // A non-void-returning function.
zhanyong.wan470df422010-02-02 22:34:58 +00001991 CaptureStdout();
shiqiane35fdd92008-12-10 05:08:54 +00001992 a.Binary(2, 1);
1993 VerifyOutput(
zhanyong.wan470df422010-02-02 22:34:58 +00001994 GetCapturedStdout(),
shiqiane35fdd92008-12-10 05:08:54 +00001995 should_print,
zhanyong.wan470df422010-02-02 22:34:58 +00001996 "Mock function call matches EXPECT_CALL(a, Binary(_, 1))...\n"
1997 " Function call: Binary(2, 1)\n"
shiqiane35fdd92008-12-10 05:08:54 +00001998 " Returns: true\n"
zhanyong.wan470df422010-02-02 22:34:58 +00001999 "Stack trace:\n",
2000 "Binary");
shiqiane35fdd92008-12-10 05:08:54 +00002001 }
2002
2003 // Tests how the flag affects uninteresting calls.
2004 void TestUninterestingCall(bool should_print) {
2005 MockA a;
2006
2007 // A void-returning function.
zhanyong.wan470df422010-02-02 22:34:58 +00002008 CaptureStdout();
shiqiane35fdd92008-12-10 05:08:54 +00002009 a.DoA(5);
2010 VerifyOutput(
zhanyong.wan470df422010-02-02 22:34:58 +00002011 GetCapturedStdout(),
shiqiane35fdd92008-12-10 05:08:54 +00002012 should_print,
2013 "\nGMOCK WARNING:\n"
zhanyong.wan470df422010-02-02 22:34:58 +00002014 "Uninteresting mock function call - returning directly.\n"
2015 " Function call: DoA(5)\n"
2016 "Stack trace:\n",
2017 "DoA");
shiqiane35fdd92008-12-10 05:08:54 +00002018
2019 // A non-void-returning function.
zhanyong.wan470df422010-02-02 22:34:58 +00002020 CaptureStdout();
shiqiane35fdd92008-12-10 05:08:54 +00002021 a.Binary(2, 1);
2022 VerifyOutput(
zhanyong.wan470df422010-02-02 22:34:58 +00002023 GetCapturedStdout(),
shiqiane35fdd92008-12-10 05:08:54 +00002024 should_print,
2025 "\nGMOCK WARNING:\n"
zhanyong.wan470df422010-02-02 22:34:58 +00002026 "Uninteresting mock function call - returning default value.\n"
2027 " Function call: Binary(2, 1)\n"
shiqiane35fdd92008-12-10 05:08:54 +00002028 " Returns: false\n"
zhanyong.wan470df422010-02-02 22:34:58 +00002029 "Stack trace:\n",
2030 "Binary");
shiqiane35fdd92008-12-10 05:08:54 +00002031 }
2032};
2033
2034// Tests that --gmock_verbose=info causes both expected and
2035// uninteresting calls to be reported.
2036TEST_F(GMockVerboseFlagTest, Info) {
2037 GMOCK_FLAG(verbose) = kInfoVerbosity;
2038 TestExpectedCall(true);
2039 TestUninterestingCall(true);
2040}
2041
2042// Tests that --gmock_verbose=warning causes uninteresting calls to be
2043// reported.
2044TEST_F(GMockVerboseFlagTest, Warning) {
2045 GMOCK_FLAG(verbose) = kWarningVerbosity;
2046 TestExpectedCall(false);
2047 TestUninterestingCall(true);
2048}
2049
2050// Tests that --gmock_verbose=warning causes neither expected nor
2051// uninteresting calls to be reported.
2052TEST_F(GMockVerboseFlagTest, Error) {
2053 GMOCK_FLAG(verbose) = kErrorVerbosity;
2054 TestExpectedCall(false);
2055 TestUninterestingCall(false);
2056}
2057
2058// Tests that --gmock_verbose=SOME_INVALID_VALUE has the same effect
2059// as --gmock_verbose=warning.
2060TEST_F(GMockVerboseFlagTest, InvalidFlagIsTreatedAsWarning) {
2061 GMOCK_FLAG(verbose) = "invalid"; // Treated as "warning".
2062 TestExpectedCall(false);
2063 TestUninterestingCall(true);
2064}
2065
zhanyong.wan2516f602010-08-31 18:28:02 +00002066#endif // GTEST_HAS_STREAM_REDIRECTION
shiqiane35fdd92008-12-10 05:08:54 +00002067
zhanyong.wan9413f2f2009-05-29 19:50:06 +00002068// A helper class that generates a failure when printed. We use it to
2069// ensure that Google Mock doesn't print a value (even to an internal
2070// buffer) when it is not supposed to do so.
2071class PrintMeNot {};
2072
2073void PrintTo(PrintMeNot /* dummy */, ::std::ostream* /* os */) {
2074 ADD_FAILURE() << "Google Mock is printing a value that shouldn't be "
2075 << "printed even to an internal buffer.";
2076}
2077
2078class LogTestHelper {
2079 public:
zhanyong.wan32de5f52009-12-23 00:13:23 +00002080 LogTestHelper() {}
2081
zhanyong.wan9413f2f2009-05-29 19:50:06 +00002082 MOCK_METHOD1(Foo, PrintMeNot(PrintMeNot));
zhanyong.wan32de5f52009-12-23 00:13:23 +00002083
2084 private:
2085 GTEST_DISALLOW_COPY_AND_ASSIGN_(LogTestHelper);
zhanyong.wan9413f2f2009-05-29 19:50:06 +00002086};
2087
vladlosev76c1c612010-05-05 19:47:46 +00002088class GMockLogTest : public VerboseFlagPreservingFixture {
zhanyong.wan9413f2f2009-05-29 19:50:06 +00002089 protected:
zhanyong.wan9413f2f2009-05-29 19:50:06 +00002090 LogTestHelper helper_;
zhanyong.wan9413f2f2009-05-29 19:50:06 +00002091};
2092
2093TEST_F(GMockLogTest, DoesNotPrintGoodCallInternallyIfVerbosityIsWarning) {
2094 GMOCK_FLAG(verbose) = kWarningVerbosity;
2095 EXPECT_CALL(helper_, Foo(_))
2096 .WillOnce(Return(PrintMeNot()));
2097 helper_.Foo(PrintMeNot()); // This is an expected call.
2098}
2099
2100TEST_F(GMockLogTest, DoesNotPrintGoodCallInternallyIfVerbosityIsError) {
2101 GMOCK_FLAG(verbose) = kErrorVerbosity;
2102 EXPECT_CALL(helper_, Foo(_))
2103 .WillOnce(Return(PrintMeNot()));
2104 helper_.Foo(PrintMeNot()); // This is an expected call.
2105}
2106
2107TEST_F(GMockLogTest, DoesNotPrintWarningInternallyIfVerbosityIsError) {
2108 GMOCK_FLAG(verbose) = kErrorVerbosity;
2109 ON_CALL(helper_, Foo(_))
2110 .WillByDefault(Return(PrintMeNot()));
2111 helper_.Foo(PrintMeNot()); // This should generate a warning.
2112}
2113
2114// Tests Mock::AllowLeak().
2115
zhanyong.wandf35a762009-04-22 22:25:31 +00002116TEST(AllowLeakTest, AllowsLeakingUnusedMockObject) {
2117 MockA* a = new MockA;
2118 Mock::AllowLeak(a);
2119}
2120
2121TEST(AllowLeakTest, CanBeCalledBeforeOnCall) {
2122 MockA* a = new MockA;
2123 Mock::AllowLeak(a);
2124 ON_CALL(*a, DoA(_)).WillByDefault(Return());
2125 a->DoA(0);
2126}
2127
2128TEST(AllowLeakTest, CanBeCalledAfterOnCall) {
2129 MockA* a = new MockA;
2130 ON_CALL(*a, DoA(_)).WillByDefault(Return());
2131 Mock::AllowLeak(a);
2132}
2133
2134TEST(AllowLeakTest, CanBeCalledBeforeExpectCall) {
2135 MockA* a = new MockA;
2136 Mock::AllowLeak(a);
2137 EXPECT_CALL(*a, DoA(_));
2138 a->DoA(0);
2139}
2140
2141TEST(AllowLeakTest, CanBeCalledAfterExpectCall) {
2142 MockA* a = new MockA;
2143 EXPECT_CALL(*a, DoA(_)).Times(AnyNumber());
2144 Mock::AllowLeak(a);
2145}
2146
2147TEST(AllowLeakTest, WorksWhenBothOnCallAndExpectCallArePresent) {
2148 MockA* a = new MockA;
2149 ON_CALL(*a, DoA(_)).WillByDefault(Return());
2150 EXPECT_CALL(*a, DoA(_)).Times(AnyNumber());
2151 Mock::AllowLeak(a);
2152}
shiqiane35fdd92008-12-10 05:08:54 +00002153
2154// Tests that we can verify and clear a mock object's expectations
2155// when none of its methods has expectations.
2156TEST(VerifyAndClearExpectationsTest, NoMethodHasExpectations) {
2157 MockB b;
2158 ASSERT_TRUE(Mock::VerifyAndClearExpectations(&b));
2159
2160 // There should be no expectations on the methods now, so we can
2161 // freely call them.
2162 EXPECT_EQ(0, b.DoB());
2163 EXPECT_EQ(0, b.DoB(1));
2164}
2165
2166// Tests that we can verify and clear a mock object's expectations
2167// when some, but not all, of its methods have expectations *and* the
2168// verification succeeds.
2169TEST(VerifyAndClearExpectationsTest, SomeMethodsHaveExpectationsAndSucceed) {
2170 MockB b;
2171 EXPECT_CALL(b, DoB())
2172 .WillOnce(Return(1));
2173 b.DoB();
2174 ASSERT_TRUE(Mock::VerifyAndClearExpectations(&b));
2175
2176 // There should be no expectations on the methods now, so we can
2177 // freely call them.
2178 EXPECT_EQ(0, b.DoB());
2179 EXPECT_EQ(0, b.DoB(1));
2180}
2181
2182// Tests that we can verify and clear a mock object's expectations
2183// when some, but not all, of its methods have expectations *and* the
2184// verification fails.
2185TEST(VerifyAndClearExpectationsTest, SomeMethodsHaveExpectationsAndFail) {
2186 MockB b;
2187 EXPECT_CALL(b, DoB())
2188 .WillOnce(Return(1));
vladlosev6c54a5e2009-10-21 06:15:34 +00002189 bool result = true;
shiqiane35fdd92008-12-10 05:08:54 +00002190 EXPECT_NONFATAL_FAILURE(result = Mock::VerifyAndClearExpectations(&b),
2191 "Actual: never called");
2192 ASSERT_FALSE(result);
2193
2194 // There should be no expectations on the methods now, so we can
2195 // freely call them.
2196 EXPECT_EQ(0, b.DoB());
2197 EXPECT_EQ(0, b.DoB(1));
2198}
2199
2200// Tests that we can verify and clear a mock object's expectations
2201// when all of its methods have expectations.
2202TEST(VerifyAndClearExpectationsTest, AllMethodsHaveExpectations) {
2203 MockB b;
2204 EXPECT_CALL(b, DoB())
2205 .WillOnce(Return(1));
2206 EXPECT_CALL(b, DoB(_))
2207 .WillOnce(Return(2));
2208 b.DoB();
2209 b.DoB(1);
2210 ASSERT_TRUE(Mock::VerifyAndClearExpectations(&b));
2211
2212 // There should be no expectations on the methods now, so we can
2213 // freely call them.
2214 EXPECT_EQ(0, b.DoB());
2215 EXPECT_EQ(0, b.DoB(1));
2216}
2217
2218// Tests that we can verify and clear a mock object's expectations
2219// when a method has more than one expectation.
2220TEST(VerifyAndClearExpectationsTest, AMethodHasManyExpectations) {
2221 MockB b;
2222 EXPECT_CALL(b, DoB(0))
2223 .WillOnce(Return(1));
2224 EXPECT_CALL(b, DoB(_))
2225 .WillOnce(Return(2));
2226 b.DoB(1);
vladlosev6c54a5e2009-10-21 06:15:34 +00002227 bool result = true;
shiqiane35fdd92008-12-10 05:08:54 +00002228 EXPECT_NONFATAL_FAILURE(result = Mock::VerifyAndClearExpectations(&b),
2229 "Actual: never called");
2230 ASSERT_FALSE(result);
2231
2232 // There should be no expectations on the methods now, so we can
2233 // freely call them.
2234 EXPECT_EQ(0, b.DoB());
2235 EXPECT_EQ(0, b.DoB(1));
2236}
2237
2238// Tests that we can call VerifyAndClearExpectations() on the same
2239// mock object multiple times.
2240TEST(VerifyAndClearExpectationsTest, CanCallManyTimes) {
2241 MockB b;
2242 EXPECT_CALL(b, DoB());
2243 b.DoB();
2244 Mock::VerifyAndClearExpectations(&b);
2245
2246 EXPECT_CALL(b, DoB(_))
2247 .WillOnce(Return(1));
2248 b.DoB(1);
2249 Mock::VerifyAndClearExpectations(&b);
2250 Mock::VerifyAndClearExpectations(&b);
2251
2252 // There should be no expectations on the methods now, so we can
2253 // freely call them.
2254 EXPECT_EQ(0, b.DoB());
2255 EXPECT_EQ(0, b.DoB(1));
2256}
2257
2258// Tests that we can clear a mock object's default actions when none
2259// of its methods has default actions.
2260TEST(VerifyAndClearTest, NoMethodHasDefaultActions) {
2261 MockB b;
2262 // If this crashes or generates a failure, the test will catch it.
2263 Mock::VerifyAndClear(&b);
2264 EXPECT_EQ(0, b.DoB());
2265}
2266
2267// Tests that we can clear a mock object's default actions when some,
2268// but not all of its methods have default actions.
2269TEST(VerifyAndClearTest, SomeMethodsHaveDefaultActions) {
2270 MockB b;
2271 ON_CALL(b, DoB())
2272 .WillByDefault(Return(1));
2273
2274 Mock::VerifyAndClear(&b);
2275
2276 // Verifies that the default action of int DoB() was removed.
2277 EXPECT_EQ(0, b.DoB());
2278}
2279
2280// Tests that we can clear a mock object's default actions when all of
2281// its methods have default actions.
2282TEST(VerifyAndClearTest, AllMethodsHaveDefaultActions) {
2283 MockB b;
2284 ON_CALL(b, DoB())
2285 .WillByDefault(Return(1));
2286 ON_CALL(b, DoB(_))
2287 .WillByDefault(Return(2));
2288
2289 Mock::VerifyAndClear(&b);
2290
2291 // Verifies that the default action of int DoB() was removed.
2292 EXPECT_EQ(0, b.DoB());
2293
2294 // Verifies that the default action of int DoB(int) was removed.
2295 EXPECT_EQ(0, b.DoB(0));
2296}
2297
2298// Tests that we can clear a mock object's default actions when a
2299// method has more than one ON_CALL() set on it.
2300TEST(VerifyAndClearTest, AMethodHasManyDefaultActions) {
2301 MockB b;
2302 ON_CALL(b, DoB(0))
2303 .WillByDefault(Return(1));
2304 ON_CALL(b, DoB(_))
2305 .WillByDefault(Return(2));
2306
2307 Mock::VerifyAndClear(&b);
2308
2309 // Verifies that the default actions (there are two) of int DoB(int)
2310 // were removed.
2311 EXPECT_EQ(0, b.DoB(0));
2312 EXPECT_EQ(0, b.DoB(1));
2313}
2314
2315// Tests that we can call VerifyAndClear() on a mock object multiple
2316// times.
2317TEST(VerifyAndClearTest, CanCallManyTimes) {
2318 MockB b;
2319 ON_CALL(b, DoB())
2320 .WillByDefault(Return(1));
2321 Mock::VerifyAndClear(&b);
2322 Mock::VerifyAndClear(&b);
2323
2324 ON_CALL(b, DoB(_))
2325 .WillByDefault(Return(1));
2326 Mock::VerifyAndClear(&b);
2327
2328 EXPECT_EQ(0, b.DoB());
2329 EXPECT_EQ(0, b.DoB(1));
2330}
2331
2332// Tests that VerifyAndClear() works when the verification succeeds.
2333TEST(VerifyAndClearTest, Success) {
2334 MockB b;
2335 ON_CALL(b, DoB())
2336 .WillByDefault(Return(1));
2337 EXPECT_CALL(b, DoB(1))
2338 .WillOnce(Return(2));
2339
2340 b.DoB();
2341 b.DoB(1);
2342 ASSERT_TRUE(Mock::VerifyAndClear(&b));
2343
2344 // There should be no expectations on the methods now, so we can
2345 // freely call them.
2346 EXPECT_EQ(0, b.DoB());
2347 EXPECT_EQ(0, b.DoB(1));
2348}
2349
2350// Tests that VerifyAndClear() works when the verification fails.
2351TEST(VerifyAndClearTest, Failure) {
2352 MockB b;
2353 ON_CALL(b, DoB(_))
2354 .WillByDefault(Return(1));
2355 EXPECT_CALL(b, DoB())
2356 .WillOnce(Return(2));
2357
2358 b.DoB(1);
vladlosev6c54a5e2009-10-21 06:15:34 +00002359 bool result = true;
shiqiane35fdd92008-12-10 05:08:54 +00002360 EXPECT_NONFATAL_FAILURE(result = Mock::VerifyAndClear(&b),
2361 "Actual: never called");
2362 ASSERT_FALSE(result);
2363
2364 // There should be no expectations on the methods now, so we can
2365 // freely call them.
2366 EXPECT_EQ(0, b.DoB());
2367 EXPECT_EQ(0, b.DoB(1));
2368}
2369
2370// Tests that VerifyAndClear() works when the default actions and
2371// expectations are set on a const mock object.
2372TEST(VerifyAndClearTest, Const) {
2373 MockB b;
2374 ON_CALL(Const(b), DoB())
2375 .WillByDefault(Return(1));
2376
2377 EXPECT_CALL(Const(b), DoB())
2378 .WillOnce(DoDefault())
2379 .WillOnce(Return(2));
2380
2381 b.DoB();
2382 b.DoB();
2383 ASSERT_TRUE(Mock::VerifyAndClear(&b));
2384
2385 // There should be no expectations on the methods now, so we can
2386 // freely call them.
2387 EXPECT_EQ(0, b.DoB());
2388 EXPECT_EQ(0, b.DoB(1));
2389}
2390
2391// Tests that we can set default actions and expectations on a mock
2392// object after VerifyAndClear() has been called on it.
2393TEST(VerifyAndClearTest, CanSetDefaultActionsAndExpectationsAfterwards) {
2394 MockB b;
2395 ON_CALL(b, DoB())
2396 .WillByDefault(Return(1));
2397 EXPECT_CALL(b, DoB(_))
2398 .WillOnce(Return(2));
2399 b.DoB(1);
2400
2401 Mock::VerifyAndClear(&b);
2402
2403 EXPECT_CALL(b, DoB())
2404 .WillOnce(Return(3));
2405 ON_CALL(b, DoB(_))
2406 .WillByDefault(Return(4));
2407
2408 EXPECT_EQ(3, b.DoB());
2409 EXPECT_EQ(4, b.DoB(1));
2410}
2411
2412// Tests that calling VerifyAndClear() on one mock object does not
2413// affect other mock objects (either of the same type or not).
2414TEST(VerifyAndClearTest, DoesNotAffectOtherMockObjects) {
2415 MockA a;
2416 MockB b1;
2417 MockB b2;
2418
2419 ON_CALL(a, Binary(_, _))
2420 .WillByDefault(Return(true));
2421 EXPECT_CALL(a, Binary(_, _))
2422 .WillOnce(DoDefault())
2423 .WillOnce(Return(false));
2424
2425 ON_CALL(b1, DoB())
2426 .WillByDefault(Return(1));
2427 EXPECT_CALL(b1, DoB(_))
2428 .WillOnce(Return(2));
2429
2430 ON_CALL(b2, DoB())
2431 .WillByDefault(Return(3));
2432 EXPECT_CALL(b2, DoB(_));
2433
2434 b2.DoB(0);
2435 Mock::VerifyAndClear(&b2);
2436
2437 // Verifies that the default actions and expectations of a and b1
2438 // are still in effect.
2439 EXPECT_TRUE(a.Binary(0, 0));
2440 EXPECT_FALSE(a.Binary(0, 0));
2441
2442 EXPECT_EQ(1, b1.DoB());
2443 EXPECT_EQ(2, b1.DoB(0));
2444}
2445
vladlosev9bcb5f92011-10-24 23:41:07 +00002446TEST(VerifyAndClearTest,
2447 DestroyingChainedMocksDoesNotDeadlockThroughExpectations) {
2448 linked_ptr<MockA> a(new MockA);
2449 ReferenceHoldingMock test_mock;
2450
2451 // EXPECT_CALL stores a reference to a inside test_mock.
2452 EXPECT_CALL(test_mock, AcceptReference(_))
2453 .WillRepeatedly(SetArgPointee<0>(a));
2454
2455 // Throw away the reference to the mock that we have in a. After this, the
2456 // only reference to it is stored by test_mock.
2457 a.reset();
2458
2459 // When test_mock goes out of scope, it destroys the last remaining reference
2460 // to the mock object originally pointed to by a. This will cause the MockA
2461 // destructor to be called from inside the ReferenceHoldingMock destructor.
2462 // The state of all mocks is protected by a single global lock, but there
2463 // should be no deadlock.
2464}
2465
2466TEST(VerifyAndClearTest,
2467 DestroyingChainedMocksDoesNotDeadlockThroughDefaultAction) {
2468 linked_ptr<MockA> a(new MockA);
2469 ReferenceHoldingMock test_mock;
2470
2471 // ON_CALL stores a reference to a inside test_mock.
2472 ON_CALL(test_mock, AcceptReference(_))
2473 .WillByDefault(SetArgPointee<0>(a));
2474
2475 // Throw away the reference to the mock that we have in a. After this, the
2476 // only reference to it is stored by test_mock.
2477 a.reset();
2478
2479 // When test_mock goes out of scope, it destroys the last remaining reference
2480 // to the mock object originally pointed to by a. This will cause the MockA
2481 // destructor to be called from inside the ReferenceHoldingMock destructor.
2482 // The state of all mocks is protected by a single global lock, but there
2483 // should be no deadlock.
2484}
2485
shiqiane35fdd92008-12-10 05:08:54 +00002486// Tests that a mock function's action can call a mock function
2487// (either the same function or a different one) either as an explicit
2488// action or as a default action without causing a dead lock. It
2489// verifies that the action is not performed inside the critical
2490// section.
vladlosev54af9ba2010-05-04 16:05:11 +00002491TEST(SynchronizationTest, CanCallMockMethodInAction) {
2492 MockA a;
2493 MockC c;
2494 ON_CALL(a, DoA(_))
2495 .WillByDefault(IgnoreResult(InvokeWithoutArgs(&c,
2496 &MockC::NonVoidMethod)));
2497 EXPECT_CALL(a, DoA(1));
2498 EXPECT_CALL(a, DoA(1))
2499 .WillOnce(Invoke(&a, &MockA::DoA))
2500 .RetiresOnSaturation();
2501 EXPECT_CALL(c, NonVoidMethod());
shiqiane35fdd92008-12-10 05:08:54 +00002502
vladlosev54af9ba2010-05-04 16:05:11 +00002503 a.DoA(1);
2504 // This will match the second EXPECT_CALL() and trigger another a.DoA(1),
2505 // which will in turn match the first EXPECT_CALL() and trigger a call to
2506 // c.NonVoidMethod() that was specified by the ON_CALL() since the first
2507 // EXPECT_CALL() did not specify an action.
shiqiane35fdd92008-12-10 05:08:54 +00002508}
2509
2510} // namespace
zhanyong.wandf35a762009-04-22 22:25:31 +00002511
zhanyong.wan9571b282009-08-07 07:15:56 +00002512// Allows the user to define his own main and then invoke gmock_main
2513// from it. This might be necessary on some platforms which require
2514// specific setup and teardown.
2515#if GMOCK_RENAME_MAIN
2516int gmock_main(int argc, char **argv) {
2517#else
zhanyong.wandf35a762009-04-22 22:25:31 +00002518int main(int argc, char **argv) {
zhanyong.wan9571b282009-08-07 07:15:56 +00002519#endif // GMOCK_RENAME_MAIN
zhanyong.wandf35a762009-04-22 22:25:31 +00002520 testing::InitGoogleMock(&argc, argv);
2521
2522 // Ensures that the tests pass no matter what value of
2523 // --gmock_catch_leaked_mocks and --gmock_verbose the user specifies.
2524 testing::GMOCK_FLAG(catch_leaked_mocks) = true;
2525 testing::GMOCK_FLAG(verbose) = testing::internal::kWarningVerbosity;
2526
2527 return RUN_ALL_TESTS();
2528}