blob: aea5228b730469f3c6b1029205a7dfc512dc4043 [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;
zhanyong.wan470df422010-02-02 22:34:58 +000091using testing::internal::ExpectationTester;
vladloseve5121b52011-02-11 23:50:38 +000092using testing::internal::FormatFileLocation;
shiqiane35fdd92008-12-10 05:08:54 +000093using testing::internal::g_gmock_mutex;
94using testing::internal::kErrorVerbosity;
95using testing::internal::kInfoVerbosity;
96using testing::internal::kWarningVerbosity;
zhanyong.wan470df422010-02-02 22:34:58 +000097using testing::internal::String;
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
160// Tests that EXPECT_CALL and ON_CALL compile in a presence of macro
161// redefining a mock method name. This could happen, for example, when
162// the tested code #includes Win32 API headers which define many APIs
163// as macros, e.g. #define TextOut TextOutW.
164
165#define Method MethodW
166
167class CC {
168 public:
169 virtual ~CC() {}
170 virtual int Method() = 0;
171};
172class MockCC : public CC {
173 public:
zhanyong.wan32de5f52009-12-23 00:13:23 +0000174 MockCC() {}
175
shiqiane35fdd92008-12-10 05:08:54 +0000176 MOCK_METHOD0(Method, int());
zhanyong.wan32de5f52009-12-23 00:13:23 +0000177
178 private:
179 GTEST_DISALLOW_COPY_AND_ASSIGN_(MockCC);
shiqiane35fdd92008-12-10 05:08:54 +0000180};
181
182// Tests that a method with expanded name compiles.
183TEST(OnCallSyntaxTest, CompilesWithMethodNameExpandedFromMacro) {
184 MockCC cc;
185 ON_CALL(cc, Method());
186}
187
188// Tests that the method with expanded name not only compiles but runs
189// and returns a correct value, too.
190TEST(OnCallSyntaxTest, WorksWithMethodNameExpandedFromMacro) {
191 MockCC cc;
192 ON_CALL(cc, Method()).WillByDefault(Return(42));
193 EXPECT_EQ(42, cc.Method());
194}
195
196// Tests that a method with expanded name compiles.
197TEST(ExpectCallSyntaxTest, CompilesWithMethodNameExpandedFromMacro) {
198 MockCC cc;
199 EXPECT_CALL(cc, Method());
200 cc.Method();
201}
202
203// Tests that it works, too.
204TEST(ExpectCallSyntaxTest, WorksWithMethodNameExpandedFromMacro) {
205 MockCC cc;
206 EXPECT_CALL(cc, Method()).WillOnce(Return(42));
207 EXPECT_EQ(42, cc.Method());
208}
209
210#undef Method // Done with macro redefinition tests.
211
212// Tests that ON_CALL evaluates its arguments exactly once as promised
213// by Google Mock.
214TEST(OnCallSyntaxTest, EvaluatesFirstArgumentOnce) {
215 MockA a;
216 MockA* pa = &a;
217
218 ON_CALL(*pa++, DoA(_));
219 EXPECT_EQ(&a + 1, pa);
220}
221
222TEST(OnCallSyntaxTest, EvaluatesSecondArgumentOnce) {
223 MockA a;
224 int n = 0;
225
226 ON_CALL(a, DoA(n++));
227 EXPECT_EQ(1, n);
228}
229
230// Tests that the syntax of ON_CALL() is enforced at run time.
231
zhanyong.wanbf550852009-06-09 06:09:53 +0000232TEST(OnCallSyntaxTest, WithIsOptional) {
shiqiane35fdd92008-12-10 05:08:54 +0000233 MockA a;
234
235 ON_CALL(a, DoA(5))
236 .WillByDefault(Return());
237 ON_CALL(a, DoA(_))
zhanyong.wanbf550852009-06-09 06:09:53 +0000238 .With(_)
shiqiane35fdd92008-12-10 05:08:54 +0000239 .WillByDefault(Return());
240}
241
zhanyong.wanbf550852009-06-09 06:09:53 +0000242TEST(OnCallSyntaxTest, WithCanAppearAtMostOnce) {
shiqiane35fdd92008-12-10 05:08:54 +0000243 MockA a;
244
245 EXPECT_NONFATAL_FAILURE({ // NOLINT
246 ON_CALL(a, ReturnResult(_))
zhanyong.wanbf550852009-06-09 06:09:53 +0000247 .With(_)
248 .With(_)
shiqiane35fdd92008-12-10 05:08:54 +0000249 .WillByDefault(Return(Result()));
zhanyong.wanbf550852009-06-09 06:09:53 +0000250 }, ".With() cannot appear more than once in an ON_CALL()");
251}
252
shiqiane35fdd92008-12-10 05:08:54 +0000253TEST(OnCallSyntaxTest, WillByDefaultIsMandatory) {
254 MockA a;
255
zhanyong.wan04d6ed82009-09-11 07:01:08 +0000256 EXPECT_DEATH_IF_SUPPORTED({
shiqiane35fdd92008-12-10 05:08:54 +0000257 ON_CALL(a, DoA(5));
258 a.DoA(5);
259 }, "");
260}
261
shiqiane35fdd92008-12-10 05:08:54 +0000262TEST(OnCallSyntaxTest, WillByDefaultCanAppearAtMostOnce) {
263 MockA a;
264
265 EXPECT_NONFATAL_FAILURE({ // NOLINT
266 ON_CALL(a, DoA(5))
267 .WillByDefault(Return())
268 .WillByDefault(Return());
269 }, ".WillByDefault() must appear exactly once in an ON_CALL()");
270}
271
272// Tests that EXPECT_CALL evaluates its arguments exactly once as
273// promised by Google Mock.
274TEST(ExpectCallSyntaxTest, EvaluatesFirstArgumentOnce) {
275 MockA a;
276 MockA* pa = &a;
277
278 EXPECT_CALL(*pa++, DoA(_));
279 a.DoA(0);
280 EXPECT_EQ(&a + 1, pa);
281}
282
283TEST(ExpectCallSyntaxTest, EvaluatesSecondArgumentOnce) {
284 MockA a;
285 int n = 0;
286
287 EXPECT_CALL(a, DoA(n++));
288 a.DoA(0);
289 EXPECT_EQ(1, n);
290}
291
292// Tests that the syntax of EXPECT_CALL() is enforced at run time.
293
zhanyong.wanbf550852009-06-09 06:09:53 +0000294TEST(ExpectCallSyntaxTest, WithIsOptional) {
shiqiane35fdd92008-12-10 05:08:54 +0000295 MockA a;
296
297 EXPECT_CALL(a, DoA(5))
298 .Times(0);
299 EXPECT_CALL(a, DoA(6))
zhanyong.wanbf550852009-06-09 06:09:53 +0000300 .With(_)
shiqiane35fdd92008-12-10 05:08:54 +0000301 .Times(0);
302}
303
zhanyong.wanbf550852009-06-09 06:09:53 +0000304TEST(ExpectCallSyntaxTest, WithCanAppearAtMostOnce) {
shiqiane35fdd92008-12-10 05:08:54 +0000305 MockA a;
306
307 EXPECT_NONFATAL_FAILURE({ // NOLINT
308 EXPECT_CALL(a, DoA(6))
zhanyong.wanbf550852009-06-09 06:09:53 +0000309 .With(_)
310 .With(_);
311 }, ".With() cannot appear more than once in an EXPECT_CALL()");
shiqiane35fdd92008-12-10 05:08:54 +0000312
313 a.DoA(6);
314}
315
zhanyong.wanbf550852009-06-09 06:09:53 +0000316TEST(ExpectCallSyntaxTest, WithMustBeFirstClause) {
shiqiane35fdd92008-12-10 05:08:54 +0000317 MockA a;
318
319 EXPECT_NONFATAL_FAILURE({ // NOLINT
320 EXPECT_CALL(a, DoA(1))
321 .Times(1)
zhanyong.wanbf550852009-06-09 06:09:53 +0000322 .With(_);
323 }, ".With() must be the first clause in an EXPECT_CALL()");
shiqiane35fdd92008-12-10 05:08:54 +0000324
325 a.DoA(1);
326
327 EXPECT_NONFATAL_FAILURE({ // NOLINT
328 EXPECT_CALL(a, DoA(2))
329 .WillOnce(Return())
zhanyong.wanbf550852009-06-09 06:09:53 +0000330 .With(_);
331 }, ".With() must be the first clause in an EXPECT_CALL()");
shiqiane35fdd92008-12-10 05:08:54 +0000332
333 a.DoA(2);
334}
335
336TEST(ExpectCallSyntaxTest, TimesCanBeInferred) {
337 MockA a;
338
339 EXPECT_CALL(a, DoA(1))
340 .WillOnce(Return());
341
342 EXPECT_CALL(a, DoA(2))
343 .WillOnce(Return())
344 .WillRepeatedly(Return());
345
346 a.DoA(1);
347 a.DoA(2);
348 a.DoA(2);
349}
350
351TEST(ExpectCallSyntaxTest, TimesCanAppearAtMostOnce) {
352 MockA a;
353
354 EXPECT_NONFATAL_FAILURE({ // NOLINT
355 EXPECT_CALL(a, DoA(1))
356 .Times(1)
357 .Times(2);
358 }, ".Times() cannot appear more than once in an EXPECT_CALL()");
359
360 a.DoA(1);
361 a.DoA(1);
362}
363
364TEST(ExpectCallSyntaxTest, TimesMustBeBeforeInSequence) {
365 MockA a;
366 Sequence s;
367
368 EXPECT_NONFATAL_FAILURE({ // NOLINT
369 EXPECT_CALL(a, DoA(1))
370 .InSequence(s)
371 .Times(1);
372 }, ".Times() cannot appear after ");
373
374 a.DoA(1);
375}
376
377TEST(ExpectCallSyntaxTest, InSequenceIsOptional) {
378 MockA a;
379 Sequence s;
380
381 EXPECT_CALL(a, DoA(1));
382 EXPECT_CALL(a, DoA(2))
383 .InSequence(s);
384
385 a.DoA(1);
386 a.DoA(2);
387}
388
389TEST(ExpectCallSyntaxTest, InSequenceCanAppearMultipleTimes) {
390 MockA a;
391 Sequence s1, s2;
392
393 EXPECT_CALL(a, DoA(1))
394 .InSequence(s1, s2)
395 .InSequence(s1);
396
397 a.DoA(1);
398}
399
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000400TEST(ExpectCallSyntaxTest, InSequenceMustBeBeforeAfter) {
401 MockA a;
402 Sequence s;
403
404 Expectation e = EXPECT_CALL(a, DoA(1))
405 .Times(AnyNumber());
406 EXPECT_NONFATAL_FAILURE({ // NOLINT
407 EXPECT_CALL(a, DoA(2))
408 .After(e)
409 .InSequence(s);
410 }, ".InSequence() cannot appear after ");
411
412 a.DoA(2);
413}
414
415TEST(ExpectCallSyntaxTest, InSequenceMustBeBeforeWillOnce) {
shiqiane35fdd92008-12-10 05:08:54 +0000416 MockA a;
417 Sequence s;
418
419 EXPECT_NONFATAL_FAILURE({ // NOLINT
420 EXPECT_CALL(a, DoA(1))
421 .WillOnce(Return())
422 .InSequence(s);
423 }, ".InSequence() cannot appear after ");
424
425 a.DoA(1);
426}
427
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000428TEST(ExpectCallSyntaxTest, AfterMustBeBeforeWillOnce) {
429 MockA a;
430
431 Expectation e = EXPECT_CALL(a, DoA(1));
432 EXPECT_NONFATAL_FAILURE({
433 EXPECT_CALL(a, DoA(2))
434 .WillOnce(Return())
435 .After(e);
436 }, ".After() cannot appear after ");
437
438 a.DoA(1);
439 a.DoA(2);
440}
441
shiqiane35fdd92008-12-10 05:08:54 +0000442TEST(ExpectCallSyntaxTest, WillIsOptional) {
443 MockA a;
444
445 EXPECT_CALL(a, DoA(1));
446 EXPECT_CALL(a, DoA(2))
447 .WillOnce(Return());
448
449 a.DoA(1);
450 a.DoA(2);
451}
452
453TEST(ExpectCallSyntaxTest, WillCanAppearMultipleTimes) {
454 MockA a;
455
456 EXPECT_CALL(a, DoA(1))
457 .Times(AnyNumber())
458 .WillOnce(Return())
459 .WillOnce(Return())
460 .WillOnce(Return());
461}
462
463TEST(ExpectCallSyntaxTest, WillMustBeBeforeWillRepeatedly) {
464 MockA a;
465
466 EXPECT_NONFATAL_FAILURE({ // NOLINT
467 EXPECT_CALL(a, DoA(1))
468 .WillRepeatedly(Return())
469 .WillOnce(Return());
470 }, ".WillOnce() cannot appear after ");
471
472 a.DoA(1);
473}
474
475TEST(ExpectCallSyntaxTest, WillRepeatedlyIsOptional) {
476 MockA a;
477
478 EXPECT_CALL(a, DoA(1))
479 .WillOnce(Return());
480 EXPECT_CALL(a, DoA(2))
481 .WillOnce(Return())
482 .WillRepeatedly(Return());
483
484 a.DoA(1);
485 a.DoA(2);
486 a.DoA(2);
487}
488
489TEST(ExpectCallSyntaxTest, WillRepeatedlyCannotAppearMultipleTimes) {
490 MockA a;
491
492 EXPECT_NONFATAL_FAILURE({ // NOLINT
493 EXPECT_CALL(a, DoA(1))
494 .WillRepeatedly(Return())
495 .WillRepeatedly(Return());
496 }, ".WillRepeatedly() cannot appear more than once in an "
497 "EXPECT_CALL()");
498}
499
500TEST(ExpectCallSyntaxTest, WillRepeatedlyMustBeBeforeRetiresOnSaturation) {
501 MockA a;
502
503 EXPECT_NONFATAL_FAILURE({ // NOLINT
504 EXPECT_CALL(a, DoA(1))
505 .RetiresOnSaturation()
506 .WillRepeatedly(Return());
507 }, ".WillRepeatedly() cannot appear after ");
508}
509
510TEST(ExpectCallSyntaxTest, RetiresOnSaturationIsOptional) {
511 MockA a;
512
513 EXPECT_CALL(a, DoA(1));
514 EXPECT_CALL(a, DoA(1))
515 .RetiresOnSaturation();
516
517 a.DoA(1);
518 a.DoA(1);
519}
520
521TEST(ExpectCallSyntaxTest, RetiresOnSaturationCannotAppearMultipleTimes) {
522 MockA a;
523
524 EXPECT_NONFATAL_FAILURE({ // NOLINT
525 EXPECT_CALL(a, DoA(1))
526 .RetiresOnSaturation()
527 .RetiresOnSaturation();
528 }, ".RetiresOnSaturation() cannot appear more than once");
529
530 a.DoA(1);
531}
532
533TEST(ExpectCallSyntaxTest, DefaultCardinalityIsOnce) {
534 {
535 MockA a;
536 EXPECT_CALL(a, DoA(1));
537 a.DoA(1);
538 }
539 EXPECT_NONFATAL_FAILURE({ // NOLINT
540 MockA a;
541 EXPECT_CALL(a, DoA(1));
542 }, "to be called once");
543 EXPECT_NONFATAL_FAILURE({ // NOLINT
544 MockA a;
545 EXPECT_CALL(a, DoA(1));
546 a.DoA(1);
547 a.DoA(1);
548 }, "to be called once");
549}
550
zhanyong.wan2516f602010-08-31 18:28:02 +0000551#if GTEST_HAS_STREAM_REDIRECTION
shiqiane35fdd92008-12-10 05:08:54 +0000552
553// Tests that Google Mock doesn't print a warning when the number of
554// WillOnce() is adequate.
555TEST(ExpectCallSyntaxTest, DoesNotWarnOnAdequateActionCount) {
zhanyong.wan470df422010-02-02 22:34:58 +0000556 CaptureStdout();
shiqiane35fdd92008-12-10 05:08:54 +0000557 {
558 MockB b;
559
560 // It's always fine to omit WillOnce() entirely.
561 EXPECT_CALL(b, DoB())
562 .Times(0);
563 EXPECT_CALL(b, DoB(1))
564 .Times(AtMost(1));
565 EXPECT_CALL(b, DoB(2))
566 .Times(1)
567 .WillRepeatedly(Return(1));
568
569 // It's fine for the number of WillOnce()s to equal the upper bound.
570 EXPECT_CALL(b, DoB(3))
571 .Times(Between(1, 2))
572 .WillOnce(Return(1))
573 .WillOnce(Return(2));
574
575 // It's fine for the number of WillOnce()s to be smaller than the
576 // upper bound when there is a WillRepeatedly().
577 EXPECT_CALL(b, DoB(4))
578 .Times(AtMost(3))
579 .WillOnce(Return(1))
580 .WillRepeatedly(Return(2));
581
582 // Satisfies the above expectations.
583 b.DoB(2);
584 b.DoB(3);
585 }
zhanyong.wan470df422010-02-02 22:34:58 +0000586 EXPECT_STREQ("", GetCapturedStdout().c_str());
shiqiane35fdd92008-12-10 05:08:54 +0000587}
588
589// Tests that Google Mock warns on having too many actions in an
590// expectation compared to its cardinality.
591TEST(ExpectCallSyntaxTest, WarnsOnTooManyActions) {
zhanyong.wan470df422010-02-02 22:34:58 +0000592 CaptureStdout();
shiqiane35fdd92008-12-10 05:08:54 +0000593 {
594 MockB b;
595
596 // Warns when the number of WillOnce()s is larger than the upper bound.
597 EXPECT_CALL(b, DoB())
598 .Times(0)
599 .WillOnce(Return(1)); // #1
600 EXPECT_CALL(b, DoB())
601 .Times(AtMost(1))
602 .WillOnce(Return(1))
603 .WillOnce(Return(2)); // #2
604 EXPECT_CALL(b, DoB(1))
605 .Times(1)
606 .WillOnce(Return(1))
607 .WillOnce(Return(2))
608 .RetiresOnSaturation(); // #3
609
610 // Warns when the number of WillOnce()s equals the upper bound and
611 // there is a WillRepeatedly().
612 EXPECT_CALL(b, DoB())
613 .Times(0)
614 .WillRepeatedly(Return(1)); // #4
615 EXPECT_CALL(b, DoB(2))
616 .Times(1)
617 .WillOnce(Return(1))
618 .WillRepeatedly(Return(2)); // #5
619
620 // Satisfies the above expectations.
621 b.DoB(1);
622 b.DoB(2);
623 }
zhanyong.wan470df422010-02-02 22:34:58 +0000624 const String output = GetCapturedStdout();
vladlosev6c54a5e2009-10-21 06:15:34 +0000625 EXPECT_PRED_FORMAT2(
626 IsSubstring,
627 "Too many actions specified in EXPECT_CALL(b, DoB())...\n"
628 "Expected to be never called, but has 1 WillOnce().",
629 output); // #1
630 EXPECT_PRED_FORMAT2(
631 IsSubstring,
632 "Too many actions specified in EXPECT_CALL(b, DoB())...\n"
633 "Expected to be called at most once, "
634 "but has 2 WillOnce()s.",
635 output); // #2
636 EXPECT_PRED_FORMAT2(
637 IsSubstring,
638 "Too many actions specified in EXPECT_CALL(b, DoB(1))...\n"
639 "Expected to be called once, but has 2 WillOnce()s.",
640 output); // #3
641 EXPECT_PRED_FORMAT2(
642 IsSubstring,
643 "Too many actions specified in EXPECT_CALL(b, DoB())...\n"
644 "Expected to be never called, but has 0 WillOnce()s "
645 "and a WillRepeatedly().",
646 output); // #4
647 EXPECT_PRED_FORMAT2(
648 IsSubstring,
649 "Too many actions specified in EXPECT_CALL(b, DoB(2))...\n"
650 "Expected to be called once, but has 1 WillOnce() "
651 "and a WillRepeatedly().",
652 output); // #5
shiqiane35fdd92008-12-10 05:08:54 +0000653}
654
655// Tests that Google Mock warns on having too few actions in an
656// expectation compared to its cardinality.
657TEST(ExpectCallSyntaxTest, WarnsOnTooFewActions) {
658 MockB b;
659
660 EXPECT_CALL(b, DoB())
661 .Times(Between(2, 3))
662 .WillOnce(Return(1));
663
zhanyong.wan470df422010-02-02 22:34:58 +0000664 CaptureStdout();
shiqiane35fdd92008-12-10 05:08:54 +0000665 b.DoB();
zhanyong.wan470df422010-02-02 22:34:58 +0000666 const String output = GetCapturedStdout();
vladlosev6c54a5e2009-10-21 06:15:34 +0000667 EXPECT_PRED_FORMAT2(
668 IsSubstring,
669 "Too few actions specified in EXPECT_CALL(b, DoB())...\n"
670 "Expected to be called between 2 and 3 times, "
671 "but has only 1 WillOnce().",
672 output);
shiqiane35fdd92008-12-10 05:08:54 +0000673 b.DoB();
674}
675
zhanyong.wan2516f602010-08-31 18:28:02 +0000676#endif // GTEST_HAS_STREAM_REDIRECTION
shiqiane35fdd92008-12-10 05:08:54 +0000677
678// Tests the semantics of ON_CALL().
679
680// Tests that the built-in default action is taken when no ON_CALL()
681// is specified.
682TEST(OnCallTest, TakesBuiltInDefaultActionWhenNoOnCall) {
683 MockB b;
684 EXPECT_CALL(b, DoB());
685
686 EXPECT_EQ(0, b.DoB());
687}
688
689// Tests that the built-in default action is taken when no ON_CALL()
690// matches the invocation.
691TEST(OnCallTest, TakesBuiltInDefaultActionWhenNoOnCallMatches) {
692 MockB b;
693 ON_CALL(b, DoB(1))
694 .WillByDefault(Return(1));
695 EXPECT_CALL(b, DoB(_));
696
697 EXPECT_EQ(0, b.DoB(2));
698}
699
700// Tests that the last matching ON_CALL() action is taken.
701TEST(OnCallTest, PicksLastMatchingOnCall) {
702 MockB b;
703 ON_CALL(b, DoB(_))
704 .WillByDefault(Return(3));
705 ON_CALL(b, DoB(2))
706 .WillByDefault(Return(2));
707 ON_CALL(b, DoB(1))
708 .WillByDefault(Return(1));
709 EXPECT_CALL(b, DoB(_));
710
711 EXPECT_EQ(2, b.DoB(2));
712}
713
714// Tests the semantics of EXPECT_CALL().
715
716// Tests that any call is allowed when no EXPECT_CALL() is specified.
717TEST(ExpectCallTest, AllowsAnyCallWhenNoSpec) {
718 MockB b;
719 EXPECT_CALL(b, DoB());
720 // There is no expectation on DoB(int).
721
722 b.DoB();
723
724 // DoB(int) can be called any number of times.
725 b.DoB(1);
726 b.DoB(2);
727}
728
729// Tests that the last matching EXPECT_CALL() fires.
730TEST(ExpectCallTest, PicksLastMatchingExpectCall) {
731 MockB b;
732 EXPECT_CALL(b, DoB(_))
733 .WillRepeatedly(Return(2));
734 EXPECT_CALL(b, DoB(1))
735 .WillRepeatedly(Return(1));
736
737 EXPECT_EQ(1, b.DoB(1));
738}
739
740// Tests lower-bound violation.
741TEST(ExpectCallTest, CatchesTooFewCalls) {
742 EXPECT_NONFATAL_FAILURE({ // NOLINT
743 MockB b;
744 EXPECT_CALL(b, DoB(5))
745 .Times(AtLeast(2));
746
747 b.DoB(5);
vladlosev6c54a5e2009-10-21 06:15:34 +0000748 }, "Actual function call count doesn't match EXPECT_CALL(b, DoB(5))...\n"
shiqiane35fdd92008-12-10 05:08:54 +0000749 " Expected: to be called at least twice\n"
750 " Actual: called once - unsatisfied and active");
751}
752
753// Tests that the cardinality can be inferred when no Times(...) is
754// specified.
755TEST(ExpectCallTest, InfersCardinalityWhenThereIsNoWillRepeatedly) {
756 {
757 MockB b;
758 EXPECT_CALL(b, DoB())
759 .WillOnce(Return(1))
760 .WillOnce(Return(2));
761
762 EXPECT_EQ(1, b.DoB());
763 EXPECT_EQ(2, b.DoB());
764 }
765
766 EXPECT_NONFATAL_FAILURE({ // NOLINT
767 MockB b;
768 EXPECT_CALL(b, DoB())
769 .WillOnce(Return(1))
770 .WillOnce(Return(2));
771
772 EXPECT_EQ(1, b.DoB());
773 }, "to be called twice");
774
775 { // NOLINT
776 MockB b;
777 EXPECT_CALL(b, DoB())
778 .WillOnce(Return(1))
779 .WillOnce(Return(2));
780
781 EXPECT_EQ(1, b.DoB());
782 EXPECT_EQ(2, b.DoB());
783 EXPECT_NONFATAL_FAILURE(b.DoB(), "to be called twice");
784 }
785}
786
787TEST(ExpectCallTest, InfersCardinality1WhenThereIsWillRepeatedly) {
788 {
789 MockB b;
790 EXPECT_CALL(b, DoB())
791 .WillOnce(Return(1))
792 .WillRepeatedly(Return(2));
793
794 EXPECT_EQ(1, b.DoB());
795 }
796
797 { // NOLINT
798 MockB b;
799 EXPECT_CALL(b, DoB())
800 .WillOnce(Return(1))
801 .WillRepeatedly(Return(2));
802
803 EXPECT_EQ(1, b.DoB());
804 EXPECT_EQ(2, b.DoB());
805 EXPECT_EQ(2, b.DoB());
806 }
807
808 EXPECT_NONFATAL_FAILURE({ // NOLINT
809 MockB b;
810 EXPECT_CALL(b, DoB())
811 .WillOnce(Return(1))
812 .WillRepeatedly(Return(2));
813 }, "to be called at least once");
814}
815
816// Tests that the n-th action is taken for the n-th matching
817// invocation.
818TEST(ExpectCallTest, NthMatchTakesNthAction) {
819 MockB b;
820 EXPECT_CALL(b, DoB())
821 .WillOnce(Return(1))
822 .WillOnce(Return(2))
823 .WillOnce(Return(3));
824
825 EXPECT_EQ(1, b.DoB());
826 EXPECT_EQ(2, b.DoB());
827 EXPECT_EQ(3, b.DoB());
828}
829
vladloseve5121b52011-02-11 23:50:38 +0000830// Tests that the WillRepeatedly() action is taken when the WillOnce(...)
831// list is exhausted.
832TEST(ExpectCallTest, TakesRepeatedActionWhenWillListIsExhausted) {
833 MockB b;
834 EXPECT_CALL(b, DoB())
835 .WillOnce(Return(1))
836 .WillRepeatedly(Return(2));
837
838 EXPECT_EQ(1, b.DoB());
839 EXPECT_EQ(2, b.DoB());
840 EXPECT_EQ(2, b.DoB());
841}
842
zhanyong.wan2516f602010-08-31 18:28:02 +0000843#if GTEST_HAS_STREAM_REDIRECTION
shiqiane35fdd92008-12-10 05:08:54 +0000844
845// Tests that the default action is taken when the WillOnce(...) list is
846// exhausted and there is no WillRepeatedly().
847TEST(ExpectCallTest, TakesDefaultActionWhenWillListIsExhausted) {
848 MockB b;
849 EXPECT_CALL(b, DoB(_))
850 .Times(1);
851 EXPECT_CALL(b, DoB())
852 .Times(AnyNumber())
853 .WillOnce(Return(1))
854 .WillOnce(Return(2));
855
zhanyong.wan470df422010-02-02 22:34:58 +0000856 CaptureStdout();
shiqiane35fdd92008-12-10 05:08:54 +0000857 EXPECT_EQ(0, b.DoB(1)); // Shouldn't generate a warning as the
858 // expectation has no action clause at all.
859 EXPECT_EQ(1, b.DoB());
860 EXPECT_EQ(2, b.DoB());
zhanyong.wan470df422010-02-02 22:34:58 +0000861 const String output1 = GetCapturedStdout();
862 EXPECT_STREQ("", output1.c_str());
shiqiane35fdd92008-12-10 05:08:54 +0000863
zhanyong.wan470df422010-02-02 22:34:58 +0000864 CaptureStdout();
shiqiane35fdd92008-12-10 05:08:54 +0000865 EXPECT_EQ(0, b.DoB());
866 EXPECT_EQ(0, b.DoB());
zhanyong.wan470df422010-02-02 22:34:58 +0000867 const String output2 = GetCapturedStdout();
868 EXPECT_THAT(output2.c_str(),
869 HasSubstr("Actions ran out in EXPECT_CALL(b, DoB())...\n"
870 "Called 3 times, but only 2 WillOnce()s are specified"
871 " - returning default value."));
872 EXPECT_THAT(output2.c_str(),
873 HasSubstr("Actions ran out in EXPECT_CALL(b, DoB())...\n"
874 "Called 4 times, but only 2 WillOnce()s are specified"
875 " - returning default value."));
shiqiane35fdd92008-12-10 05:08:54 +0000876}
877
vladloseve5121b52011-02-11 23:50:38 +0000878TEST(FunctionMockerTest, ReportsExpectCallLocationForExhausedActions) {
shiqiane35fdd92008-12-10 05:08:54 +0000879 MockB b;
vladloseve5121b52011-02-11 23:50:38 +0000880 std::string expect_call_location = FormatFileLocation(__FILE__, __LINE__ + 1);
881 EXPECT_CALL(b, DoB()).Times(AnyNumber()).WillOnce(Return(1));
shiqiane35fdd92008-12-10 05:08:54 +0000882
883 EXPECT_EQ(1, b.DoB());
vladloseve5121b52011-02-11 23:50:38 +0000884
885 CaptureStdout();
886 EXPECT_EQ(0, b.DoB());
887 const String output = GetCapturedStdout();
888 // The warning message should contain the call location.
889 EXPECT_PRED_FORMAT2(IsSubstring, expect_call_location, output);
shiqiane35fdd92008-12-10 05:08:54 +0000890}
891
vladloseve5121b52011-02-11 23:50:38 +0000892TEST(FunctionMockerTest, ReportsDefaultActionLocationOfUninterestingCalls) {
893 std::string on_call_location;
894 CaptureStdout();
895 {
896 MockB b;
897 on_call_location = FormatFileLocation(__FILE__, __LINE__ + 1);
898 ON_CALL(b, DoB(_)).WillByDefault(Return(0));
899 b.DoB(0);
900 }
901 EXPECT_PRED_FORMAT2(IsSubstring, on_call_location, GetCapturedStdout());
902}
903
904#endif // GTEST_HAS_STREAM_REDIRECTION
905
shiqiane35fdd92008-12-10 05:08:54 +0000906// Tests that an uninteresting call performs the default action.
907TEST(UninterestingCallTest, DoesDefaultAction) {
908 // When there is an ON_CALL() statement, the action specified by it
909 // should be taken.
910 MockA a;
911 ON_CALL(a, Binary(_, _))
912 .WillByDefault(Return(true));
913 EXPECT_TRUE(a.Binary(1, 2));
914
915 // When there is no ON_CALL(), the default value for the return type
916 // should be returned.
917 MockB b;
918 EXPECT_EQ(0, b.DoB());
919}
920
921// Tests that an unexpected call performs the default action.
922TEST(UnexpectedCallTest, DoesDefaultAction) {
923 // When there is an ON_CALL() statement, the action specified by it
924 // should be taken.
925 MockA a;
926 ON_CALL(a, Binary(_, _))
927 .WillByDefault(Return(true));
928 EXPECT_CALL(a, Binary(0, 0));
929 a.Binary(0, 0);
930 bool result = false;
931 EXPECT_NONFATAL_FAILURE(result = a.Binary(1, 2),
932 "Unexpected mock function call");
933 EXPECT_TRUE(result);
934
935 // When there is no ON_CALL(), the default value for the return type
936 // should be returned.
937 MockB b;
938 EXPECT_CALL(b, DoB(0))
939 .Times(0);
940 int n = -1;
941 EXPECT_NONFATAL_FAILURE(n = b.DoB(1),
942 "Unexpected mock function call");
943 EXPECT_EQ(0, n);
944}
945
946// Tests that when an unexpected void function generates the right
947// failure message.
948TEST(UnexpectedCallTest, GeneratesFailureForVoidFunction) {
949 // First, tests the message when there is only one EXPECT_CALL().
950 MockA a1;
951 EXPECT_CALL(a1, DoA(1));
952 a1.DoA(1);
953 // Ideally we should match the failure message against a regex, but
954 // EXPECT_NONFATAL_FAILURE doesn't support that, so we test for
955 // multiple sub-strings instead.
956 EXPECT_NONFATAL_FAILURE(
957 a1.DoA(9),
958 "Unexpected mock function call - returning directly.\n"
959 " Function call: DoA(9)\n"
960 "Google Mock tried the following 1 expectation, but it didn't match:");
961 EXPECT_NONFATAL_FAILURE(
962 a1.DoA(9),
963 " Expected arg #0: is equal to 1\n"
964 " Actual: 9\n"
965 " Expected: to be called once\n"
966 " Actual: called once - saturated and active");
967
968 // Next, tests the message when there are more than one EXPECT_CALL().
969 MockA a2;
970 EXPECT_CALL(a2, DoA(1));
971 EXPECT_CALL(a2, DoA(3));
972 a2.DoA(1);
973 EXPECT_NONFATAL_FAILURE(
974 a2.DoA(2),
975 "Unexpected mock function call - returning directly.\n"
976 " Function call: DoA(2)\n"
977 "Google Mock tried the following 2 expectations, but none matched:");
978 EXPECT_NONFATAL_FAILURE(
979 a2.DoA(2),
vladlosev6c54a5e2009-10-21 06:15:34 +0000980 "tried expectation #0: EXPECT_CALL(a2, DoA(1))...\n"
shiqiane35fdd92008-12-10 05:08:54 +0000981 " Expected arg #0: is equal to 1\n"
982 " Actual: 2\n"
983 " Expected: to be called once\n"
984 " Actual: called once - saturated and active");
985 EXPECT_NONFATAL_FAILURE(
986 a2.DoA(2),
vladlosev6c54a5e2009-10-21 06:15:34 +0000987 "tried expectation #1: EXPECT_CALL(a2, DoA(3))...\n"
shiqiane35fdd92008-12-10 05:08:54 +0000988 " Expected arg #0: is equal to 3\n"
989 " Actual: 2\n"
990 " Expected: to be called once\n"
991 " Actual: never called - unsatisfied and active");
992 a2.DoA(3);
993}
994
995// Tests that an unexpected non-void function generates the right
996// failure message.
997TEST(UnexpectedCallTest, GeneartesFailureForNonVoidFunction) {
998 MockB b1;
999 EXPECT_CALL(b1, DoB(1));
1000 b1.DoB(1);
1001 EXPECT_NONFATAL_FAILURE(
1002 b1.DoB(2),
1003 "Unexpected mock function call - returning default value.\n"
1004 " Function call: DoB(2)\n"
1005 " Returns: 0\n"
1006 "Google Mock tried the following 1 expectation, but it didn't match:");
1007 EXPECT_NONFATAL_FAILURE(
1008 b1.DoB(2),
1009 " Expected arg #0: is equal to 1\n"
1010 " Actual: 2\n"
1011 " Expected: to be called once\n"
1012 " Actual: called once - saturated and active");
1013}
1014
1015// Tests that Google Mock explains that an retired expectation doesn't
1016// match the call.
1017TEST(UnexpectedCallTest, RetiredExpectation) {
1018 MockB b;
1019 EXPECT_CALL(b, DoB(1))
1020 .RetiresOnSaturation();
1021
1022 b.DoB(1);
1023 EXPECT_NONFATAL_FAILURE(
1024 b.DoB(1),
1025 " Expected: the expectation is active\n"
1026 " Actual: it is retired");
1027}
1028
1029// Tests that Google Mock explains that an expectation that doesn't
1030// match the arguments doesn't match the call.
1031TEST(UnexpectedCallTest, UnmatchedArguments) {
1032 MockB b;
1033 EXPECT_CALL(b, DoB(1));
1034
1035 EXPECT_NONFATAL_FAILURE(
1036 b.DoB(2),
1037 " Expected arg #0: is equal to 1\n"
1038 " Actual: 2\n");
1039 b.DoB(1);
1040}
1041
shiqiane35fdd92008-12-10 05:08:54 +00001042// Tests that Google Mock explains that an expectation with
1043// unsatisfied pre-requisites doesn't match the call.
1044TEST(UnexpectedCallTest, UnsatisifiedPrerequisites) {
1045 Sequence s1, s2;
1046 MockB b;
1047 EXPECT_CALL(b, DoB(1))
1048 .InSequence(s1);
1049 EXPECT_CALL(b, DoB(2))
1050 .Times(AnyNumber())
1051 .InSequence(s1);
1052 EXPECT_CALL(b, DoB(3))
1053 .InSequence(s2);
1054 EXPECT_CALL(b, DoB(4))
1055 .InSequence(s1, s2);
1056
1057 ::testing::TestPartResultArray failures;
1058 {
1059 ::testing::ScopedFakeTestPartResultReporter reporter(&failures);
1060 b.DoB(4);
1061 // Now 'failures' contains the Google Test failures generated by
1062 // the above statement.
1063 }
1064
1065 // There should be one non-fatal failure.
1066 ASSERT_EQ(1, failures.size());
1067 const ::testing::TestPartResult& r = failures.GetTestPartResult(0);
zhanyong.wanbbd6e102009-09-18 18:17:19 +00001068 EXPECT_EQ(::testing::TestPartResult::kNonFatalFailure, r.type());
shiqiane35fdd92008-12-10 05:08:54 +00001069
1070 // Verifies that the failure message contains the two unsatisfied
1071 // pre-requisites but not the satisfied one.
zhanyong.wand14aaed2010-01-14 05:36:32 +00001072#if GTEST_USES_PCRE
1073 EXPECT_THAT(r.message(), ContainsRegex(
shiqiane35fdd92008-12-10 05:08:54 +00001074 // PCRE has trouble using (.|\n) to match any character, but
1075 // supports the (?s) prefix for using . to match any character.
1076 "(?s)the following immediate pre-requisites are not satisfied:\n"
1077 ".*: pre-requisite #0\n"
zhanyong.wand14aaed2010-01-14 05:36:32 +00001078 ".*: pre-requisite #1"));
1079#elif GTEST_USES_POSIX_RE
1080 EXPECT_THAT(r.message(), ContainsRegex(
shiqiane35fdd92008-12-10 05:08:54 +00001081 // POSIX RE doesn't understand the (?s) prefix, but has no trouble
1082 // with (.|\n).
1083 "the following immediate pre-requisites are not satisfied:\n"
1084 "(.|\n)*: pre-requisite #0\n"
zhanyong.wand14aaed2010-01-14 05:36:32 +00001085 "(.|\n)*: pre-requisite #1"));
1086#else
1087 // We can only use Google Test's own simple regex.
1088 EXPECT_THAT(r.message(), ContainsRegex(
1089 "the following immediate pre-requisites are not satisfied:"));
1090 EXPECT_THAT(r.message(), ContainsRegex(": pre-requisite #0"));
1091 EXPECT_THAT(r.message(), ContainsRegex(": pre-requisite #1"));
1092#endif // GTEST_USES_PCRE
shiqiane35fdd92008-12-10 05:08:54 +00001093
shiqiane35fdd92008-12-10 05:08:54 +00001094 b.DoB(1);
1095 b.DoB(3);
1096 b.DoB(4);
1097}
1098
zhanyong.wan5b95fa72009-01-27 22:28:45 +00001099TEST(UndefinedReturnValueTest, ReturnValueIsMandatory) {
1100 MockA a;
1101 // TODO(wan@google.com): We should really verify the output message,
1102 // but we cannot yet due to that EXPECT_DEATH only captures stderr
1103 // while Google Mock logs to stdout.
zhanyong.wan04d6ed82009-09-11 07:01:08 +00001104 EXPECT_DEATH_IF_SUPPORTED(a.ReturnResult(1), "");
zhanyong.wan5b95fa72009-01-27 22:28:45 +00001105}
1106
shiqiane35fdd92008-12-10 05:08:54 +00001107// Tests that an excessive call (one whose arguments match the
1108// matchers but is called too many times) performs the default action.
1109TEST(ExcessiveCallTest, DoesDefaultAction) {
1110 // When there is an ON_CALL() statement, the action specified by it
1111 // should be taken.
1112 MockA a;
1113 ON_CALL(a, Binary(_, _))
1114 .WillByDefault(Return(true));
1115 EXPECT_CALL(a, Binary(0, 0));
1116 a.Binary(0, 0);
1117 bool result = false;
1118 EXPECT_NONFATAL_FAILURE(result = a.Binary(0, 0),
1119 "Mock function called more times than expected");
1120 EXPECT_TRUE(result);
1121
1122 // When there is no ON_CALL(), the default value for the return type
1123 // should be returned.
1124 MockB b;
1125 EXPECT_CALL(b, DoB(0))
1126 .Times(0);
1127 int n = -1;
1128 EXPECT_NONFATAL_FAILURE(n = b.DoB(0),
1129 "Mock function called more times than expected");
1130 EXPECT_EQ(0, n);
1131}
1132
1133// Tests that when a void function is called too many times,
1134// the failure message contains the argument values.
1135TEST(ExcessiveCallTest, GeneratesFailureForVoidFunction) {
1136 MockA a;
1137 EXPECT_CALL(a, DoA(_))
1138 .Times(0);
1139 EXPECT_NONFATAL_FAILURE(
1140 a.DoA(9),
1141 "Mock function called more times than expected - returning directly.\n"
1142 " Function call: DoA(9)\n"
1143 " Expected: to be never called\n"
1144 " Actual: called once - over-saturated and active");
1145}
1146
1147// Tests that when a non-void function is called too many times, the
1148// failure message contains the argument values and the return value.
1149TEST(ExcessiveCallTest, GeneratesFailureForNonVoidFunction) {
1150 MockB b;
1151 EXPECT_CALL(b, DoB(_));
1152 b.DoB(1);
1153 EXPECT_NONFATAL_FAILURE(
1154 b.DoB(2),
1155 "Mock function called more times than expected - "
1156 "returning default value.\n"
1157 " Function call: DoB(2)\n"
1158 " Returns: 0\n"
1159 " Expected: to be called once\n"
1160 " Actual: called twice - over-saturated and active");
1161}
1162
1163// Tests using sequences.
1164
1165TEST(InSequenceTest, AllExpectationInScopeAreInSequence) {
1166 MockA a;
1167 {
1168 InSequence dummy;
1169
1170 EXPECT_CALL(a, DoA(1));
1171 EXPECT_CALL(a, DoA(2));
1172 }
1173
1174 EXPECT_NONFATAL_FAILURE({ // NOLINT
1175 a.DoA(2);
1176 }, "Unexpected mock function call");
1177
1178 a.DoA(1);
1179 a.DoA(2);
1180}
1181
1182TEST(InSequenceTest, NestedInSequence) {
1183 MockA a;
1184 {
1185 InSequence dummy;
1186
1187 EXPECT_CALL(a, DoA(1));
1188 {
1189 InSequence dummy2;
1190
1191 EXPECT_CALL(a, DoA(2));
1192 EXPECT_CALL(a, DoA(3));
1193 }
1194 }
1195
1196 EXPECT_NONFATAL_FAILURE({ // NOLINT
1197 a.DoA(1);
1198 a.DoA(3);
1199 }, "Unexpected mock function call");
1200
1201 a.DoA(2);
1202 a.DoA(3);
1203}
1204
1205TEST(InSequenceTest, ExpectationsOutOfScopeAreNotAffected) {
1206 MockA a;
1207 {
1208 InSequence dummy;
1209
1210 EXPECT_CALL(a, DoA(1));
1211 EXPECT_CALL(a, DoA(2));
1212 }
1213 EXPECT_CALL(a, DoA(3));
1214
1215 EXPECT_NONFATAL_FAILURE({ // NOLINT
1216 a.DoA(2);
1217 }, "Unexpected mock function call");
1218
1219 a.DoA(3);
1220 a.DoA(1);
1221 a.DoA(2);
1222}
1223
1224// Tests that any order is allowed when no sequence is used.
1225TEST(SequenceTest, AnyOrderIsOkByDefault) {
1226 {
1227 MockA a;
1228 MockB b;
1229
1230 EXPECT_CALL(a, DoA(1));
1231 EXPECT_CALL(b, DoB())
1232 .Times(AnyNumber());
1233
1234 a.DoA(1);
1235 b.DoB();
1236 }
1237
1238 { // NOLINT
1239 MockA a;
1240 MockB b;
1241
1242 EXPECT_CALL(a, DoA(1));
1243 EXPECT_CALL(b, DoB())
1244 .Times(AnyNumber());
1245
1246 b.DoB();
1247 a.DoA(1);
1248 }
1249}
1250
shiqiane35fdd92008-12-10 05:08:54 +00001251// Tests that the calls must be in strict order when a complete order
1252// is specified.
1253TEST(SequenceTest, CallsMustBeInStrictOrderWhenSaidSo) {
1254 MockA a;
1255 Sequence s;
1256
1257 EXPECT_CALL(a, ReturnResult(1))
1258 .InSequence(s)
1259 .WillOnce(Return(Result()));
1260
1261 EXPECT_CALL(a, ReturnResult(2))
1262 .InSequence(s)
1263 .WillOnce(Return(Result()));
1264
1265 EXPECT_CALL(a, ReturnResult(3))
1266 .InSequence(s)
1267 .WillOnce(Return(Result()));
1268
zhanyong.wan04d6ed82009-09-11 07:01:08 +00001269 EXPECT_DEATH_IF_SUPPORTED({
shiqiane35fdd92008-12-10 05:08:54 +00001270 a.ReturnResult(1);
1271 a.ReturnResult(3);
1272 a.ReturnResult(2);
1273 }, "");
1274
zhanyong.wan04d6ed82009-09-11 07:01:08 +00001275 EXPECT_DEATH_IF_SUPPORTED({
shiqiane35fdd92008-12-10 05:08:54 +00001276 a.ReturnResult(2);
1277 a.ReturnResult(1);
1278 a.ReturnResult(3);
1279 }, "");
1280
1281 a.ReturnResult(1);
1282 a.ReturnResult(2);
1283 a.ReturnResult(3);
1284}
1285
1286// Tests specifying a DAG using multiple sequences.
1287TEST(SequenceTest, CallsMustConformToSpecifiedDag) {
1288 MockA a;
1289 MockB b;
1290 Sequence x, y;
1291
1292 EXPECT_CALL(a, ReturnResult(1))
1293 .InSequence(x)
1294 .WillOnce(Return(Result()));
1295
1296 EXPECT_CALL(b, DoB())
1297 .Times(2)
1298 .InSequence(y);
1299
1300 EXPECT_CALL(a, ReturnResult(2))
1301 .InSequence(x, y)
1302 .WillRepeatedly(Return(Result()));
1303
1304 EXPECT_CALL(a, ReturnResult(3))
1305 .InSequence(x)
1306 .WillOnce(Return(Result()));
1307
zhanyong.wan04d6ed82009-09-11 07:01:08 +00001308 EXPECT_DEATH_IF_SUPPORTED({
shiqiane35fdd92008-12-10 05:08:54 +00001309 a.ReturnResult(1);
1310 b.DoB();
1311 a.ReturnResult(2);
1312 }, "");
1313
zhanyong.wan04d6ed82009-09-11 07:01:08 +00001314 EXPECT_DEATH_IF_SUPPORTED({
shiqiane35fdd92008-12-10 05:08:54 +00001315 a.ReturnResult(2);
1316 }, "");
1317
zhanyong.wan04d6ed82009-09-11 07:01:08 +00001318 EXPECT_DEATH_IF_SUPPORTED({
shiqiane35fdd92008-12-10 05:08:54 +00001319 a.ReturnResult(3);
1320 }, "");
1321
zhanyong.wan04d6ed82009-09-11 07:01:08 +00001322 EXPECT_DEATH_IF_SUPPORTED({
shiqiane35fdd92008-12-10 05:08:54 +00001323 a.ReturnResult(1);
1324 b.DoB();
1325 b.DoB();
1326 a.ReturnResult(3);
1327 a.ReturnResult(2);
1328 }, "");
1329
1330 b.DoB();
1331 a.ReturnResult(1);
1332 b.DoB();
1333 a.ReturnResult(3);
1334}
1335
shiqiane35fdd92008-12-10 05:08:54 +00001336TEST(SequenceTest, Retirement) {
1337 MockA a;
1338 Sequence s;
1339
1340 EXPECT_CALL(a, DoA(1))
1341 .InSequence(s);
1342 EXPECT_CALL(a, DoA(_))
1343 .InSequence(s)
1344 .RetiresOnSaturation();
1345 EXPECT_CALL(a, DoA(1))
1346 .InSequence(s);
1347
1348 a.DoA(1);
1349 a.DoA(2);
1350 a.DoA(1);
1351}
1352
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001353// Tests Expectation.
1354
1355TEST(ExpectationTest, ConstrutorsWork) {
1356 MockA a;
1357 Expectation e1; // Default ctor.
zhanyong.waned6c9272011-02-23 19:39:27 +00001358
1359 // Ctor from various forms of EXPECT_CALL.
1360 Expectation e2 = EXPECT_CALL(a, DoA(2));
1361 Expectation e3 = EXPECT_CALL(a, DoA(3)).With(_);
1362 {
1363 Sequence s;
1364 Expectation e4 = EXPECT_CALL(a, DoA(4)).Times(1);
1365 Expectation e5 = EXPECT_CALL(a, DoA(5)).InSequence(s);
1366 }
1367 Expectation e6 = EXPECT_CALL(a, DoA(6)).After(e2);
1368 Expectation e7 = EXPECT_CALL(a, DoA(7)).WillOnce(Return());
1369 Expectation e8 = EXPECT_CALL(a, DoA(8)).WillRepeatedly(Return());
1370 Expectation e9 = EXPECT_CALL(a, DoA(9)).RetiresOnSaturation();
1371
1372 Expectation e10 = e2; // Copy ctor.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001373
1374 EXPECT_THAT(e1, Ne(e2));
zhanyong.waned6c9272011-02-23 19:39:27 +00001375 EXPECT_THAT(e2, Eq(e10));
1376
1377 a.DoA(2);
1378 a.DoA(3);
1379 a.DoA(4);
1380 a.DoA(5);
1381 a.DoA(6);
1382 a.DoA(7);
1383 a.DoA(8);
1384 a.DoA(9);
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001385}
1386
1387TEST(ExpectationTest, AssignmentWorks) {
1388 MockA a;
1389 Expectation e1;
1390 Expectation e2 = EXPECT_CALL(a, DoA(1));
1391
1392 EXPECT_THAT(e1, Ne(e2));
1393
1394 e1 = e2;
1395 EXPECT_THAT(e1, Eq(e2));
1396
1397 a.DoA(1);
1398}
1399
1400// Tests ExpectationSet.
1401
1402TEST(ExpectationSetTest, MemberTypesAreCorrect) {
1403 ::testing::StaticAssertTypeEq<Expectation, ExpectationSet::value_type>();
1404}
1405
1406TEST(ExpectationSetTest, ConstructorsWork) {
1407 MockA a;
1408
1409 Expectation e1;
1410 const Expectation e2;
1411 ExpectationSet es1; // Default ctor.
1412 ExpectationSet es2 = EXPECT_CALL(a, DoA(1)); // Ctor from EXPECT_CALL.
1413 ExpectationSet es3 = e1; // Ctor from Expectation.
1414 ExpectationSet es4(e1); // Ctor from Expectation; alternative syntax.
1415 ExpectationSet es5 = e2; // Ctor from const Expectation.
1416 ExpectationSet es6(e2); // Ctor from const Expectation; alternative syntax.
1417 ExpectationSet es7 = es2; // Copy ctor.
1418
1419 EXPECT_EQ(0, es1.size());
1420 EXPECT_EQ(1, es2.size());
1421 EXPECT_EQ(1, es3.size());
1422 EXPECT_EQ(1, es4.size());
1423 EXPECT_EQ(1, es5.size());
1424 EXPECT_EQ(1, es6.size());
1425 EXPECT_EQ(1, es7.size());
1426
1427 EXPECT_THAT(es3, Ne(es2));
1428 EXPECT_THAT(es4, Eq(es3));
1429 EXPECT_THAT(es5, Eq(es4));
1430 EXPECT_THAT(es6, Eq(es5));
1431 EXPECT_THAT(es7, Eq(es2));
1432 a.DoA(1);
1433}
1434
1435TEST(ExpectationSetTest, AssignmentWorks) {
1436 ExpectationSet es1;
1437 ExpectationSet es2 = Expectation();
1438
1439 es1 = es2;
1440 EXPECT_EQ(1, es1.size());
1441 EXPECT_THAT(*(es1.begin()), Eq(Expectation()));
1442 EXPECT_THAT(es1, Eq(es2));
1443}
1444
1445TEST(ExpectationSetTest, InsertionWorks) {
1446 ExpectationSet es1;
1447 Expectation e1;
1448 es1 += e1;
1449 EXPECT_EQ(1, es1.size());
1450 EXPECT_THAT(*(es1.begin()), Eq(e1));
1451
1452 MockA a;
1453 Expectation e2 = EXPECT_CALL(a, DoA(1));
1454 es1 += e2;
1455 EXPECT_EQ(2, es1.size());
1456
1457 ExpectationSet::const_iterator it1 = es1.begin();
1458 ExpectationSet::const_iterator it2 = it1;
1459 ++it2;
1460 EXPECT_TRUE(*it1 == e1 || *it2 == e1); // e1 must be in the set.
1461 EXPECT_TRUE(*it1 == e2 || *it2 == e2); // e2 must be in the set too.
1462 a.DoA(1);
1463}
1464
1465TEST(ExpectationSetTest, SizeWorks) {
1466 ExpectationSet es;
1467 EXPECT_EQ(0, es.size());
1468
1469 es += Expectation();
1470 EXPECT_EQ(1, es.size());
1471
1472 MockA a;
1473 es += EXPECT_CALL(a, DoA(1));
1474 EXPECT_EQ(2, es.size());
1475
1476 a.DoA(1);
1477}
1478
1479TEST(ExpectationSetTest, IsEnumerable) {
1480 ExpectationSet es;
1481 EXPECT_THAT(es.begin(), Eq(es.end()));
1482
1483 es += Expectation();
1484 ExpectationSet::const_iterator it = es.begin();
1485 EXPECT_THAT(it, Ne(es.end()));
1486 EXPECT_THAT(*it, Eq(Expectation()));
1487 ++it;
1488 EXPECT_THAT(it, Eq(es.end()));
1489}
1490
1491// Tests the .After() clause.
1492
1493TEST(AfterTest, SucceedsWhenPartialOrderIsSatisfied) {
1494 MockA a;
1495 ExpectationSet es;
1496 es += EXPECT_CALL(a, DoA(1));
1497 es += EXPECT_CALL(a, DoA(2));
1498 EXPECT_CALL(a, DoA(3))
1499 .After(es);
1500
1501 a.DoA(1);
1502 a.DoA(2);
1503 a.DoA(3);
1504}
1505
1506TEST(AfterTest, SucceedsWhenTotalOrderIsSatisfied) {
1507 MockA a;
1508 MockB b;
1509 // The following also verifies that const Expectation objects work
1510 // too. Do not remove the const modifiers.
1511 const Expectation e1 = EXPECT_CALL(a, DoA(1));
1512 const Expectation e2 = EXPECT_CALL(b, DoB())
1513 .Times(2)
1514 .After(e1);
1515 EXPECT_CALL(a, DoA(2)).After(e2);
1516
1517 a.DoA(1);
1518 b.DoB();
1519 b.DoB();
1520 a.DoA(2);
1521}
1522
1523// Calls must be in strict order when specified so.
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00001524TEST(AfterDeathTest, CallsMustBeInStrictOrderWhenSpecifiedSo) {
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001525 MockA a;
1526 MockB b;
1527 Expectation e1 = EXPECT_CALL(a, DoA(1));
1528 Expectation e2 = EXPECT_CALL(b, DoB())
1529 .Times(2)
1530 .After(e1);
1531 EXPECT_CALL(a, ReturnResult(2))
1532 .After(e2)
1533 .WillOnce(Return(Result()));
1534
1535 a.DoA(1);
1536 // If a call to ReturnResult() violates the specified order, no
1537 // matching expectation will be found, and thus the default action
1538 // will be done. Since the return type of ReturnResult() is not a
1539 // built-in type, gmock won't know what to return and will thus
1540 // abort the program. Therefore a death test can tell us whether
1541 // gmock catches the order violation correctly.
1542 //
1543 // gtest and gmock print messages to stdout, which isn't captured by
1544 // death tests. Therefore we have to match with an empty regular
1545 // expression in all the EXPECT_DEATH()s.
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00001546 EXPECT_DEATH_IF_SUPPORTED(a.ReturnResult(2), "");
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001547
1548 b.DoB();
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00001549 EXPECT_DEATH_IF_SUPPORTED(a.ReturnResult(2), "");
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001550
1551 b.DoB();
1552 a.ReturnResult(2);
1553}
1554
1555// Calls must satisfy the partial order when specified so.
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00001556TEST(AfterDeathTest, CallsMustSatisfyPartialOrderWhenSpecifiedSo) {
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001557 MockA a;
1558 Expectation e = EXPECT_CALL(a, DoA(1));
1559 const ExpectationSet es = EXPECT_CALL(a, DoA(2));
1560 EXPECT_CALL(a, ReturnResult(3))
1561 .After(e, es)
1562 .WillOnce(Return(Result()));
1563
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00001564 EXPECT_DEATH_IF_SUPPORTED(a.ReturnResult(3), "");
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001565
1566 a.DoA(2);
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00001567 EXPECT_DEATH_IF_SUPPORTED(a.ReturnResult(3), "");
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001568
1569 a.DoA(1);
1570 a.ReturnResult(3);
1571}
1572
1573// .After() can be combined with .InSequence().
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00001574TEST(AfterDeathTest, CanBeUsedWithInSequence) {
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001575 MockA a;
1576 Sequence s;
1577 Expectation e = EXPECT_CALL(a, DoA(1));
1578 EXPECT_CALL(a, DoA(2)).InSequence(s);
1579 EXPECT_CALL(a, ReturnResult(3))
1580 .InSequence(s).After(e)
1581 .WillOnce(Return(Result()));
1582
1583 a.DoA(1);
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00001584 EXPECT_DEATH_IF_SUPPORTED(a.ReturnResult(3), "");
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001585
1586 a.DoA(2);
1587 a.ReturnResult(3);
1588}
1589
1590// .After() can be called multiple times.
1591TEST(AfterTest, CanBeCalledManyTimes) {
1592 MockA a;
1593 Expectation e1 = EXPECT_CALL(a, DoA(1));
1594 Expectation e2 = EXPECT_CALL(a, DoA(2));
1595 Expectation e3 = EXPECT_CALL(a, DoA(3));
1596 EXPECT_CALL(a, DoA(4))
1597 .After(e1)
1598 .After(e2)
1599 .After(e3);
1600
1601 a.DoA(3);
1602 a.DoA(1);
1603 a.DoA(2);
1604 a.DoA(4);
1605}
1606
1607// .After() accepts up to 5 arguments.
1608TEST(AfterTest, AcceptsUpToFiveArguments) {
1609 MockA a;
1610 Expectation e1 = EXPECT_CALL(a, DoA(1));
1611 Expectation e2 = EXPECT_CALL(a, DoA(2));
1612 Expectation e3 = EXPECT_CALL(a, DoA(3));
1613 ExpectationSet es1 = EXPECT_CALL(a, DoA(4));
1614 ExpectationSet es2 = EXPECT_CALL(a, DoA(5));
1615 EXPECT_CALL(a, DoA(6))
1616 .After(e1, e2, e3, es1, es2);
1617
1618 a.DoA(5);
1619 a.DoA(2);
1620 a.DoA(4);
1621 a.DoA(1);
1622 a.DoA(3);
1623 a.DoA(6);
1624}
1625
1626// .After() allows input to contain duplicated Expectations.
1627TEST(AfterTest, AcceptsDuplicatedInput) {
1628 MockA a;
1629 Expectation e1 = EXPECT_CALL(a, DoA(1));
1630 Expectation e2 = EXPECT_CALL(a, DoA(2));
1631 ExpectationSet es;
1632 es += e1;
1633 es += e2;
1634 EXPECT_CALL(a, ReturnResult(3))
1635 .After(e1, e2, es, e1)
1636 .WillOnce(Return(Result()));
1637
1638 a.DoA(1);
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00001639 EXPECT_DEATH_IF_SUPPORTED(a.ReturnResult(3), "");
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001640
1641 a.DoA(2);
1642 a.ReturnResult(3);
1643}
1644
1645// An Expectation added to an ExpectationSet after it has been used in
1646// an .After() has no effect.
1647TEST(AfterTest, ChangesToExpectationSetHaveNoEffectAfterwards) {
1648 MockA a;
1649 ExpectationSet es1 = EXPECT_CALL(a, DoA(1));
1650 Expectation e2 = EXPECT_CALL(a, DoA(2));
1651 EXPECT_CALL(a, DoA(3))
1652 .After(es1);
1653 es1 += e2;
1654
1655 a.DoA(1);
1656 a.DoA(3);
1657 a.DoA(2);
1658}
1659
shiqiane35fdd92008-12-10 05:08:54 +00001660// Tests that Google Mock correctly handles calls to mock functions
1661// after a mock object owning one of their pre-requisites has died.
1662
1663// Tests that calls that satisfy the original spec are successful.
1664TEST(DeletingMockEarlyTest, Success1) {
1665 MockB* const b1 = new MockB;
1666 MockA* const a = new MockA;
1667 MockB* const b2 = new MockB;
1668
1669 {
1670 InSequence dummy;
1671 EXPECT_CALL(*b1, DoB(_))
1672 .WillOnce(Return(1));
1673 EXPECT_CALL(*a, Binary(_, _))
1674 .Times(AnyNumber())
1675 .WillRepeatedly(Return(true));
1676 EXPECT_CALL(*b2, DoB(_))
1677 .Times(AnyNumber())
1678 .WillRepeatedly(Return(2));
1679 }
1680
1681 EXPECT_EQ(1, b1->DoB(1));
1682 delete b1;
1683 // a's pre-requisite has died.
1684 EXPECT_TRUE(a->Binary(0, 1));
1685 delete b2;
1686 // a's successor has died.
1687 EXPECT_TRUE(a->Binary(1, 2));
1688 delete a;
1689}
1690
1691// Tests that calls that satisfy the original spec are successful.
1692TEST(DeletingMockEarlyTest, Success2) {
1693 MockB* const b1 = new MockB;
1694 MockA* const a = new MockA;
1695 MockB* const b2 = new MockB;
1696
1697 {
1698 InSequence dummy;
1699 EXPECT_CALL(*b1, DoB(_))
1700 .WillOnce(Return(1));
1701 EXPECT_CALL(*a, Binary(_, _))
1702 .Times(AnyNumber());
1703 EXPECT_CALL(*b2, DoB(_))
1704 .Times(AnyNumber())
1705 .WillRepeatedly(Return(2));
1706 }
1707
1708 delete a; // a is trivially satisfied.
1709 EXPECT_EQ(1, b1->DoB(1));
1710 EXPECT_EQ(2, b2->DoB(2));
1711 delete b1;
1712 delete b2;
1713}
1714
zhanyong.wan6f147692009-03-03 06:44:08 +00001715// Tests that it's OK to delete a mock object itself in its action.
1716
zhanyong.wan32de5f52009-12-23 00:13:23 +00001717// Suppresses warning on unreferenced formal parameter in MSVC with
1718// -W4.
1719#ifdef _MSC_VER
1720#pragma warning(push)
1721#pragma warning(disable:4100)
1722#endif
1723
zhanyong.wan6f147692009-03-03 06:44:08 +00001724ACTION_P(Delete, ptr) { delete ptr; }
1725
zhanyong.wan32de5f52009-12-23 00:13:23 +00001726#ifdef _MSC_VER
1727#pragma warning(pop)
1728#endif
1729
zhanyong.wan6f147692009-03-03 06:44:08 +00001730TEST(DeletingMockEarlyTest, CanDeleteSelfInActionReturningVoid) {
1731 MockA* const a = new MockA;
1732 EXPECT_CALL(*a, DoA(_)).WillOnce(Delete(a));
1733 a->DoA(42); // This will cause a to be deleted.
1734}
1735
1736TEST(DeletingMockEarlyTest, CanDeleteSelfInActionReturningValue) {
1737 MockA* const a = new MockA;
1738 EXPECT_CALL(*a, ReturnResult(_))
1739 .WillOnce(DoAll(Delete(a), Return(Result())));
1740 a->ReturnResult(42); // This will cause a to be deleted.
1741}
1742
1743// Tests that calls that violate the original spec yield failures.
shiqiane35fdd92008-12-10 05:08:54 +00001744TEST(DeletingMockEarlyTest, Failure1) {
1745 MockB* const b1 = new MockB;
1746 MockA* const a = new MockA;
1747 MockB* const b2 = new MockB;
1748
1749 {
1750 InSequence dummy;
1751 EXPECT_CALL(*b1, DoB(_))
1752 .WillOnce(Return(1));
1753 EXPECT_CALL(*a, Binary(_, _))
1754 .Times(AnyNumber());
1755 EXPECT_CALL(*b2, DoB(_))
1756 .Times(AnyNumber())
1757 .WillRepeatedly(Return(2));
1758 }
1759
1760 delete a; // a is trivially satisfied.
1761 EXPECT_NONFATAL_FAILURE({
1762 b2->DoB(2);
1763 }, "Unexpected mock function call");
1764 EXPECT_EQ(1, b1->DoB(1));
1765 delete b1;
1766 delete b2;
1767}
1768
zhanyong.wan6f147692009-03-03 06:44:08 +00001769// Tests that calls that violate the original spec yield failures.
shiqiane35fdd92008-12-10 05:08:54 +00001770TEST(DeletingMockEarlyTest, Failure2) {
1771 MockB* const b1 = new MockB;
1772 MockA* const a = new MockA;
1773 MockB* const b2 = new MockB;
1774
1775 {
1776 InSequence dummy;
1777 EXPECT_CALL(*b1, DoB(_));
1778 EXPECT_CALL(*a, Binary(_, _))
1779 .Times(AnyNumber());
1780 EXPECT_CALL(*b2, DoB(_))
1781 .Times(AnyNumber());
1782 }
1783
1784 EXPECT_NONFATAL_FAILURE(delete b1,
1785 "Actual: never called");
1786 EXPECT_NONFATAL_FAILURE(a->Binary(0, 1),
1787 "Unexpected mock function call");
1788 EXPECT_NONFATAL_FAILURE(b2->DoB(1),
1789 "Unexpected mock function call");
1790 delete a;
1791 delete b2;
1792}
1793
1794class EvenNumberCardinality : public CardinalityInterface {
1795 public:
1796 // Returns true iff call_count calls will satisfy this cardinality.
1797 virtual bool IsSatisfiedByCallCount(int call_count) const {
1798 return call_count % 2 == 0;
1799 }
1800
1801 // Returns true iff call_count calls will saturate this cardinality.
zhanyong.wan32de5f52009-12-23 00:13:23 +00001802 virtual bool IsSaturatedByCallCount(int /* call_count */) const {
1803 return false;
1804 }
shiqiane35fdd92008-12-10 05:08:54 +00001805
1806 // Describes self to an ostream.
1807 virtual void DescribeTo(::std::ostream* os) const {
1808 *os << "called even number of times";
1809 }
1810};
1811
1812Cardinality EvenNumber() {
1813 return Cardinality(new EvenNumberCardinality);
1814}
1815
1816TEST(ExpectationBaseTest,
1817 AllPrerequisitesAreSatisfiedWorksForNonMonotonicCardinality) {
1818 MockA* a = new MockA;
1819 Sequence s;
1820
1821 EXPECT_CALL(*a, DoA(1))
1822 .Times(EvenNumber())
1823 .InSequence(s);
1824 EXPECT_CALL(*a, DoA(2))
1825 .Times(AnyNumber())
1826 .InSequence(s);
1827 EXPECT_CALL(*a, DoA(3))
1828 .Times(AnyNumber());
1829
1830 a->DoA(3);
1831 a->DoA(1);
1832 EXPECT_NONFATAL_FAILURE(a->DoA(2), "Unexpected mock function call");
1833 EXPECT_NONFATAL_FAILURE(delete a, "to be called even number of times");
1834}
1835
1836// The following tests verify the message generated when a mock
1837// function is called.
1838
1839struct Printable {
1840};
1841
1842inline void operator<<(::std::ostream& os, const Printable&) {
1843 os << "Printable";
1844}
1845
1846struct Unprintable {
1847 Unprintable() : value(0) {}
1848 int value;
1849};
1850
1851class MockC {
1852 public:
zhanyong.wan32de5f52009-12-23 00:13:23 +00001853 MockC() {}
1854
shiqiane35fdd92008-12-10 05:08:54 +00001855 MOCK_METHOD6(VoidMethod, void(bool cond, int n, string s, void* p,
1856 const Printable& x, Unprintable y));
1857 MOCK_METHOD0(NonVoidMethod, int()); // NOLINT
zhanyong.wan32de5f52009-12-23 00:13:23 +00001858
1859 private:
1860 GTEST_DISALLOW_COPY_AND_ASSIGN_(MockC);
shiqiane35fdd92008-12-10 05:08:54 +00001861};
1862
vladlosev76c1c612010-05-05 19:47:46 +00001863class VerboseFlagPreservingFixture : public testing::Test {
1864 protected:
1865 // The code needs to work when both ::string and ::std::string are defined
1866 // and the flag is implemented as a testing::internal::String. In this
1867 // case, without the call to c_str(), the compiler will complain that it
1868 // cannot figure out what overload of string constructor to use.
1869 // TODO(vladl@google.com): Use internal::string instead of String for
1870 // string flags in Google Test.
1871 VerboseFlagPreservingFixture()
1872 : saved_verbose_flag_(GMOCK_FLAG(verbose).c_str()) {}
1873
1874 ~VerboseFlagPreservingFixture() { GMOCK_FLAG(verbose) = saved_verbose_flag_; }
1875
1876 private:
1877 const string saved_verbose_flag_;
1878
1879 GTEST_DISALLOW_COPY_AND_ASSIGN_(VerboseFlagPreservingFixture);
1880};
1881
zhanyong.wan2516f602010-08-31 18:28:02 +00001882#if GTEST_HAS_STREAM_REDIRECTION
shiqiane35fdd92008-12-10 05:08:54 +00001883
1884// Tests that an uninteresting mock function call generates a warning
1885// containing the stack trace.
1886TEST(FunctionCallMessageTest, UninterestingCallGeneratesFyiWithStackTrace) {
1887 MockC c;
zhanyong.wan470df422010-02-02 22:34:58 +00001888 CaptureStdout();
shiqiane35fdd92008-12-10 05:08:54 +00001889 c.VoidMethod(false, 5, "Hi", NULL, Printable(), Unprintable());
zhanyong.wan470df422010-02-02 22:34:58 +00001890 const String output = GetCapturedStdout();
shiqiane35fdd92008-12-10 05:08:54 +00001891 EXPECT_PRED_FORMAT2(IsSubstring, "GMOCK WARNING", output);
1892 EXPECT_PRED_FORMAT2(IsSubstring, "Stack trace:", output);
1893#ifndef NDEBUG
1894 // We check the stack trace content in dbg-mode only, as opt-mode
1895 // may inline the call we are interested in seeing.
1896
1897 // Verifies that a void mock function's name appears in the stack
1898 // trace.
zhanyong.wan470df422010-02-02 22:34:58 +00001899 EXPECT_PRED_FORMAT2(IsSubstring, "VoidMethod(", output);
shiqiane35fdd92008-12-10 05:08:54 +00001900
1901 // Verifies that a non-void mock function's name appears in the
1902 // stack trace.
zhanyong.wan470df422010-02-02 22:34:58 +00001903 CaptureStdout();
shiqiane35fdd92008-12-10 05:08:54 +00001904 c.NonVoidMethod();
zhanyong.wan470df422010-02-02 22:34:58 +00001905 const String output2 = GetCapturedStdout();
1906 EXPECT_PRED_FORMAT2(IsSubstring, "NonVoidMethod(", output2);
shiqiane35fdd92008-12-10 05:08:54 +00001907#endif // NDEBUG
1908}
1909
1910// Tests that an uninteresting mock function call causes the function
1911// arguments and return value to be printed.
1912TEST(FunctionCallMessageTest, UninterestingCallPrintsArgumentsAndReturnValue) {
1913 // A non-void mock function.
1914 MockB b;
zhanyong.wan470df422010-02-02 22:34:58 +00001915 CaptureStdout();
shiqiane35fdd92008-12-10 05:08:54 +00001916 b.DoB();
zhanyong.wan470df422010-02-02 22:34:58 +00001917 const String output1 = GetCapturedStdout();
shiqiane35fdd92008-12-10 05:08:54 +00001918 EXPECT_PRED_FORMAT2(
1919 IsSubstring,
1920 "Uninteresting mock function call - returning default value.\n"
1921 " Function call: DoB()\n"
zhanyong.wan470df422010-02-02 22:34:58 +00001922 " Returns: 0\n", output1.c_str());
shiqiane35fdd92008-12-10 05:08:54 +00001923 // Makes sure the return value is printed.
1924
1925 // A void mock function.
1926 MockC c;
zhanyong.wan470df422010-02-02 22:34:58 +00001927 CaptureStdout();
shiqiane35fdd92008-12-10 05:08:54 +00001928 c.VoidMethod(false, 5, "Hi", NULL, Printable(), Unprintable());
zhanyong.wan470df422010-02-02 22:34:58 +00001929 const String output2 = GetCapturedStdout();
1930 EXPECT_THAT(output2.c_str(),
1931 ContainsRegex(
1932 "Uninteresting mock function call - returning directly\\.\n"
1933 " Function call: VoidMethod"
1934 "\\(false, 5, \"Hi\", NULL, @.+ "
zhanyong.wanc6333dc2010-08-09 18:20:45 +00001935 "Printable, 4-byte object <00-00 00-00>\\)"));
shiqiane35fdd92008-12-10 05:08:54 +00001936 // A void function has no return value to print.
1937}
1938
1939// Tests how the --gmock_verbose flag affects Google Mock's output.
1940
vladlosev76c1c612010-05-05 19:47:46 +00001941class GMockVerboseFlagTest : public VerboseFlagPreservingFixture {
shiqiane35fdd92008-12-10 05:08:54 +00001942 public:
1943 // Verifies that the given Google Mock output is correct. (When
1944 // should_print is true, the output should match the given regex and
1945 // contain the given function name in the stack trace. When it's
1946 // false, the output should be empty.)
zhanyong.wan470df422010-02-02 22:34:58 +00001947 void VerifyOutput(const String& output, bool should_print,
1948 const string& expected_substring,
shiqiane35fdd92008-12-10 05:08:54 +00001949 const string& function_name) {
1950 if (should_print) {
zhanyong.wan470df422010-02-02 22:34:58 +00001951 EXPECT_THAT(output.c_str(), HasSubstr(expected_substring));
shiqiane35fdd92008-12-10 05:08:54 +00001952#ifndef NDEBUG
1953 // We check the stack trace content in dbg-mode only, as opt-mode
1954 // may inline the call we are interested in seeing.
zhanyong.wan470df422010-02-02 22:34:58 +00001955 EXPECT_THAT(output.c_str(), HasSubstr(function_name));
1956#else
1957 // Suppresses 'unused function parameter' warnings.
1958 static_cast<void>(function_name);
shiqiane35fdd92008-12-10 05:08:54 +00001959#endif // NDEBUG
1960 } else {
zhanyong.wan470df422010-02-02 22:34:58 +00001961 EXPECT_STREQ("", output.c_str());
shiqiane35fdd92008-12-10 05:08:54 +00001962 }
1963 }
1964
1965 // Tests how the flag affects expected calls.
1966 void TestExpectedCall(bool should_print) {
1967 MockA a;
1968 EXPECT_CALL(a, DoA(5));
1969 EXPECT_CALL(a, Binary(_, 1))
1970 .WillOnce(Return(true));
1971
1972 // A void-returning function.
zhanyong.wan470df422010-02-02 22:34:58 +00001973 CaptureStdout();
shiqiane35fdd92008-12-10 05:08:54 +00001974 a.DoA(5);
1975 VerifyOutput(
zhanyong.wan470df422010-02-02 22:34:58 +00001976 GetCapturedStdout(),
shiqiane35fdd92008-12-10 05:08:54 +00001977 should_print,
zhanyong.wan470df422010-02-02 22:34:58 +00001978 "Mock function call matches EXPECT_CALL(a, DoA(5))...\n"
1979 " Function call: DoA(5)\n"
1980 "Stack trace:\n",
1981 "DoA");
shiqiane35fdd92008-12-10 05:08:54 +00001982
1983 // A non-void-returning function.
zhanyong.wan470df422010-02-02 22:34:58 +00001984 CaptureStdout();
shiqiane35fdd92008-12-10 05:08:54 +00001985 a.Binary(2, 1);
1986 VerifyOutput(
zhanyong.wan470df422010-02-02 22:34:58 +00001987 GetCapturedStdout(),
shiqiane35fdd92008-12-10 05:08:54 +00001988 should_print,
zhanyong.wan470df422010-02-02 22:34:58 +00001989 "Mock function call matches EXPECT_CALL(a, Binary(_, 1))...\n"
1990 " Function call: Binary(2, 1)\n"
shiqiane35fdd92008-12-10 05:08:54 +00001991 " Returns: true\n"
zhanyong.wan470df422010-02-02 22:34:58 +00001992 "Stack trace:\n",
1993 "Binary");
shiqiane35fdd92008-12-10 05:08:54 +00001994 }
1995
1996 // Tests how the flag affects uninteresting calls.
1997 void TestUninterestingCall(bool should_print) {
1998 MockA a;
1999
2000 // A void-returning function.
zhanyong.wan470df422010-02-02 22:34:58 +00002001 CaptureStdout();
shiqiane35fdd92008-12-10 05:08:54 +00002002 a.DoA(5);
2003 VerifyOutput(
zhanyong.wan470df422010-02-02 22:34:58 +00002004 GetCapturedStdout(),
shiqiane35fdd92008-12-10 05:08:54 +00002005 should_print,
2006 "\nGMOCK WARNING:\n"
zhanyong.wan470df422010-02-02 22:34:58 +00002007 "Uninteresting mock function call - returning directly.\n"
2008 " Function call: DoA(5)\n"
2009 "Stack trace:\n",
2010 "DoA");
shiqiane35fdd92008-12-10 05:08:54 +00002011
2012 // A non-void-returning function.
zhanyong.wan470df422010-02-02 22:34:58 +00002013 CaptureStdout();
shiqiane35fdd92008-12-10 05:08:54 +00002014 a.Binary(2, 1);
2015 VerifyOutput(
zhanyong.wan470df422010-02-02 22:34:58 +00002016 GetCapturedStdout(),
shiqiane35fdd92008-12-10 05:08:54 +00002017 should_print,
2018 "\nGMOCK WARNING:\n"
zhanyong.wan470df422010-02-02 22:34:58 +00002019 "Uninteresting mock function call - returning default value.\n"
2020 " Function call: Binary(2, 1)\n"
shiqiane35fdd92008-12-10 05:08:54 +00002021 " Returns: false\n"
zhanyong.wan470df422010-02-02 22:34:58 +00002022 "Stack trace:\n",
2023 "Binary");
shiqiane35fdd92008-12-10 05:08:54 +00002024 }
2025};
2026
2027// Tests that --gmock_verbose=info causes both expected and
2028// uninteresting calls to be reported.
2029TEST_F(GMockVerboseFlagTest, Info) {
2030 GMOCK_FLAG(verbose) = kInfoVerbosity;
2031 TestExpectedCall(true);
2032 TestUninterestingCall(true);
2033}
2034
2035// Tests that --gmock_verbose=warning causes uninteresting calls to be
2036// reported.
2037TEST_F(GMockVerboseFlagTest, Warning) {
2038 GMOCK_FLAG(verbose) = kWarningVerbosity;
2039 TestExpectedCall(false);
2040 TestUninterestingCall(true);
2041}
2042
2043// Tests that --gmock_verbose=warning causes neither expected nor
2044// uninteresting calls to be reported.
2045TEST_F(GMockVerboseFlagTest, Error) {
2046 GMOCK_FLAG(verbose) = kErrorVerbosity;
2047 TestExpectedCall(false);
2048 TestUninterestingCall(false);
2049}
2050
2051// Tests that --gmock_verbose=SOME_INVALID_VALUE has the same effect
2052// as --gmock_verbose=warning.
2053TEST_F(GMockVerboseFlagTest, InvalidFlagIsTreatedAsWarning) {
2054 GMOCK_FLAG(verbose) = "invalid"; // Treated as "warning".
2055 TestExpectedCall(false);
2056 TestUninterestingCall(true);
2057}
2058
zhanyong.wan2516f602010-08-31 18:28:02 +00002059#endif // GTEST_HAS_STREAM_REDIRECTION
shiqiane35fdd92008-12-10 05:08:54 +00002060
zhanyong.wan9413f2f2009-05-29 19:50:06 +00002061// A helper class that generates a failure when printed. We use it to
2062// ensure that Google Mock doesn't print a value (even to an internal
2063// buffer) when it is not supposed to do so.
2064class PrintMeNot {};
2065
2066void PrintTo(PrintMeNot /* dummy */, ::std::ostream* /* os */) {
2067 ADD_FAILURE() << "Google Mock is printing a value that shouldn't be "
2068 << "printed even to an internal buffer.";
2069}
2070
2071class LogTestHelper {
2072 public:
zhanyong.wan32de5f52009-12-23 00:13:23 +00002073 LogTestHelper() {}
2074
zhanyong.wan9413f2f2009-05-29 19:50:06 +00002075 MOCK_METHOD1(Foo, PrintMeNot(PrintMeNot));
zhanyong.wan32de5f52009-12-23 00:13:23 +00002076
2077 private:
2078 GTEST_DISALLOW_COPY_AND_ASSIGN_(LogTestHelper);
zhanyong.wan9413f2f2009-05-29 19:50:06 +00002079};
2080
vladlosev76c1c612010-05-05 19:47:46 +00002081class GMockLogTest : public VerboseFlagPreservingFixture {
zhanyong.wan9413f2f2009-05-29 19:50:06 +00002082 protected:
zhanyong.wan9413f2f2009-05-29 19:50:06 +00002083 LogTestHelper helper_;
zhanyong.wan9413f2f2009-05-29 19:50:06 +00002084};
2085
2086TEST_F(GMockLogTest, DoesNotPrintGoodCallInternallyIfVerbosityIsWarning) {
2087 GMOCK_FLAG(verbose) = kWarningVerbosity;
2088 EXPECT_CALL(helper_, Foo(_))
2089 .WillOnce(Return(PrintMeNot()));
2090 helper_.Foo(PrintMeNot()); // This is an expected call.
2091}
2092
2093TEST_F(GMockLogTest, DoesNotPrintGoodCallInternallyIfVerbosityIsError) {
2094 GMOCK_FLAG(verbose) = kErrorVerbosity;
2095 EXPECT_CALL(helper_, Foo(_))
2096 .WillOnce(Return(PrintMeNot()));
2097 helper_.Foo(PrintMeNot()); // This is an expected call.
2098}
2099
2100TEST_F(GMockLogTest, DoesNotPrintWarningInternallyIfVerbosityIsError) {
2101 GMOCK_FLAG(verbose) = kErrorVerbosity;
2102 ON_CALL(helper_, Foo(_))
2103 .WillByDefault(Return(PrintMeNot()));
2104 helper_.Foo(PrintMeNot()); // This should generate a warning.
2105}
2106
2107// Tests Mock::AllowLeak().
2108
zhanyong.wandf35a762009-04-22 22:25:31 +00002109TEST(AllowLeakTest, AllowsLeakingUnusedMockObject) {
2110 MockA* a = new MockA;
2111 Mock::AllowLeak(a);
2112}
2113
2114TEST(AllowLeakTest, CanBeCalledBeforeOnCall) {
2115 MockA* a = new MockA;
2116 Mock::AllowLeak(a);
2117 ON_CALL(*a, DoA(_)).WillByDefault(Return());
2118 a->DoA(0);
2119}
2120
2121TEST(AllowLeakTest, CanBeCalledAfterOnCall) {
2122 MockA* a = new MockA;
2123 ON_CALL(*a, DoA(_)).WillByDefault(Return());
2124 Mock::AllowLeak(a);
2125}
2126
2127TEST(AllowLeakTest, CanBeCalledBeforeExpectCall) {
2128 MockA* a = new MockA;
2129 Mock::AllowLeak(a);
2130 EXPECT_CALL(*a, DoA(_));
2131 a->DoA(0);
2132}
2133
2134TEST(AllowLeakTest, CanBeCalledAfterExpectCall) {
2135 MockA* a = new MockA;
2136 EXPECT_CALL(*a, DoA(_)).Times(AnyNumber());
2137 Mock::AllowLeak(a);
2138}
2139
2140TEST(AllowLeakTest, WorksWhenBothOnCallAndExpectCallArePresent) {
2141 MockA* a = new MockA;
2142 ON_CALL(*a, DoA(_)).WillByDefault(Return());
2143 EXPECT_CALL(*a, DoA(_)).Times(AnyNumber());
2144 Mock::AllowLeak(a);
2145}
shiqiane35fdd92008-12-10 05:08:54 +00002146
2147// Tests that we can verify and clear a mock object's expectations
2148// when none of its methods has expectations.
2149TEST(VerifyAndClearExpectationsTest, NoMethodHasExpectations) {
2150 MockB b;
2151 ASSERT_TRUE(Mock::VerifyAndClearExpectations(&b));
2152
2153 // There should be no expectations on the methods now, so we can
2154 // freely call them.
2155 EXPECT_EQ(0, b.DoB());
2156 EXPECT_EQ(0, b.DoB(1));
2157}
2158
2159// Tests that we can verify and clear a mock object's expectations
2160// when some, but not all, of its methods have expectations *and* the
2161// verification succeeds.
2162TEST(VerifyAndClearExpectationsTest, SomeMethodsHaveExpectationsAndSucceed) {
2163 MockB b;
2164 EXPECT_CALL(b, DoB())
2165 .WillOnce(Return(1));
2166 b.DoB();
2167 ASSERT_TRUE(Mock::VerifyAndClearExpectations(&b));
2168
2169 // There should be no expectations on the methods now, so we can
2170 // freely call them.
2171 EXPECT_EQ(0, b.DoB());
2172 EXPECT_EQ(0, b.DoB(1));
2173}
2174
2175// Tests that we can verify and clear a mock object's expectations
2176// when some, but not all, of its methods have expectations *and* the
2177// verification fails.
2178TEST(VerifyAndClearExpectationsTest, SomeMethodsHaveExpectationsAndFail) {
2179 MockB b;
2180 EXPECT_CALL(b, DoB())
2181 .WillOnce(Return(1));
vladlosev6c54a5e2009-10-21 06:15:34 +00002182 bool result = true;
shiqiane35fdd92008-12-10 05:08:54 +00002183 EXPECT_NONFATAL_FAILURE(result = Mock::VerifyAndClearExpectations(&b),
2184 "Actual: never called");
2185 ASSERT_FALSE(result);
2186
2187 // There should be no expectations on the methods now, so we can
2188 // freely call them.
2189 EXPECT_EQ(0, b.DoB());
2190 EXPECT_EQ(0, b.DoB(1));
2191}
2192
2193// Tests that we can verify and clear a mock object's expectations
2194// when all of its methods have expectations.
2195TEST(VerifyAndClearExpectationsTest, AllMethodsHaveExpectations) {
2196 MockB b;
2197 EXPECT_CALL(b, DoB())
2198 .WillOnce(Return(1));
2199 EXPECT_CALL(b, DoB(_))
2200 .WillOnce(Return(2));
2201 b.DoB();
2202 b.DoB(1);
2203 ASSERT_TRUE(Mock::VerifyAndClearExpectations(&b));
2204
2205 // There should be no expectations on the methods now, so we can
2206 // freely call them.
2207 EXPECT_EQ(0, b.DoB());
2208 EXPECT_EQ(0, b.DoB(1));
2209}
2210
2211// Tests that we can verify and clear a mock object's expectations
2212// when a method has more than one expectation.
2213TEST(VerifyAndClearExpectationsTest, AMethodHasManyExpectations) {
2214 MockB b;
2215 EXPECT_CALL(b, DoB(0))
2216 .WillOnce(Return(1));
2217 EXPECT_CALL(b, DoB(_))
2218 .WillOnce(Return(2));
2219 b.DoB(1);
vladlosev6c54a5e2009-10-21 06:15:34 +00002220 bool result = true;
shiqiane35fdd92008-12-10 05:08:54 +00002221 EXPECT_NONFATAL_FAILURE(result = Mock::VerifyAndClearExpectations(&b),
2222 "Actual: never called");
2223 ASSERT_FALSE(result);
2224
2225 // There should be no expectations on the methods now, so we can
2226 // freely call them.
2227 EXPECT_EQ(0, b.DoB());
2228 EXPECT_EQ(0, b.DoB(1));
2229}
2230
2231// Tests that we can call VerifyAndClearExpectations() on the same
2232// mock object multiple times.
2233TEST(VerifyAndClearExpectationsTest, CanCallManyTimes) {
2234 MockB b;
2235 EXPECT_CALL(b, DoB());
2236 b.DoB();
2237 Mock::VerifyAndClearExpectations(&b);
2238
2239 EXPECT_CALL(b, DoB(_))
2240 .WillOnce(Return(1));
2241 b.DoB(1);
2242 Mock::VerifyAndClearExpectations(&b);
2243 Mock::VerifyAndClearExpectations(&b);
2244
2245 // There should be no expectations on the methods now, so we can
2246 // freely call them.
2247 EXPECT_EQ(0, b.DoB());
2248 EXPECT_EQ(0, b.DoB(1));
2249}
2250
2251// Tests that we can clear a mock object's default actions when none
2252// of its methods has default actions.
2253TEST(VerifyAndClearTest, NoMethodHasDefaultActions) {
2254 MockB b;
2255 // If this crashes or generates a failure, the test will catch it.
2256 Mock::VerifyAndClear(&b);
2257 EXPECT_EQ(0, b.DoB());
2258}
2259
2260// Tests that we can clear a mock object's default actions when some,
2261// but not all of its methods have default actions.
2262TEST(VerifyAndClearTest, SomeMethodsHaveDefaultActions) {
2263 MockB b;
2264 ON_CALL(b, DoB())
2265 .WillByDefault(Return(1));
2266
2267 Mock::VerifyAndClear(&b);
2268
2269 // Verifies that the default action of int DoB() was removed.
2270 EXPECT_EQ(0, b.DoB());
2271}
2272
2273// Tests that we can clear a mock object's default actions when all of
2274// its methods have default actions.
2275TEST(VerifyAndClearTest, AllMethodsHaveDefaultActions) {
2276 MockB b;
2277 ON_CALL(b, DoB())
2278 .WillByDefault(Return(1));
2279 ON_CALL(b, DoB(_))
2280 .WillByDefault(Return(2));
2281
2282 Mock::VerifyAndClear(&b);
2283
2284 // Verifies that the default action of int DoB() was removed.
2285 EXPECT_EQ(0, b.DoB());
2286
2287 // Verifies that the default action of int DoB(int) was removed.
2288 EXPECT_EQ(0, b.DoB(0));
2289}
2290
2291// Tests that we can clear a mock object's default actions when a
2292// method has more than one ON_CALL() set on it.
2293TEST(VerifyAndClearTest, AMethodHasManyDefaultActions) {
2294 MockB b;
2295 ON_CALL(b, DoB(0))
2296 .WillByDefault(Return(1));
2297 ON_CALL(b, DoB(_))
2298 .WillByDefault(Return(2));
2299
2300 Mock::VerifyAndClear(&b);
2301
2302 // Verifies that the default actions (there are two) of int DoB(int)
2303 // were removed.
2304 EXPECT_EQ(0, b.DoB(0));
2305 EXPECT_EQ(0, b.DoB(1));
2306}
2307
2308// Tests that we can call VerifyAndClear() on a mock object multiple
2309// times.
2310TEST(VerifyAndClearTest, CanCallManyTimes) {
2311 MockB b;
2312 ON_CALL(b, DoB())
2313 .WillByDefault(Return(1));
2314 Mock::VerifyAndClear(&b);
2315 Mock::VerifyAndClear(&b);
2316
2317 ON_CALL(b, DoB(_))
2318 .WillByDefault(Return(1));
2319 Mock::VerifyAndClear(&b);
2320
2321 EXPECT_EQ(0, b.DoB());
2322 EXPECT_EQ(0, b.DoB(1));
2323}
2324
2325// Tests that VerifyAndClear() works when the verification succeeds.
2326TEST(VerifyAndClearTest, Success) {
2327 MockB b;
2328 ON_CALL(b, DoB())
2329 .WillByDefault(Return(1));
2330 EXPECT_CALL(b, DoB(1))
2331 .WillOnce(Return(2));
2332
2333 b.DoB();
2334 b.DoB(1);
2335 ASSERT_TRUE(Mock::VerifyAndClear(&b));
2336
2337 // There should be no expectations on the methods now, so we can
2338 // freely call them.
2339 EXPECT_EQ(0, b.DoB());
2340 EXPECT_EQ(0, b.DoB(1));
2341}
2342
2343// Tests that VerifyAndClear() works when the verification fails.
2344TEST(VerifyAndClearTest, Failure) {
2345 MockB b;
2346 ON_CALL(b, DoB(_))
2347 .WillByDefault(Return(1));
2348 EXPECT_CALL(b, DoB())
2349 .WillOnce(Return(2));
2350
2351 b.DoB(1);
vladlosev6c54a5e2009-10-21 06:15:34 +00002352 bool result = true;
shiqiane35fdd92008-12-10 05:08:54 +00002353 EXPECT_NONFATAL_FAILURE(result = Mock::VerifyAndClear(&b),
2354 "Actual: never called");
2355 ASSERT_FALSE(result);
2356
2357 // There should be no expectations on the methods now, so we can
2358 // freely call them.
2359 EXPECT_EQ(0, b.DoB());
2360 EXPECT_EQ(0, b.DoB(1));
2361}
2362
2363// Tests that VerifyAndClear() works when the default actions and
2364// expectations are set on a const mock object.
2365TEST(VerifyAndClearTest, Const) {
2366 MockB b;
2367 ON_CALL(Const(b), DoB())
2368 .WillByDefault(Return(1));
2369
2370 EXPECT_CALL(Const(b), DoB())
2371 .WillOnce(DoDefault())
2372 .WillOnce(Return(2));
2373
2374 b.DoB();
2375 b.DoB();
2376 ASSERT_TRUE(Mock::VerifyAndClear(&b));
2377
2378 // There should be no expectations on the methods now, so we can
2379 // freely call them.
2380 EXPECT_EQ(0, b.DoB());
2381 EXPECT_EQ(0, b.DoB(1));
2382}
2383
2384// Tests that we can set default actions and expectations on a mock
2385// object after VerifyAndClear() has been called on it.
2386TEST(VerifyAndClearTest, CanSetDefaultActionsAndExpectationsAfterwards) {
2387 MockB b;
2388 ON_CALL(b, DoB())
2389 .WillByDefault(Return(1));
2390 EXPECT_CALL(b, DoB(_))
2391 .WillOnce(Return(2));
2392 b.DoB(1);
2393
2394 Mock::VerifyAndClear(&b);
2395
2396 EXPECT_CALL(b, DoB())
2397 .WillOnce(Return(3));
2398 ON_CALL(b, DoB(_))
2399 .WillByDefault(Return(4));
2400
2401 EXPECT_EQ(3, b.DoB());
2402 EXPECT_EQ(4, b.DoB(1));
2403}
2404
2405// Tests that calling VerifyAndClear() on one mock object does not
2406// affect other mock objects (either of the same type or not).
2407TEST(VerifyAndClearTest, DoesNotAffectOtherMockObjects) {
2408 MockA a;
2409 MockB b1;
2410 MockB b2;
2411
2412 ON_CALL(a, Binary(_, _))
2413 .WillByDefault(Return(true));
2414 EXPECT_CALL(a, Binary(_, _))
2415 .WillOnce(DoDefault())
2416 .WillOnce(Return(false));
2417
2418 ON_CALL(b1, DoB())
2419 .WillByDefault(Return(1));
2420 EXPECT_CALL(b1, DoB(_))
2421 .WillOnce(Return(2));
2422
2423 ON_CALL(b2, DoB())
2424 .WillByDefault(Return(3));
2425 EXPECT_CALL(b2, DoB(_));
2426
2427 b2.DoB(0);
2428 Mock::VerifyAndClear(&b2);
2429
2430 // Verifies that the default actions and expectations of a and b1
2431 // are still in effect.
2432 EXPECT_TRUE(a.Binary(0, 0));
2433 EXPECT_FALSE(a.Binary(0, 0));
2434
2435 EXPECT_EQ(1, b1.DoB());
2436 EXPECT_EQ(2, b1.DoB(0));
2437}
2438
2439// Tests that a mock function's action can call a mock function
2440// (either the same function or a different one) either as an explicit
2441// action or as a default action without causing a dead lock. It
2442// verifies that the action is not performed inside the critical
2443// section.
vladlosev54af9ba2010-05-04 16:05:11 +00002444TEST(SynchronizationTest, CanCallMockMethodInAction) {
2445 MockA a;
2446 MockC c;
2447 ON_CALL(a, DoA(_))
2448 .WillByDefault(IgnoreResult(InvokeWithoutArgs(&c,
2449 &MockC::NonVoidMethod)));
2450 EXPECT_CALL(a, DoA(1));
2451 EXPECT_CALL(a, DoA(1))
2452 .WillOnce(Invoke(&a, &MockA::DoA))
2453 .RetiresOnSaturation();
2454 EXPECT_CALL(c, NonVoidMethod());
shiqiane35fdd92008-12-10 05:08:54 +00002455
vladlosev54af9ba2010-05-04 16:05:11 +00002456 a.DoA(1);
2457 // This will match the second EXPECT_CALL() and trigger another a.DoA(1),
2458 // which will in turn match the first EXPECT_CALL() and trigger a call to
2459 // c.NonVoidMethod() that was specified by the ON_CALL() since the first
2460 // EXPECT_CALL() did not specify an action.
shiqiane35fdd92008-12-10 05:08:54 +00002461}
2462
2463} // namespace
zhanyong.wandf35a762009-04-22 22:25:31 +00002464
zhanyong.wan9571b282009-08-07 07:15:56 +00002465// Allows the user to define his own main and then invoke gmock_main
2466// from it. This might be necessary on some platforms which require
2467// specific setup and teardown.
2468#if GMOCK_RENAME_MAIN
2469int gmock_main(int argc, char **argv) {
2470#else
zhanyong.wandf35a762009-04-22 22:25:31 +00002471int main(int argc, char **argv) {
zhanyong.wan9571b282009-08-07 07:15:56 +00002472#endif // GMOCK_RENAME_MAIN
zhanyong.wandf35a762009-04-22 22:25:31 +00002473 testing::InitGoogleMock(&argc, argv);
2474
2475 // Ensures that the tests pass no matter what value of
2476 // --gmock_catch_leaked_mocks and --gmock_verbose the user specifies.
2477 testing::GMOCK_FLAG(catch_leaked_mocks) = true;
2478 testing::GMOCK_FLAG(verbose) = testing::internal::kWarningVerbosity;
2479
2480 return RUN_ALL_TESTS();
2481}