1 // 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 (at) google.com (Zhanyong Wan) 31 32 // Google Mock - a framework for writing C++ mock classes. 33 // 34 // This file tests the spec builder syntax. 35 36 #include "gmock/gmock-spec-builders.h" 37 38 #include <ostream> // NOLINT 39 #include <sstream> 40 #include <string> 41 42 #include "gmock/gmock.h" 43 #include "gmock/internal/gmock-port.h" 44 #include "gtest/gtest.h" 45 #include "gtest/gtest-spi.h" 46 #include "gtest/internal/gtest-port.h" 47 48 namespace testing { 49 namespace internal { 50 51 // Helper class for testing the Expectation class template. 52 class 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 63 namespace { 64 65 using testing::_; 66 using testing::AnyNumber; 67 using testing::AtLeast; 68 using testing::AtMost; 69 using testing::Between; 70 using testing::Cardinality; 71 using testing::CardinalityInterface; 72 using testing::ContainsRegex; 73 using testing::Const; 74 using testing::DoAll; 75 using testing::DoDefault; 76 using testing::Eq; 77 using testing::Expectation; 78 using testing::ExpectationSet; 79 using testing::GMOCK_FLAG(verbose); 80 using testing::Gt; 81 using testing::InSequence; 82 using testing::Invoke; 83 using testing::InvokeWithoutArgs; 84 using testing::IsNotSubstring; 85 using testing::IsSubstring; 86 using testing::Lt; 87 using testing::Message; 88 using testing::Mock; 89 using testing::NaggyMock; 90 using testing::Ne; 91 using testing::Return; 92 using testing::Sequence; 93 using testing::SetArgPointee; 94 using testing::internal::ExpectationTester; 95 using testing::internal::FormatFileLocation; 96 using testing::internal::kAllow; 97 using testing::internal::kErrorVerbosity; 98 using testing::internal::kFail; 99 using testing::internal::kInfoVerbosity; 100 using testing::internal::kWarn; 101 using testing::internal::kWarningVerbosity; 102 using testing::internal::linked_ptr; 103 104 #if GTEST_HAS_STREAM_REDIRECTION 105 using testing::HasSubstr; 106 using testing::internal::CaptureStdout; 107 using testing::internal::GetCapturedStdout; 108 #endif 109 110 class Incomplete; 111 112 class MockIncomplete { 113 public: 114 // This line verifies that a mock method can take a by-reference 115 // argument of an incomplete type. 116 MOCK_METHOD1(ByRefFunc, void(const Incomplete& x)); 117 }; 118 119 // Tells Google Mock how to print a value of type Incomplete. 120 void PrintTo(const Incomplete& x, ::std::ostream* os); 121 122 TEST(MockMethodTest, CanInstantiateWithIncompleteArgType) { 123 // Even though this mock class contains a mock method that takes 124 // by-reference an argument whose type is incomplete, we can still 125 // use the mock, as long as Google Mock knows how to print the 126 // argument. 127 MockIncomplete incomplete; 128 EXPECT_CALL(incomplete, ByRefFunc(_)) 129 .Times(AnyNumber()); 130 } 131 132 // The definition of the printer for the argument type doesn't have to 133 // be visible where the mock is used. 134 void PrintTo(const Incomplete& /* x */, ::std::ostream* os) { 135 *os << "incomplete"; 136 } 137 138 class Result {}; 139 140 // A type that's not default constructible. 141 class NonDefaultConstructible { 142 public: 143 explicit NonDefaultConstructible(int /* dummy */) {} 144 }; 145 146 class MockA { 147 public: 148 MockA() {} 149 150 MOCK_METHOD1(DoA, void(int n)); 151 MOCK_METHOD1(ReturnResult, Result(int n)); 152 MOCK_METHOD0(ReturnNonDefaultConstructible, NonDefaultConstructible()); 153 MOCK_METHOD2(Binary, bool(int x, int y)); 154 MOCK_METHOD2(ReturnInt, int(int x, int y)); 155 156 private: 157 GTEST_DISALLOW_COPY_AND_ASSIGN_(MockA); 158 }; 159 160 class MockB { 161 public: 162 MockB() {} 163 164 MOCK_CONST_METHOD0(DoB, int()); // NOLINT 165 MOCK_METHOD1(DoB, int(int n)); // NOLINT 166 167 private: 168 GTEST_DISALLOW_COPY_AND_ASSIGN_(MockB); 169 }; 170 171 class ReferenceHoldingMock { 172 public: 173 ReferenceHoldingMock() {} 174 175 MOCK_METHOD1(AcceptReference, void(linked_ptr<MockA>*)); 176 177 private: 178 GTEST_DISALLOW_COPY_AND_ASSIGN_(ReferenceHoldingMock); 179 }; 180 181 // Tests that EXPECT_CALL and ON_CALL compile in a presence of macro 182 // redefining a mock method name. This could happen, for example, when 183 // the tested code #includes Win32 API headers which define many APIs 184 // as macros, e.g. #define TextOut TextOutW. 185 186 #define Method MethodW 187 188 class CC { 189 public: 190 virtual ~CC() {} 191 virtual int Method() = 0; 192 }; 193 class MockCC : public CC { 194 public: 195 MockCC() {} 196 197 MOCK_METHOD0(Method, int()); 198 199 private: 200 GTEST_DISALLOW_COPY_AND_ASSIGN_(MockCC); 201 }; 202 203 // Tests that a method with expanded name compiles. 204 TEST(OnCallSyntaxTest, CompilesWithMethodNameExpandedFromMacro) { 205 MockCC cc; 206 ON_CALL(cc, Method()); 207 } 208 209 // Tests that the method with expanded name not only compiles but runs 210 // and returns a correct value, too. 211 TEST(OnCallSyntaxTest, WorksWithMethodNameExpandedFromMacro) { 212 MockCC cc; 213 ON_CALL(cc, Method()).WillByDefault(Return(42)); 214 EXPECT_EQ(42, cc.Method()); 215 } 216 217 // Tests that a method with expanded name compiles. 218 TEST(ExpectCallSyntaxTest, CompilesWithMethodNameExpandedFromMacro) { 219 MockCC cc; 220 EXPECT_CALL(cc, Method()); 221 cc.Method(); 222 } 223 224 // Tests that it works, too. 225 TEST(ExpectCallSyntaxTest, WorksWithMethodNameExpandedFromMacro) { 226 MockCC cc; 227 EXPECT_CALL(cc, Method()).WillOnce(Return(42)); 228 EXPECT_EQ(42, cc.Method()); 229 } 230 231 #undef Method // Done with macro redefinition tests. 232 233 // Tests that ON_CALL evaluates its arguments exactly once as promised 234 // by Google Mock. 235 TEST(OnCallSyntaxTest, EvaluatesFirstArgumentOnce) { 236 MockA a; 237 MockA* pa = &a; 238 239 ON_CALL(*pa++, DoA(_)); 240 EXPECT_EQ(&a + 1, pa); 241 } 242 243 TEST(OnCallSyntaxTest, EvaluatesSecondArgumentOnce) { 244 MockA a; 245 int n = 0; 246 247 ON_CALL(a, DoA(n++)); 248 EXPECT_EQ(1, n); 249 } 250 251 // Tests that the syntax of ON_CALL() is enforced at run time. 252 253 TEST(OnCallSyntaxTest, WithIsOptional) { 254 MockA a; 255 256 ON_CALL(a, DoA(5)) 257 .WillByDefault(Return()); 258 ON_CALL(a, DoA(_)) 259 .With(_) 260 .WillByDefault(Return()); 261 } 262 263 TEST(OnCallSyntaxTest, WithCanAppearAtMostOnce) { 264 MockA a; 265 266 EXPECT_NONFATAL_FAILURE({ // NOLINT 267 ON_CALL(a, ReturnResult(_)) 268 .With(_) 269 .With(_) 270 .WillByDefault(Return(Result())); 271 }, ".With() cannot appear more than once in an ON_CALL()"); 272 } 273 274 TEST(OnCallSyntaxTest, WillByDefaultIsMandatory) { 275 MockA a; 276 277 EXPECT_DEATH_IF_SUPPORTED({ 278 ON_CALL(a, DoA(5)); 279 a.DoA(5); 280 }, ""); 281 } 282 283 TEST(OnCallSyntaxTest, WillByDefaultCanAppearAtMostOnce) { 284 MockA a; 285 286 EXPECT_NONFATAL_FAILURE({ // NOLINT 287 ON_CALL(a, DoA(5)) 288 .WillByDefault(Return()) 289 .WillByDefault(Return()); 290 }, ".WillByDefault() must appear exactly once in an ON_CALL()"); 291 } 292 293 // Tests that EXPECT_CALL evaluates its arguments exactly once as 294 // promised by Google Mock. 295 TEST(ExpectCallSyntaxTest, EvaluatesFirstArgumentOnce) { 296 MockA a; 297 MockA* pa = &a; 298 299 EXPECT_CALL(*pa++, DoA(_)); 300 a.DoA(0); 301 EXPECT_EQ(&a + 1, pa); 302 } 303 304 TEST(ExpectCallSyntaxTest, EvaluatesSecondArgumentOnce) { 305 MockA a; 306 int n = 0; 307 308 EXPECT_CALL(a, DoA(n++)); 309 a.DoA(0); 310 EXPECT_EQ(1, n); 311 } 312 313 // Tests that the syntax of EXPECT_CALL() is enforced at run time. 314 315 TEST(ExpectCallSyntaxTest, WithIsOptional) { 316 MockA a; 317 318 EXPECT_CALL(a, DoA(5)) 319 .Times(0); 320 EXPECT_CALL(a, DoA(6)) 321 .With(_) 322 .Times(0); 323 } 324 325 TEST(ExpectCallSyntaxTest, WithCanAppearAtMostOnce) { 326 MockA a; 327 328 EXPECT_NONFATAL_FAILURE({ // NOLINT 329 EXPECT_CALL(a, DoA(6)) 330 .With(_) 331 .With(_); 332 }, ".With() cannot appear more than once in an EXPECT_CALL()"); 333 334 a.DoA(6); 335 } 336 337 TEST(ExpectCallSyntaxTest, WithMustBeFirstClause) { 338 MockA a; 339 340 EXPECT_NONFATAL_FAILURE({ // NOLINT 341 EXPECT_CALL(a, DoA(1)) 342 .Times(1) 343 .With(_); 344 }, ".With() must be the first clause in an EXPECT_CALL()"); 345 346 a.DoA(1); 347 348 EXPECT_NONFATAL_FAILURE({ // NOLINT 349 EXPECT_CALL(a, DoA(2)) 350 .WillOnce(Return()) 351 .With(_); 352 }, ".With() must be the first clause in an EXPECT_CALL()"); 353 354 a.DoA(2); 355 } 356 357 TEST(ExpectCallSyntaxTest, TimesCanBeInferred) { 358 MockA a; 359 360 EXPECT_CALL(a, DoA(1)) 361 .WillOnce(Return()); 362 363 EXPECT_CALL(a, DoA(2)) 364 .WillOnce(Return()) 365 .WillRepeatedly(Return()); 366 367 a.DoA(1); 368 a.DoA(2); 369 a.DoA(2); 370 } 371 372 TEST(ExpectCallSyntaxTest, TimesCanAppearAtMostOnce) { 373 MockA a; 374 375 EXPECT_NONFATAL_FAILURE({ // NOLINT 376 EXPECT_CALL(a, DoA(1)) 377 .Times(1) 378 .Times(2); 379 }, ".Times() cannot appear more than once in an EXPECT_CALL()"); 380 381 a.DoA(1); 382 a.DoA(1); 383 } 384 385 TEST(ExpectCallSyntaxTest, TimesMustBeBeforeInSequence) { 386 MockA a; 387 Sequence s; 388 389 EXPECT_NONFATAL_FAILURE({ // NOLINT 390 EXPECT_CALL(a, DoA(1)) 391 .InSequence(s) 392 .Times(1); 393 }, ".Times() cannot appear after "); 394 395 a.DoA(1); 396 } 397 398 TEST(ExpectCallSyntaxTest, InSequenceIsOptional) { 399 MockA a; 400 Sequence s; 401 402 EXPECT_CALL(a, DoA(1)); 403 EXPECT_CALL(a, DoA(2)) 404 .InSequence(s); 405 406 a.DoA(1); 407 a.DoA(2); 408 } 409 410 TEST(ExpectCallSyntaxTest, InSequenceCanAppearMultipleTimes) { 411 MockA a; 412 Sequence s1, s2; 413 414 EXPECT_CALL(a, DoA(1)) 415 .InSequence(s1, s2) 416 .InSequence(s1); 417 418 a.DoA(1); 419 } 420 421 TEST(ExpectCallSyntaxTest, InSequenceMustBeBeforeAfter) { 422 MockA a; 423 Sequence s; 424 425 Expectation e = EXPECT_CALL(a, DoA(1)) 426 .Times(AnyNumber()); 427 EXPECT_NONFATAL_FAILURE({ // NOLINT 428 EXPECT_CALL(a, DoA(2)) 429 .After(e) 430 .InSequence(s); 431 }, ".InSequence() cannot appear after "); 432 433 a.DoA(2); 434 } 435 436 TEST(ExpectCallSyntaxTest, InSequenceMustBeBeforeWillOnce) { 437 MockA a; 438 Sequence s; 439 440 EXPECT_NONFATAL_FAILURE({ // NOLINT 441 EXPECT_CALL(a, DoA(1)) 442 .WillOnce(Return()) 443 .InSequence(s); 444 }, ".InSequence() cannot appear after "); 445 446 a.DoA(1); 447 } 448 449 TEST(ExpectCallSyntaxTest, AfterMustBeBeforeWillOnce) { 450 MockA a; 451 452 Expectation e = EXPECT_CALL(a, DoA(1)); 453 EXPECT_NONFATAL_FAILURE({ 454 EXPECT_CALL(a, DoA(2)) 455 .WillOnce(Return()) 456 .After(e); 457 }, ".After() cannot appear after "); 458 459 a.DoA(1); 460 a.DoA(2); 461 } 462 463 TEST(ExpectCallSyntaxTest, WillIsOptional) { 464 MockA a; 465 466 EXPECT_CALL(a, DoA(1)); 467 EXPECT_CALL(a, DoA(2)) 468 .WillOnce(Return()); 469 470 a.DoA(1); 471 a.DoA(2); 472 } 473 474 TEST(ExpectCallSyntaxTest, WillCanAppearMultipleTimes) { 475 MockA a; 476 477 EXPECT_CALL(a, DoA(1)) 478 .Times(AnyNumber()) 479 .WillOnce(Return()) 480 .WillOnce(Return()) 481 .WillOnce(Return()); 482 } 483 484 TEST(ExpectCallSyntaxTest, WillMustBeBeforeWillRepeatedly) { 485 MockA a; 486 487 EXPECT_NONFATAL_FAILURE({ // NOLINT 488 EXPECT_CALL(a, DoA(1)) 489 .WillRepeatedly(Return()) 490 .WillOnce(Return()); 491 }, ".WillOnce() cannot appear after "); 492 493 a.DoA(1); 494 } 495 496 TEST(ExpectCallSyntaxTest, WillRepeatedlyIsOptional) { 497 MockA a; 498 499 EXPECT_CALL(a, DoA(1)) 500 .WillOnce(Return()); 501 EXPECT_CALL(a, DoA(2)) 502 .WillOnce(Return()) 503 .WillRepeatedly(Return()); 504 505 a.DoA(1); 506 a.DoA(2); 507 a.DoA(2); 508 } 509 510 TEST(ExpectCallSyntaxTest, WillRepeatedlyCannotAppearMultipleTimes) { 511 MockA a; 512 513 EXPECT_NONFATAL_FAILURE({ // NOLINT 514 EXPECT_CALL(a, DoA(1)) 515 .WillRepeatedly(Return()) 516 .WillRepeatedly(Return()); 517 }, ".WillRepeatedly() cannot appear more than once in an " 518 "EXPECT_CALL()"); 519 } 520 521 TEST(ExpectCallSyntaxTest, WillRepeatedlyMustBeBeforeRetiresOnSaturation) { 522 MockA a; 523 524 EXPECT_NONFATAL_FAILURE({ // NOLINT 525 EXPECT_CALL(a, DoA(1)) 526 .RetiresOnSaturation() 527 .WillRepeatedly(Return()); 528 }, ".WillRepeatedly() cannot appear after "); 529 } 530 531 TEST(ExpectCallSyntaxTest, RetiresOnSaturationIsOptional) { 532 MockA a; 533 534 EXPECT_CALL(a, DoA(1)); 535 EXPECT_CALL(a, DoA(1)) 536 .RetiresOnSaturation(); 537 538 a.DoA(1); 539 a.DoA(1); 540 } 541 542 TEST(ExpectCallSyntaxTest, RetiresOnSaturationCannotAppearMultipleTimes) { 543 MockA a; 544 545 EXPECT_NONFATAL_FAILURE({ // NOLINT 546 EXPECT_CALL(a, DoA(1)) 547 .RetiresOnSaturation() 548 .RetiresOnSaturation(); 549 }, ".RetiresOnSaturation() cannot appear more than once"); 550 551 a.DoA(1); 552 } 553 554 TEST(ExpectCallSyntaxTest, DefaultCardinalityIsOnce) { 555 { 556 MockA a; 557 EXPECT_CALL(a, DoA(1)); 558 a.DoA(1); 559 } 560 EXPECT_NONFATAL_FAILURE({ // NOLINT 561 MockA a; 562 EXPECT_CALL(a, DoA(1)); 563 }, "to be called once"); 564 EXPECT_NONFATAL_FAILURE({ // NOLINT 565 MockA a; 566 EXPECT_CALL(a, DoA(1)); 567 a.DoA(1); 568 a.DoA(1); 569 }, "to be called once"); 570 } 571 572 #if GTEST_HAS_STREAM_REDIRECTION 573 574 // Tests that Google Mock doesn't print a warning when the number of 575 // WillOnce() is adequate. 576 TEST(ExpectCallSyntaxTest, DoesNotWarnOnAdequateActionCount) { 577 CaptureStdout(); 578 { 579 MockB b; 580 581 // It's always fine to omit WillOnce() entirely. 582 EXPECT_CALL(b, DoB()) 583 .Times(0); 584 EXPECT_CALL(b, DoB(1)) 585 .Times(AtMost(1)); 586 EXPECT_CALL(b, DoB(2)) 587 .Times(1) 588 .WillRepeatedly(Return(1)); 589 590 // It's fine for the number of WillOnce()s to equal the upper bound. 591 EXPECT_CALL(b, DoB(3)) 592 .Times(Between(1, 2)) 593 .WillOnce(Return(1)) 594 .WillOnce(Return(2)); 595 596 // It's fine for the number of WillOnce()s to be smaller than the 597 // upper bound when there is a WillRepeatedly(). 598 EXPECT_CALL(b, DoB(4)) 599 .Times(AtMost(3)) 600 .WillOnce(Return(1)) 601 .WillRepeatedly(Return(2)); 602 603 // Satisfies the above expectations. 604 b.DoB(2); 605 b.DoB(3); 606 } 607 EXPECT_STREQ("", GetCapturedStdout().c_str()); 608 } 609 610 // Tests that Google Mock warns on having too many actions in an 611 // expectation compared to its cardinality. 612 TEST(ExpectCallSyntaxTest, WarnsOnTooManyActions) { 613 CaptureStdout(); 614 { 615 MockB b; 616 617 // Warns when the number of WillOnce()s is larger than the upper bound. 618 EXPECT_CALL(b, DoB()) 619 .Times(0) 620 .WillOnce(Return(1)); // #1 621 EXPECT_CALL(b, DoB()) 622 .Times(AtMost(1)) 623 .WillOnce(Return(1)) 624 .WillOnce(Return(2)); // #2 625 EXPECT_CALL(b, DoB(1)) 626 .Times(1) 627 .WillOnce(Return(1)) 628 .WillOnce(Return(2)) 629 .RetiresOnSaturation(); // #3 630 631 // Warns when the number of WillOnce()s equals the upper bound and 632 // there is a WillRepeatedly(). 633 EXPECT_CALL(b, DoB()) 634 .Times(0) 635 .WillRepeatedly(Return(1)); // #4 636 EXPECT_CALL(b, DoB(2)) 637 .Times(1) 638 .WillOnce(Return(1)) 639 .WillRepeatedly(Return(2)); // #5 640 641 // Satisfies the above expectations. 642 b.DoB(1); 643 b.DoB(2); 644 } 645 const std::string output = GetCapturedStdout(); 646 EXPECT_PRED_FORMAT2( 647 IsSubstring, 648 "Too many actions specified in EXPECT_CALL(b, DoB())...\n" 649 "Expected to be never called, but has 1 WillOnce().", 650 output); // #1 651 EXPECT_PRED_FORMAT2( 652 IsSubstring, 653 "Too many actions specified in EXPECT_CALL(b, DoB())...\n" 654 "Expected to be called at most once, " 655 "but has 2 WillOnce()s.", 656 output); // #2 657 EXPECT_PRED_FORMAT2( 658 IsSubstring, 659 "Too many actions specified in EXPECT_CALL(b, DoB(1))...\n" 660 "Expected to be called once, but has 2 WillOnce()s.", 661 output); // #3 662 EXPECT_PRED_FORMAT2( 663 IsSubstring, 664 "Too many actions specified in EXPECT_CALL(b, DoB())...\n" 665 "Expected to be never called, but has 0 WillOnce()s " 666 "and a WillRepeatedly().", 667 output); // #4 668 EXPECT_PRED_FORMAT2( 669 IsSubstring, 670 "Too many actions specified in EXPECT_CALL(b, DoB(2))...\n" 671 "Expected to be called once, but has 1 WillOnce() " 672 "and a WillRepeatedly().", 673 output); // #5 674 } 675 676 // Tests that Google Mock warns on having too few actions in an 677 // expectation compared to its cardinality. 678 TEST(ExpectCallSyntaxTest, WarnsOnTooFewActions) { 679 MockB b; 680 681 EXPECT_CALL(b, DoB()) 682 .Times(Between(2, 3)) 683 .WillOnce(Return(1)); 684 685 CaptureStdout(); 686 b.DoB(); 687 const std::string output = GetCapturedStdout(); 688 EXPECT_PRED_FORMAT2( 689 IsSubstring, 690 "Too few actions specified in EXPECT_CALL(b, DoB())...\n" 691 "Expected to be called between 2 and 3 times, " 692 "but has only 1 WillOnce().", 693 output); 694 b.DoB(); 695 } 696 697 TEST(ExpectCallSyntaxTest, WarningIsErrorWithFlag) { 698 int original_behavior = testing::GMOCK_FLAG(default_mock_behavior); 699 700 testing::GMOCK_FLAG(default_mock_behavior) = kAllow; 701 CaptureStdout(); 702 { 703 MockA a; 704 a.DoA(0); 705 } 706 std::string output = GetCapturedStdout(); 707 EXPECT_TRUE(output.empty()) << output; 708 709 testing::GMOCK_FLAG(default_mock_behavior) = kWarn; 710 CaptureStdout(); 711 { 712 MockA a; 713 a.DoA(0); 714 } 715 std::string warning_output = GetCapturedStdout(); 716 EXPECT_PRED_FORMAT2(IsSubstring, "GMOCK WARNING", warning_output); 717 EXPECT_PRED_FORMAT2(IsSubstring, "Uninteresting mock function call", 718 warning_output); 719 720 testing::GMOCK_FLAG(default_mock_behavior) = kFail; 721 EXPECT_NONFATAL_FAILURE({ 722 MockA a; 723 a.DoA(0); 724 }, "Uninteresting mock function call"); 725 726 // Out of bounds values are converted to kWarn 727 testing::GMOCK_FLAG(default_mock_behavior) = -1; 728 CaptureStdout(); 729 { 730 MockA a; 731 a.DoA(0); 732 } 733 warning_output = GetCapturedStdout(); 734 EXPECT_PRED_FORMAT2(IsSubstring, "GMOCK WARNING", warning_output); 735 EXPECT_PRED_FORMAT2(IsSubstring, "Uninteresting mock function call", 736 warning_output); 737 testing::GMOCK_FLAG(default_mock_behavior) = 3; 738 CaptureStdout(); 739 { 740 MockA a; 741 a.DoA(0); 742 } 743 warning_output = GetCapturedStdout(); 744 EXPECT_PRED_FORMAT2(IsSubstring, "GMOCK WARNING", warning_output); 745 EXPECT_PRED_FORMAT2(IsSubstring, "Uninteresting mock function call", 746 warning_output); 747 748 testing::GMOCK_FLAG(default_mock_behavior) = original_behavior; 749 } 750 751 752 #endif // GTEST_HAS_STREAM_REDIRECTION 753 754 // Tests the semantics of ON_CALL(). 755 756 // Tests that the built-in default action is taken when no ON_CALL() 757 // is specified. 758 TEST(OnCallTest, TakesBuiltInDefaultActionWhenNoOnCall) { 759 MockB b; 760 EXPECT_CALL(b, DoB()); 761 762 EXPECT_EQ(0, b.DoB()); 763 } 764 765 // Tests that the built-in default action is taken when no ON_CALL() 766 // matches the invocation. 767 TEST(OnCallTest, TakesBuiltInDefaultActionWhenNoOnCallMatches) { 768 MockB b; 769 ON_CALL(b, DoB(1)) 770 .WillByDefault(Return(1)); 771 EXPECT_CALL(b, DoB(_)); 772 773 EXPECT_EQ(0, b.DoB(2)); 774 } 775 776 // Tests that the last matching ON_CALL() action is taken. 777 TEST(OnCallTest, PicksLastMatchingOnCall) { 778 MockB b; 779 ON_CALL(b, DoB(_)) 780 .WillByDefault(Return(3)); 781 ON_CALL(b, DoB(2)) 782 .WillByDefault(Return(2)); 783 ON_CALL(b, DoB(1)) 784 .WillByDefault(Return(1)); 785 EXPECT_CALL(b, DoB(_)); 786 787 EXPECT_EQ(2, b.DoB(2)); 788 } 789 790 // Tests the semantics of EXPECT_CALL(). 791 792 // Tests that any call is allowed when no EXPECT_CALL() is specified. 793 TEST(ExpectCallTest, AllowsAnyCallWhenNoSpec) { 794 MockB b; 795 EXPECT_CALL(b, DoB()); 796 // There is no expectation on DoB(int). 797 798 b.DoB(); 799 800 // DoB(int) can be called any number of times. 801 b.DoB(1); 802 b.DoB(2); 803 } 804 805 // Tests that the last matching EXPECT_CALL() fires. 806 TEST(ExpectCallTest, PicksLastMatchingExpectCall) { 807 MockB b; 808 EXPECT_CALL(b, DoB(_)) 809 .WillRepeatedly(Return(2)); 810 EXPECT_CALL(b, DoB(1)) 811 .WillRepeatedly(Return(1)); 812 813 EXPECT_EQ(1, b.DoB(1)); 814 } 815 816 // Tests lower-bound violation. 817 TEST(ExpectCallTest, CatchesTooFewCalls) { 818 EXPECT_NONFATAL_FAILURE({ // NOLINT 819 MockB b; 820 EXPECT_CALL(b, DoB(5)) 821 .Times(AtLeast(2)); 822 823 b.DoB(5); 824 }, "Actual function call count doesn't match EXPECT_CALL(b, DoB(5))...\n" 825 " Expected: to be called at least twice\n" 826 " Actual: called once - unsatisfied and active"); 827 } 828 829 // Tests that the cardinality can be inferred when no Times(...) is 830 // specified. 831 TEST(ExpectCallTest, InfersCardinalityWhenThereIsNoWillRepeatedly) { 832 { 833 MockB b; 834 EXPECT_CALL(b, DoB()) 835 .WillOnce(Return(1)) 836 .WillOnce(Return(2)); 837 838 EXPECT_EQ(1, b.DoB()); 839 EXPECT_EQ(2, b.DoB()); 840 } 841 842 EXPECT_NONFATAL_FAILURE({ // NOLINT 843 MockB b; 844 EXPECT_CALL(b, DoB()) 845 .WillOnce(Return(1)) 846 .WillOnce(Return(2)); 847 848 EXPECT_EQ(1, b.DoB()); 849 }, "to be called twice"); 850 851 { // NOLINT 852 MockB b; 853 EXPECT_CALL(b, DoB()) 854 .WillOnce(Return(1)) 855 .WillOnce(Return(2)); 856 857 EXPECT_EQ(1, b.DoB()); 858 EXPECT_EQ(2, b.DoB()); 859 EXPECT_NONFATAL_FAILURE(b.DoB(), "to be called twice"); 860 } 861 } 862 863 TEST(ExpectCallTest, InfersCardinality1WhenThereIsWillRepeatedly) { 864 { 865 MockB b; 866 EXPECT_CALL(b, DoB()) 867 .WillOnce(Return(1)) 868 .WillRepeatedly(Return(2)); 869 870 EXPECT_EQ(1, b.DoB()); 871 } 872 873 { // NOLINT 874 MockB b; 875 EXPECT_CALL(b, DoB()) 876 .WillOnce(Return(1)) 877 .WillRepeatedly(Return(2)); 878 879 EXPECT_EQ(1, b.DoB()); 880 EXPECT_EQ(2, b.DoB()); 881 EXPECT_EQ(2, b.DoB()); 882 } 883 884 EXPECT_NONFATAL_FAILURE({ // NOLINT 885 MockB b; 886 EXPECT_CALL(b, DoB()) 887 .WillOnce(Return(1)) 888 .WillRepeatedly(Return(2)); 889 }, "to be called at least once"); 890 } 891 892 // Tests that the n-th action is taken for the n-th matching 893 // invocation. 894 TEST(ExpectCallTest, NthMatchTakesNthAction) { 895 MockB b; 896 EXPECT_CALL(b, DoB()) 897 .WillOnce(Return(1)) 898 .WillOnce(Return(2)) 899 .WillOnce(Return(3)); 900 901 EXPECT_EQ(1, b.DoB()); 902 EXPECT_EQ(2, b.DoB()); 903 EXPECT_EQ(3, b.DoB()); 904 } 905 906 // Tests that the WillRepeatedly() action is taken when the WillOnce(...) 907 // list is exhausted. 908 TEST(ExpectCallTest, TakesRepeatedActionWhenWillListIsExhausted) { 909 MockB b; 910 EXPECT_CALL(b, DoB()) 911 .WillOnce(Return(1)) 912 .WillRepeatedly(Return(2)); 913 914 EXPECT_EQ(1, b.DoB()); 915 EXPECT_EQ(2, b.DoB()); 916 EXPECT_EQ(2, b.DoB()); 917 } 918 919 #if GTEST_HAS_STREAM_REDIRECTION 920 921 // Tests that the default action is taken when the WillOnce(...) list is 922 // exhausted and there is no WillRepeatedly(). 923 TEST(ExpectCallTest, TakesDefaultActionWhenWillListIsExhausted) { 924 MockB b; 925 EXPECT_CALL(b, DoB(_)) 926 .Times(1); 927 EXPECT_CALL(b, DoB()) 928 .Times(AnyNumber()) 929 .WillOnce(Return(1)) 930 .WillOnce(Return(2)); 931 932 CaptureStdout(); 933 EXPECT_EQ(0, b.DoB(1)); // Shouldn't generate a warning as the 934 // expectation has no action clause at all. 935 EXPECT_EQ(1, b.DoB()); 936 EXPECT_EQ(2, b.DoB()); 937 const std::string output1 = GetCapturedStdout(); 938 EXPECT_STREQ("", output1.c_str()); 939 940 CaptureStdout(); 941 EXPECT_EQ(0, b.DoB()); 942 EXPECT_EQ(0, b.DoB()); 943 const std::string output2 = GetCapturedStdout(); 944 EXPECT_THAT(output2.c_str(), 945 HasSubstr("Actions ran out in EXPECT_CALL(b, DoB())...\n" 946 "Called 3 times, but only 2 WillOnce()s are specified" 947 " - returning default value.")); 948 EXPECT_THAT(output2.c_str(), 949 HasSubstr("Actions ran out in EXPECT_CALL(b, DoB())...\n" 950 "Called 4 times, but only 2 WillOnce()s are specified" 951 " - returning default value.")); 952 } 953 954 TEST(FunctionMockerMessageTest, ReportsExpectCallLocationForExhausedActions) { 955 MockB b; 956 std::string expect_call_location = FormatFileLocation(__FILE__, __LINE__ + 1); 957 EXPECT_CALL(b, DoB()).Times(AnyNumber()).WillOnce(Return(1)); 958 959 EXPECT_EQ(1, b.DoB()); 960 961 CaptureStdout(); 962 EXPECT_EQ(0, b.DoB()); 963 const std::string output = GetCapturedStdout(); 964 // The warning message should contain the call location. 965 EXPECT_PRED_FORMAT2(IsSubstring, expect_call_location, output); 966 } 967 968 TEST(FunctionMockerMessageTest, 969 ReportsDefaultActionLocationOfUninterestingCallsForNaggyMock) { 970 std::string on_call_location; 971 CaptureStdout(); 972 { 973 NaggyMock<MockB> b; 974 on_call_location = FormatFileLocation(__FILE__, __LINE__ + 1); 975 ON_CALL(b, DoB(_)).WillByDefault(Return(0)); 976 b.DoB(0); 977 } 978 EXPECT_PRED_FORMAT2(IsSubstring, on_call_location, GetCapturedStdout()); 979 } 980 981 #endif // GTEST_HAS_STREAM_REDIRECTION 982 983 // Tests that an uninteresting call performs the default action. 984 TEST(UninterestingCallTest, DoesDefaultAction) { 985 // When there is an ON_CALL() statement, the action specified by it 986 // should be taken. 987 MockA a; 988 ON_CALL(a, Binary(_, _)) 989 .WillByDefault(Return(true)); 990 EXPECT_TRUE(a.Binary(1, 2)); 991 992 // When there is no ON_CALL(), the default value for the return type 993 // should be returned. 994 MockB b; 995 EXPECT_EQ(0, b.DoB()); 996 } 997 998 // Tests that an unexpected call performs the default action. 999 TEST(UnexpectedCallTest, DoesDefaultAction) { 1000 // When there is an ON_CALL() statement, the action specified by it 1001 // should be taken. 1002 MockA a; 1003 ON_CALL(a, Binary(_, _)) 1004 .WillByDefault(Return(true)); 1005 EXPECT_CALL(a, Binary(0, 0)); 1006 a.Binary(0, 0); 1007 bool result = false; 1008 EXPECT_NONFATAL_FAILURE(result = a.Binary(1, 2), 1009 "Unexpected mock function call"); 1010 EXPECT_TRUE(result); 1011 1012 // When there is no ON_CALL(), the default value for the return type 1013 // should be returned. 1014 MockB b; 1015 EXPECT_CALL(b, DoB(0)) 1016 .Times(0); 1017 int n = -1; 1018 EXPECT_NONFATAL_FAILURE(n = b.DoB(1), 1019 "Unexpected mock function call"); 1020 EXPECT_EQ(0, n); 1021 } 1022 1023 // Tests that when an unexpected void function generates the right 1024 // failure message. 1025 TEST(UnexpectedCallTest, GeneratesFailureForVoidFunction) { 1026 // First, tests the message when there is only one EXPECT_CALL(). 1027 MockA a1; 1028 EXPECT_CALL(a1, DoA(1)); 1029 a1.DoA(1); 1030 // Ideally we should match the failure message against a regex, but 1031 // EXPECT_NONFATAL_FAILURE doesn't support that, so we test for 1032 // multiple sub-strings instead. 1033 EXPECT_NONFATAL_FAILURE( 1034 a1.DoA(9), 1035 "Unexpected mock function call - returning directly.\n" 1036 " Function call: DoA(9)\n" 1037 "Google Mock tried the following 1 expectation, but it didn't match:"); 1038 EXPECT_NONFATAL_FAILURE( 1039 a1.DoA(9), 1040 " Expected arg #0: is equal to 1\n" 1041 " Actual: 9\n" 1042 " Expected: to be called once\n" 1043 " Actual: called once - saturated and active"); 1044 1045 // Next, tests the message when there are more than one EXPECT_CALL(). 1046 MockA a2; 1047 EXPECT_CALL(a2, DoA(1)); 1048 EXPECT_CALL(a2, DoA(3)); 1049 a2.DoA(1); 1050 EXPECT_NONFATAL_FAILURE( 1051 a2.DoA(2), 1052 "Unexpected mock function call - returning directly.\n" 1053 " Function call: DoA(2)\n" 1054 "Google Mock tried the following 2 expectations, but none matched:"); 1055 EXPECT_NONFATAL_FAILURE( 1056 a2.DoA(2), 1057 "tried expectation #0: EXPECT_CALL(a2, DoA(1))...\n" 1058 " Expected arg #0: is equal to 1\n" 1059 " Actual: 2\n" 1060 " Expected: to be called once\n" 1061 " Actual: called once - saturated and active"); 1062 EXPECT_NONFATAL_FAILURE( 1063 a2.DoA(2), 1064 "tried expectation #1: EXPECT_CALL(a2, DoA(3))...\n" 1065 " Expected arg #0: is equal to 3\n" 1066 " Actual: 2\n" 1067 " Expected: to be called once\n" 1068 " Actual: never called - unsatisfied and active"); 1069 a2.DoA(3); 1070 } 1071 1072 // Tests that an unexpected non-void function generates the right 1073 // failure message. 1074 TEST(UnexpectedCallTest, GeneartesFailureForNonVoidFunction) { 1075 MockB b1; 1076 EXPECT_CALL(b1, DoB(1)); 1077 b1.DoB(1); 1078 EXPECT_NONFATAL_FAILURE( 1079 b1.DoB(2), 1080 "Unexpected mock function call - returning default value.\n" 1081 " Function call: DoB(2)\n" 1082 " Returns: 0\n" 1083 "Google Mock tried the following 1 expectation, but it didn't match:"); 1084 EXPECT_NONFATAL_FAILURE( 1085 b1.DoB(2), 1086 " Expected arg #0: is equal to 1\n" 1087 " Actual: 2\n" 1088 " Expected: to be called once\n" 1089 " Actual: called once - saturated and active"); 1090 } 1091 1092 // Tests that Google Mock explains that an retired expectation doesn't 1093 // match the call. 1094 TEST(UnexpectedCallTest, RetiredExpectation) { 1095 MockB b; 1096 EXPECT_CALL(b, DoB(1)) 1097 .RetiresOnSaturation(); 1098 1099 b.DoB(1); 1100 EXPECT_NONFATAL_FAILURE( 1101 b.DoB(1), 1102 " Expected: the expectation is active\n" 1103 " Actual: it is retired"); 1104 } 1105 1106 // Tests that Google Mock explains that an expectation that doesn't 1107 // match the arguments doesn't match the call. 1108 TEST(UnexpectedCallTest, UnmatchedArguments) { 1109 MockB b; 1110 EXPECT_CALL(b, DoB(1)); 1111 1112 EXPECT_NONFATAL_FAILURE( 1113 b.DoB(2), 1114 " Expected arg #0: is equal to 1\n" 1115 " Actual: 2\n"); 1116 b.DoB(1); 1117 } 1118 1119 // Tests that Google Mock explains that an expectation with 1120 // unsatisfied pre-requisites doesn't match the call. 1121 TEST(UnexpectedCallTest, UnsatisifiedPrerequisites) { 1122 Sequence s1, s2; 1123 MockB b; 1124 EXPECT_CALL(b, DoB(1)) 1125 .InSequence(s1); 1126 EXPECT_CALL(b, DoB(2)) 1127 .Times(AnyNumber()) 1128 .InSequence(s1); 1129 EXPECT_CALL(b, DoB(3)) 1130 .InSequence(s2); 1131 EXPECT_CALL(b, DoB(4)) 1132 .InSequence(s1, s2); 1133 1134 ::testing::TestPartResultArray failures; 1135 { 1136 ::testing::ScopedFakeTestPartResultReporter reporter(&failures); 1137 b.DoB(4); 1138 // Now 'failures' contains the Google Test failures generated by 1139 // the above statement. 1140 } 1141 1142 // There should be one non-fatal failure. 1143 ASSERT_EQ(1, failures.size()); 1144 const ::testing::TestPartResult& r = failures.GetTestPartResult(0); 1145 EXPECT_EQ(::testing::TestPartResult::kNonFatalFailure, r.type()); 1146 1147 // Verifies that the failure message contains the two unsatisfied 1148 // pre-requisites but not the satisfied one. 1149 #if GTEST_USES_PCRE 1150 EXPECT_THAT(r.message(), ContainsRegex( 1151 // PCRE has trouble using (.|\n) to match any character, but 1152 // supports the (?s) prefix for using . to match any character. 1153 "(?s)the following immediate pre-requisites are not satisfied:\n" 1154 ".*: pre-requisite #0\n" 1155 ".*: pre-requisite #1")); 1156 #elif GTEST_USES_POSIX_RE 1157 EXPECT_THAT(r.message(), ContainsRegex( 1158 // POSIX RE doesn't understand the (?s) prefix, but has no trouble 1159 // with (.|\n). 1160 "the following immediate pre-requisites are not satisfied:\n" 1161 "(.|\n)*: pre-requisite #0\n" 1162 "(.|\n)*: pre-requisite #1")); 1163 #else 1164 // We can only use Google Test's own simple regex. 1165 EXPECT_THAT(r.message(), ContainsRegex( 1166 "the following immediate pre-requisites are not satisfied:")); 1167 EXPECT_THAT(r.message(), ContainsRegex(": pre-requisite #0")); 1168 EXPECT_THAT(r.message(), ContainsRegex(": pre-requisite #1")); 1169 #endif // GTEST_USES_PCRE 1170 1171 b.DoB(1); 1172 b.DoB(3); 1173 b.DoB(4); 1174 } 1175 1176 TEST(UndefinedReturnValueTest, 1177 ReturnValueIsMandatoryWhenNotDefaultConstructible) { 1178 MockA a; 1179 // TODO(wan (at) google.com): We should really verify the output message, 1180 // but we cannot yet due to that EXPECT_DEATH only captures stderr 1181 // while Google Mock logs to stdout. 1182 #if GTEST_HAS_EXCEPTIONS 1183 EXPECT_ANY_THROW(a.ReturnNonDefaultConstructible()); 1184 #else 1185 EXPECT_DEATH_IF_SUPPORTED(a.ReturnNonDefaultConstructible(), ""); 1186 #endif 1187 } 1188 1189 // Tests that an excessive call (one whose arguments match the 1190 // matchers but is called too many times) performs the default action. 1191 TEST(ExcessiveCallTest, DoesDefaultAction) { 1192 // When there is an ON_CALL() statement, the action specified by it 1193 // should be taken. 1194 MockA a; 1195 ON_CALL(a, Binary(_, _)) 1196 .WillByDefault(Return(true)); 1197 EXPECT_CALL(a, Binary(0, 0)); 1198 a.Binary(0, 0); 1199 bool result = false; 1200 EXPECT_NONFATAL_FAILURE(result = a.Binary(0, 0), 1201 "Mock function called more times than expected"); 1202 EXPECT_TRUE(result); 1203 1204 // When there is no ON_CALL(), the default value for the return type 1205 // should be returned. 1206 MockB b; 1207 EXPECT_CALL(b, DoB(0)) 1208 .Times(0); 1209 int n = -1; 1210 EXPECT_NONFATAL_FAILURE(n = b.DoB(0), 1211 "Mock function called more times than expected"); 1212 EXPECT_EQ(0, n); 1213 } 1214 1215 // Tests that when a void function is called too many times, 1216 // the failure message contains the argument values. 1217 TEST(ExcessiveCallTest, GeneratesFailureForVoidFunction) { 1218 MockA a; 1219 EXPECT_CALL(a, DoA(_)) 1220 .Times(0); 1221 EXPECT_NONFATAL_FAILURE( 1222 a.DoA(9), 1223 "Mock function called more times than expected - returning directly.\n" 1224 " Function call: DoA(9)\n" 1225 " Expected: to be never called\n" 1226 " Actual: called once - over-saturated and active"); 1227 } 1228 1229 // Tests that when a non-void function is called too many times, the 1230 // failure message contains the argument values and the return value. 1231 TEST(ExcessiveCallTest, GeneratesFailureForNonVoidFunction) { 1232 MockB b; 1233 EXPECT_CALL(b, DoB(_)); 1234 b.DoB(1); 1235 EXPECT_NONFATAL_FAILURE( 1236 b.DoB(2), 1237 "Mock function called more times than expected - " 1238 "returning default value.\n" 1239 " Function call: DoB(2)\n" 1240 " Returns: 0\n" 1241 " Expected: to be called once\n" 1242 " Actual: called twice - over-saturated and active"); 1243 } 1244 1245 // Tests using sequences. 1246 1247 TEST(InSequenceTest, AllExpectationInScopeAreInSequence) { 1248 MockA a; 1249 { 1250 InSequence dummy; 1251 1252 EXPECT_CALL(a, DoA(1)); 1253 EXPECT_CALL(a, DoA(2)); 1254 } 1255 1256 EXPECT_NONFATAL_FAILURE({ // NOLINT 1257 a.DoA(2); 1258 }, "Unexpected mock function call"); 1259 1260 a.DoA(1); 1261 a.DoA(2); 1262 } 1263 1264 TEST(InSequenceTest, NestedInSequence) { 1265 MockA a; 1266 { 1267 InSequence dummy; 1268 1269 EXPECT_CALL(a, DoA(1)); 1270 { 1271 InSequence dummy2; 1272 1273 EXPECT_CALL(a, DoA(2)); 1274 EXPECT_CALL(a, DoA(3)); 1275 } 1276 } 1277 1278 EXPECT_NONFATAL_FAILURE({ // NOLINT 1279 a.DoA(1); 1280 a.DoA(3); 1281 }, "Unexpected mock function call"); 1282 1283 a.DoA(2); 1284 a.DoA(3); 1285 } 1286 1287 TEST(InSequenceTest, ExpectationsOutOfScopeAreNotAffected) { 1288 MockA a; 1289 { 1290 InSequence dummy; 1291 1292 EXPECT_CALL(a, DoA(1)); 1293 EXPECT_CALL(a, DoA(2)); 1294 } 1295 EXPECT_CALL(a, DoA(3)); 1296 1297 EXPECT_NONFATAL_FAILURE({ // NOLINT 1298 a.DoA(2); 1299 }, "Unexpected mock function call"); 1300 1301 a.DoA(3); 1302 a.DoA(1); 1303 a.DoA(2); 1304 } 1305 1306 // Tests that any order is allowed when no sequence is used. 1307 TEST(SequenceTest, AnyOrderIsOkByDefault) { 1308 { 1309 MockA a; 1310 MockB b; 1311 1312 EXPECT_CALL(a, DoA(1)); 1313 EXPECT_CALL(b, DoB()) 1314 .Times(AnyNumber()); 1315 1316 a.DoA(1); 1317 b.DoB(); 1318 } 1319 1320 { // NOLINT 1321 MockA a; 1322 MockB b; 1323 1324 EXPECT_CALL(a, DoA(1)); 1325 EXPECT_CALL(b, DoB()) 1326 .Times(AnyNumber()); 1327 1328 b.DoB(); 1329 a.DoA(1); 1330 } 1331 } 1332 1333 // Tests that the calls must be in strict order when a complete order 1334 // is specified. 1335 TEST(SequenceTest, CallsMustBeInStrictOrderWhenSaidSo1) { 1336 MockA a; 1337 ON_CALL(a, ReturnResult(_)) 1338 .WillByDefault(Return(Result())); 1339 1340 Sequence s; 1341 EXPECT_CALL(a, ReturnResult(1)) 1342 .InSequence(s); 1343 EXPECT_CALL(a, ReturnResult(2)) 1344 .InSequence(s); 1345 EXPECT_CALL(a, ReturnResult(3)) 1346 .InSequence(s); 1347 1348 a.ReturnResult(1); 1349 1350 // May only be called after a.ReturnResult(2). 1351 EXPECT_NONFATAL_FAILURE(a.ReturnResult(3), "Unexpected mock function call"); 1352 1353 a.ReturnResult(2); 1354 a.ReturnResult(3); 1355 } 1356 1357 // Tests that the calls must be in strict order when a complete order 1358 // is specified. 1359 TEST(SequenceTest, CallsMustBeInStrictOrderWhenSaidSo2) { 1360 MockA a; 1361 ON_CALL(a, ReturnResult(_)) 1362 .WillByDefault(Return(Result())); 1363 1364 Sequence s; 1365 EXPECT_CALL(a, ReturnResult(1)) 1366 .InSequence(s); 1367 EXPECT_CALL(a, ReturnResult(2)) 1368 .InSequence(s); 1369 1370 // May only be called after a.ReturnResult(1). 1371 EXPECT_NONFATAL_FAILURE(a.ReturnResult(2), "Unexpected mock function call"); 1372 1373 a.ReturnResult(1); 1374 a.ReturnResult(2); 1375 } 1376 1377 // Tests specifying a DAG using multiple sequences. 1378 class PartialOrderTest : public testing::Test { 1379 protected: 1380 PartialOrderTest() { 1381 ON_CALL(a_, ReturnResult(_)) 1382 .WillByDefault(Return(Result())); 1383 1384 // Specifies this partial ordering: 1385 // 1386 // a.ReturnResult(1) ==> 1387 // a.ReturnResult(2) * n ==> a.ReturnResult(3) 1388 // b.DoB() * 2 ==> 1389 Sequence x, y; 1390 EXPECT_CALL(a_, ReturnResult(1)) 1391 .InSequence(x); 1392 EXPECT_CALL(b_, DoB()) 1393 .Times(2) 1394 .InSequence(y); 1395 EXPECT_CALL(a_, ReturnResult(2)) 1396 .Times(AnyNumber()) 1397 .InSequence(x, y); 1398 EXPECT_CALL(a_, ReturnResult(3)) 1399 .InSequence(x); 1400 } 1401 1402 MockA a_; 1403 MockB b_; 1404 }; 1405 1406 TEST_F(PartialOrderTest, CallsMustConformToSpecifiedDag1) { 1407 a_.ReturnResult(1); 1408 b_.DoB(); 1409 1410 // May only be called after the second DoB(). 1411 EXPECT_NONFATAL_FAILURE(a_.ReturnResult(2), "Unexpected mock function call"); 1412 1413 b_.DoB(); 1414 a_.ReturnResult(3); 1415 } 1416 1417 TEST_F(PartialOrderTest, CallsMustConformToSpecifiedDag2) { 1418 // May only be called after ReturnResult(1). 1419 EXPECT_NONFATAL_FAILURE(a_.ReturnResult(2), "Unexpected mock function call"); 1420 1421 a_.ReturnResult(1); 1422 b_.DoB(); 1423 b_.DoB(); 1424 a_.ReturnResult(3); 1425 } 1426 1427 TEST_F(PartialOrderTest, CallsMustConformToSpecifiedDag3) { 1428 // May only be called last. 1429 EXPECT_NONFATAL_FAILURE(a_.ReturnResult(3), "Unexpected mock function call"); 1430 1431 a_.ReturnResult(1); 1432 b_.DoB(); 1433 b_.DoB(); 1434 a_.ReturnResult(3); 1435 } 1436 1437 TEST_F(PartialOrderTest, CallsMustConformToSpecifiedDag4) { 1438 a_.ReturnResult(1); 1439 b_.DoB(); 1440 b_.DoB(); 1441 a_.ReturnResult(3); 1442 1443 // May only be called before ReturnResult(3). 1444 EXPECT_NONFATAL_FAILURE(a_.ReturnResult(2), "Unexpected mock function call"); 1445 } 1446 1447 TEST(SequenceTest, Retirement) { 1448 MockA a; 1449 Sequence s; 1450 1451 EXPECT_CALL(a, DoA(1)) 1452 .InSequence(s); 1453 EXPECT_CALL(a, DoA(_)) 1454 .InSequence(s) 1455 .RetiresOnSaturation(); 1456 EXPECT_CALL(a, DoA(1)) 1457 .InSequence(s); 1458 1459 a.DoA(1); 1460 a.DoA(2); 1461 a.DoA(1); 1462 } 1463 1464 // Tests Expectation. 1465 1466 TEST(ExpectationTest, ConstrutorsWork) { 1467 MockA a; 1468 Expectation e1; // Default ctor. 1469 1470 // Ctor from various forms of EXPECT_CALL. 1471 Expectation e2 = EXPECT_CALL(a, DoA(2)); 1472 Expectation e3 = EXPECT_CALL(a, DoA(3)).With(_); 1473 { 1474 Sequence s; 1475 Expectation e4 = EXPECT_CALL(a, DoA(4)).Times(1); 1476 Expectation e5 = EXPECT_CALL(a, DoA(5)).InSequence(s); 1477 } 1478 Expectation e6 = EXPECT_CALL(a, DoA(6)).After(e2); 1479 Expectation e7 = EXPECT_CALL(a, DoA(7)).WillOnce(Return()); 1480 Expectation e8 = EXPECT_CALL(a, DoA(8)).WillRepeatedly(Return()); 1481 Expectation e9 = EXPECT_CALL(a, DoA(9)).RetiresOnSaturation(); 1482 1483 Expectation e10 = e2; // Copy ctor. 1484 1485 EXPECT_THAT(e1, Ne(e2)); 1486 EXPECT_THAT(e2, Eq(e10)); 1487 1488 a.DoA(2); 1489 a.DoA(3); 1490 a.DoA(4); 1491 a.DoA(5); 1492 a.DoA(6); 1493 a.DoA(7); 1494 a.DoA(8); 1495 a.DoA(9); 1496 } 1497 1498 TEST(ExpectationTest, AssignmentWorks) { 1499 MockA a; 1500 Expectation e1; 1501 Expectation e2 = EXPECT_CALL(a, DoA(1)); 1502 1503 EXPECT_THAT(e1, Ne(e2)); 1504 1505 e1 = e2; 1506 EXPECT_THAT(e1, Eq(e2)); 1507 1508 a.DoA(1); 1509 } 1510 1511 // Tests ExpectationSet. 1512 1513 TEST(ExpectationSetTest, MemberTypesAreCorrect) { 1514 ::testing::StaticAssertTypeEq<Expectation, ExpectationSet::value_type>(); 1515 } 1516 1517 TEST(ExpectationSetTest, ConstructorsWork) { 1518 MockA a; 1519 1520 Expectation e1; 1521 const Expectation e2; 1522 ExpectationSet es1; // Default ctor. 1523 ExpectationSet es2 = EXPECT_CALL(a, DoA(1)); // Ctor from EXPECT_CALL. 1524 ExpectationSet es3 = e1; // Ctor from Expectation. 1525 ExpectationSet es4(e1); // Ctor from Expectation; alternative syntax. 1526 ExpectationSet es5 = e2; // Ctor from const Expectation. 1527 ExpectationSet es6(e2); // Ctor from const Expectation; alternative syntax. 1528 ExpectationSet es7 = es2; // Copy ctor. 1529 1530 EXPECT_EQ(0, es1.size()); 1531 EXPECT_EQ(1, es2.size()); 1532 EXPECT_EQ(1, es3.size()); 1533 EXPECT_EQ(1, es4.size()); 1534 EXPECT_EQ(1, es5.size()); 1535 EXPECT_EQ(1, es6.size()); 1536 EXPECT_EQ(1, es7.size()); 1537 1538 EXPECT_THAT(es3, Ne(es2)); 1539 EXPECT_THAT(es4, Eq(es3)); 1540 EXPECT_THAT(es5, Eq(es4)); 1541 EXPECT_THAT(es6, Eq(es5)); 1542 EXPECT_THAT(es7, Eq(es2)); 1543 a.DoA(1); 1544 } 1545 1546 TEST(ExpectationSetTest, AssignmentWorks) { 1547 ExpectationSet es1; 1548 ExpectationSet es2 = Expectation(); 1549 1550 es1 = es2; 1551 EXPECT_EQ(1, es1.size()); 1552 EXPECT_THAT(*(es1.begin()), Eq(Expectation())); 1553 EXPECT_THAT(es1, Eq(es2)); 1554 } 1555 1556 TEST(ExpectationSetTest, InsertionWorks) { 1557 ExpectationSet es1; 1558 Expectation e1; 1559 es1 += e1; 1560 EXPECT_EQ(1, es1.size()); 1561 EXPECT_THAT(*(es1.begin()), Eq(e1)); 1562 1563 MockA a; 1564 Expectation e2 = EXPECT_CALL(a, DoA(1)); 1565 es1 += e2; 1566 EXPECT_EQ(2, es1.size()); 1567 1568 ExpectationSet::const_iterator it1 = es1.begin(); 1569 ExpectationSet::const_iterator it2 = it1; 1570 ++it2; 1571 EXPECT_TRUE(*it1 == e1 || *it2 == e1); // e1 must be in the set. 1572 EXPECT_TRUE(*it1 == e2 || *it2 == e2); // e2 must be in the set too. 1573 a.DoA(1); 1574 } 1575 1576 TEST(ExpectationSetTest, SizeWorks) { 1577 ExpectationSet es; 1578 EXPECT_EQ(0, es.size()); 1579 1580 es += Expectation(); 1581 EXPECT_EQ(1, es.size()); 1582 1583 MockA a; 1584 es += EXPECT_CALL(a, DoA(1)); 1585 EXPECT_EQ(2, es.size()); 1586 1587 a.DoA(1); 1588 } 1589 1590 TEST(ExpectationSetTest, IsEnumerable) { 1591 ExpectationSet es; 1592 EXPECT_TRUE(es.begin() == es.end()); 1593 1594 es += Expectation(); 1595 ExpectationSet::const_iterator it = es.begin(); 1596 EXPECT_TRUE(it != es.end()); 1597 EXPECT_THAT(*it, Eq(Expectation())); 1598 ++it; 1599 EXPECT_TRUE(it== es.end()); 1600 } 1601 1602 // Tests the .After() clause. 1603 1604 TEST(AfterTest, SucceedsWhenPartialOrderIsSatisfied) { 1605 MockA a; 1606 ExpectationSet es; 1607 es += EXPECT_CALL(a, DoA(1)); 1608 es += EXPECT_CALL(a, DoA(2)); 1609 EXPECT_CALL(a, DoA(3)) 1610 .After(es); 1611 1612 a.DoA(1); 1613 a.DoA(2); 1614 a.DoA(3); 1615 } 1616 1617 TEST(AfterTest, SucceedsWhenTotalOrderIsSatisfied) { 1618 MockA a; 1619 MockB b; 1620 // The following also verifies that const Expectation objects work 1621 // too. Do not remove the const modifiers. 1622 const Expectation e1 = EXPECT_CALL(a, DoA(1)); 1623 const Expectation e2 = EXPECT_CALL(b, DoB()) 1624 .Times(2) 1625 .After(e1); 1626 EXPECT_CALL(a, DoA(2)).After(e2); 1627 1628 a.DoA(1); 1629 b.DoB(); 1630 b.DoB(); 1631 a.DoA(2); 1632 } 1633 1634 // Calls must be in strict order when specified so using .After(). 1635 TEST(AfterTest, CallsMustBeInStrictOrderWhenSpecifiedSo1) { 1636 MockA a; 1637 MockB b; 1638 1639 // Define ordering: 1640 // a.DoA(1) ==> b.DoB() ==> a.DoA(2) 1641 Expectation e1 = EXPECT_CALL(a, DoA(1)); 1642 Expectation e2 = EXPECT_CALL(b, DoB()) 1643 .After(e1); 1644 EXPECT_CALL(a, DoA(2)) 1645 .After(e2); 1646 1647 a.DoA(1); 1648 1649 // May only be called after DoB(). 1650 EXPECT_NONFATAL_FAILURE(a.DoA(2), "Unexpected mock function call"); 1651 1652 b.DoB(); 1653 a.DoA(2); 1654 } 1655 1656 // Calls must be in strict order when specified so using .After(). 1657 TEST(AfterTest, CallsMustBeInStrictOrderWhenSpecifiedSo2) { 1658 MockA a; 1659 MockB b; 1660 1661 // Define ordering: 1662 // a.DoA(1) ==> b.DoB() * 2 ==> a.DoA(2) 1663 Expectation e1 = EXPECT_CALL(a, DoA(1)); 1664 Expectation e2 = EXPECT_CALL(b, DoB()) 1665 .Times(2) 1666 .After(e1); 1667 EXPECT_CALL(a, DoA(2)) 1668 .After(e2); 1669 1670 a.DoA(1); 1671 b.DoB(); 1672 1673 // May only be called after the second DoB(). 1674 EXPECT_NONFATAL_FAILURE(a.DoA(2), "Unexpected mock function call"); 1675 1676 b.DoB(); 1677 a.DoA(2); 1678 } 1679 1680 // Calls must satisfy the partial order when specified so. 1681 TEST(AfterTest, CallsMustSatisfyPartialOrderWhenSpecifiedSo) { 1682 MockA a; 1683 ON_CALL(a, ReturnResult(_)) 1684 .WillByDefault(Return(Result())); 1685 1686 // Define ordering: 1687 // a.DoA(1) ==> 1688 // a.DoA(2) ==> a.ReturnResult(3) 1689 Expectation e = EXPECT_CALL(a, DoA(1)); 1690 const ExpectationSet es = EXPECT_CALL(a, DoA(2)); 1691 EXPECT_CALL(a, ReturnResult(3)) 1692 .After(e, es); 1693 1694 // May only be called last. 1695 EXPECT_NONFATAL_FAILURE(a.ReturnResult(3), "Unexpected mock function call"); 1696 1697 a.DoA(2); 1698 a.DoA(1); 1699 a.ReturnResult(3); 1700 } 1701 1702 // Calls must satisfy the partial order when specified so. 1703 TEST(AfterTest, CallsMustSatisfyPartialOrderWhenSpecifiedSo2) { 1704 MockA a; 1705 1706 // Define ordering: 1707 // a.DoA(1) ==> 1708 // a.DoA(2) ==> a.DoA(3) 1709 Expectation e = EXPECT_CALL(a, DoA(1)); 1710 const ExpectationSet es = EXPECT_CALL(a, DoA(2)); 1711 EXPECT_CALL(a, DoA(3)) 1712 .After(e, es); 1713 1714 a.DoA(2); 1715 1716 // May only be called last. 1717 EXPECT_NONFATAL_FAILURE(a.DoA(3), "Unexpected mock function call"); 1718 1719 a.DoA(1); 1720 a.DoA(3); 1721 } 1722 1723 // .After() can be combined with .InSequence(). 1724 TEST(AfterTest, CanBeUsedWithInSequence) { 1725 MockA a; 1726 Sequence s; 1727 Expectation e = EXPECT_CALL(a, DoA(1)); 1728 EXPECT_CALL(a, DoA(2)).InSequence(s); 1729 EXPECT_CALL(a, DoA(3)) 1730 .InSequence(s) 1731 .After(e); 1732 1733 a.DoA(1); 1734 1735 // May only be after DoA(2). 1736 EXPECT_NONFATAL_FAILURE(a.DoA(3), "Unexpected mock function call"); 1737 1738 a.DoA(2); 1739 a.DoA(3); 1740 } 1741 1742 // .After() can be called multiple times. 1743 TEST(AfterTest, CanBeCalledManyTimes) { 1744 MockA a; 1745 Expectation e1 = EXPECT_CALL(a, DoA(1)); 1746 Expectation e2 = EXPECT_CALL(a, DoA(2)); 1747 Expectation e3 = EXPECT_CALL(a, DoA(3)); 1748 EXPECT_CALL(a, DoA(4)) 1749 .After(e1) 1750 .After(e2) 1751 .After(e3); 1752 1753 a.DoA(3); 1754 a.DoA(1); 1755 a.DoA(2); 1756 a.DoA(4); 1757 } 1758 1759 // .After() accepts up to 5 arguments. 1760 TEST(AfterTest, AcceptsUpToFiveArguments) { 1761 MockA a; 1762 Expectation e1 = EXPECT_CALL(a, DoA(1)); 1763 Expectation e2 = EXPECT_CALL(a, DoA(2)); 1764 Expectation e3 = EXPECT_CALL(a, DoA(3)); 1765 ExpectationSet es1 = EXPECT_CALL(a, DoA(4)); 1766 ExpectationSet es2 = EXPECT_CALL(a, DoA(5)); 1767 EXPECT_CALL(a, DoA(6)) 1768 .After(e1, e2, e3, es1, es2); 1769 1770 a.DoA(5); 1771 a.DoA(2); 1772 a.DoA(4); 1773 a.DoA(1); 1774 a.DoA(3); 1775 a.DoA(6); 1776 } 1777 1778 // .After() allows input to contain duplicated Expectations. 1779 TEST(AfterTest, AcceptsDuplicatedInput) { 1780 MockA a; 1781 ON_CALL(a, ReturnResult(_)) 1782 .WillByDefault(Return(Result())); 1783 1784 // Define ordering: 1785 // DoA(1) ==> 1786 // DoA(2) ==> ReturnResult(3) 1787 Expectation e1 = EXPECT_CALL(a, DoA(1)); 1788 Expectation e2 = EXPECT_CALL(a, DoA(2)); 1789 ExpectationSet es; 1790 es += e1; 1791 es += e2; 1792 EXPECT_CALL(a, ReturnResult(3)) 1793 .After(e1, e2, es, e1); 1794 1795 a.DoA(1); 1796 1797 // May only be after DoA(2). 1798 EXPECT_NONFATAL_FAILURE(a.ReturnResult(3), "Unexpected mock function call"); 1799 1800 a.DoA(2); 1801 a.ReturnResult(3); 1802 } 1803 1804 // An Expectation added to an ExpectationSet after it has been used in 1805 // an .After() has no effect. 1806 TEST(AfterTest, ChangesToExpectationSetHaveNoEffectAfterwards) { 1807 MockA a; 1808 ExpectationSet es1 = EXPECT_CALL(a, DoA(1)); 1809 Expectation e2 = EXPECT_CALL(a, DoA(2)); 1810 EXPECT_CALL(a, DoA(3)) 1811 .After(es1); 1812 es1 += e2; 1813 1814 a.DoA(1); 1815 a.DoA(3); 1816 a.DoA(2); 1817 } 1818 1819 // Tests that Google Mock correctly handles calls to mock functions 1820 // after a mock object owning one of their pre-requisites has died. 1821 1822 // Tests that calls that satisfy the original spec are successful. 1823 TEST(DeletingMockEarlyTest, Success1) { 1824 MockB* const b1 = new MockB; 1825 MockA* const a = new MockA; 1826 MockB* const b2 = new MockB; 1827 1828 { 1829 InSequence dummy; 1830 EXPECT_CALL(*b1, DoB(_)) 1831 .WillOnce(Return(1)); 1832 EXPECT_CALL(*a, Binary(_, _)) 1833 .Times(AnyNumber()) 1834 .WillRepeatedly(Return(true)); 1835 EXPECT_CALL(*b2, DoB(_)) 1836 .Times(AnyNumber()) 1837 .WillRepeatedly(Return(2)); 1838 } 1839 1840 EXPECT_EQ(1, b1->DoB(1)); 1841 delete b1; 1842 // a's pre-requisite has died. 1843 EXPECT_TRUE(a->Binary(0, 1)); 1844 delete b2; 1845 // a's successor has died. 1846 EXPECT_TRUE(a->Binary(1, 2)); 1847 delete a; 1848 } 1849 1850 // Tests that calls that satisfy the original spec are successful. 1851 TEST(DeletingMockEarlyTest, Success2) { 1852 MockB* const b1 = new MockB; 1853 MockA* const a = new MockA; 1854 MockB* const b2 = new MockB; 1855 1856 { 1857 InSequence dummy; 1858 EXPECT_CALL(*b1, DoB(_)) 1859 .WillOnce(Return(1)); 1860 EXPECT_CALL(*a, Binary(_, _)) 1861 .Times(AnyNumber()); 1862 EXPECT_CALL(*b2, DoB(_)) 1863 .Times(AnyNumber()) 1864 .WillRepeatedly(Return(2)); 1865 } 1866 1867 delete a; // a is trivially satisfied. 1868 EXPECT_EQ(1, b1->DoB(1)); 1869 EXPECT_EQ(2, b2->DoB(2)); 1870 delete b1; 1871 delete b2; 1872 } 1873 1874 // Tests that it's OK to delete a mock object itself in its action. 1875 1876 // Suppresses warning on unreferenced formal parameter in MSVC with 1877 // -W4. 1878 #ifdef _MSC_VER 1879 # pragma warning(push) 1880 # pragma warning(disable:4100) 1881 #endif 1882 1883 ACTION_P(Delete, ptr) { delete ptr; } 1884 1885 #ifdef _MSC_VER 1886 # pragma warning(pop) 1887 #endif 1888 1889 TEST(DeletingMockEarlyTest, CanDeleteSelfInActionReturningVoid) { 1890 MockA* const a = new MockA; 1891 EXPECT_CALL(*a, DoA(_)).WillOnce(Delete(a)); 1892 a->DoA(42); // This will cause a to be deleted. 1893 } 1894 1895 TEST(DeletingMockEarlyTest, CanDeleteSelfInActionReturningValue) { 1896 MockA* const a = new MockA; 1897 EXPECT_CALL(*a, ReturnResult(_)) 1898 .WillOnce(DoAll(Delete(a), Return(Result()))); 1899 a->ReturnResult(42); // This will cause a to be deleted. 1900 } 1901 1902 // Tests that calls that violate the original spec yield failures. 1903 TEST(DeletingMockEarlyTest, Failure1) { 1904 MockB* const b1 = new MockB; 1905 MockA* const a = new MockA; 1906 MockB* const b2 = new MockB; 1907 1908 { 1909 InSequence dummy; 1910 EXPECT_CALL(*b1, DoB(_)) 1911 .WillOnce(Return(1)); 1912 EXPECT_CALL(*a, Binary(_, _)) 1913 .Times(AnyNumber()); 1914 EXPECT_CALL(*b2, DoB(_)) 1915 .Times(AnyNumber()) 1916 .WillRepeatedly(Return(2)); 1917 } 1918 1919 delete a; // a is trivially satisfied. 1920 EXPECT_NONFATAL_FAILURE({ 1921 b2->DoB(2); 1922 }, "Unexpected mock function call"); 1923 EXPECT_EQ(1, b1->DoB(1)); 1924 delete b1; 1925 delete b2; 1926 } 1927 1928 // Tests that calls that violate the original spec yield failures. 1929 TEST(DeletingMockEarlyTest, Failure2) { 1930 MockB* const b1 = new MockB; 1931 MockA* const a = new MockA; 1932 MockB* const b2 = new MockB; 1933 1934 { 1935 InSequence dummy; 1936 EXPECT_CALL(*b1, DoB(_)); 1937 EXPECT_CALL(*a, Binary(_, _)) 1938 .Times(AnyNumber()); 1939 EXPECT_CALL(*b2, DoB(_)) 1940 .Times(AnyNumber()); 1941 } 1942 1943 EXPECT_NONFATAL_FAILURE(delete b1, 1944 "Actual: never called"); 1945 EXPECT_NONFATAL_FAILURE(a->Binary(0, 1), 1946 "Unexpected mock function call"); 1947 EXPECT_NONFATAL_FAILURE(b2->DoB(1), 1948 "Unexpected mock function call"); 1949 delete a; 1950 delete b2; 1951 } 1952 1953 class EvenNumberCardinality : public CardinalityInterface { 1954 public: 1955 // Returns true iff call_count calls will satisfy this cardinality. 1956 virtual bool IsSatisfiedByCallCount(int call_count) const { 1957 return call_count % 2 == 0; 1958 } 1959 1960 // Returns true iff call_count calls will saturate this cardinality. 1961 virtual bool IsSaturatedByCallCount(int /* call_count */) const { 1962 return false; 1963 } 1964 1965 // Describes self to an ostream. 1966 virtual void DescribeTo(::std::ostream* os) const { 1967 *os << "called even number of times"; 1968 } 1969 }; 1970 1971 Cardinality EvenNumber() { 1972 return Cardinality(new EvenNumberCardinality); 1973 } 1974 1975 TEST(ExpectationBaseTest, 1976 AllPrerequisitesAreSatisfiedWorksForNonMonotonicCardinality) { 1977 MockA* a = new MockA; 1978 Sequence s; 1979 1980 EXPECT_CALL(*a, DoA(1)) 1981 .Times(EvenNumber()) 1982 .InSequence(s); 1983 EXPECT_CALL(*a, DoA(2)) 1984 .Times(AnyNumber()) 1985 .InSequence(s); 1986 EXPECT_CALL(*a, DoA(3)) 1987 .Times(AnyNumber()); 1988 1989 a->DoA(3); 1990 a->DoA(1); 1991 EXPECT_NONFATAL_FAILURE(a->DoA(2), "Unexpected mock function call"); 1992 EXPECT_NONFATAL_FAILURE(delete a, "to be called even number of times"); 1993 } 1994 1995 // The following tests verify the message generated when a mock 1996 // function is called. 1997 1998 struct Printable { 1999 }; 2000 2001 inline void operator<<(::std::ostream& os, const Printable&) { 2002 os << "Printable"; 2003 } 2004 2005 struct Unprintable { 2006 Unprintable() : value(0) {} 2007 int value; 2008 }; 2009 2010 class MockC { 2011 public: 2012 MockC() {} 2013 2014 MOCK_METHOD6(VoidMethod, void(bool cond, int n, std::string s, void* p, 2015 const Printable& x, Unprintable y)); 2016 MOCK_METHOD0(NonVoidMethod, int()); // NOLINT 2017 2018 private: 2019 GTEST_DISALLOW_COPY_AND_ASSIGN_(MockC); 2020 }; 2021 2022 class VerboseFlagPreservingFixture : public testing::Test { 2023 protected: 2024 VerboseFlagPreservingFixture() 2025 : saved_verbose_flag_(GMOCK_FLAG(verbose)) {} 2026 2027 ~VerboseFlagPreservingFixture() { GMOCK_FLAG(verbose) = saved_verbose_flag_; } 2028 2029 private: 2030 const std::string saved_verbose_flag_; 2031 2032 GTEST_DISALLOW_COPY_AND_ASSIGN_(VerboseFlagPreservingFixture); 2033 }; 2034 2035 #if GTEST_HAS_STREAM_REDIRECTION 2036 2037 // Tests that an uninteresting mock function call on a naggy mock 2038 // generates a warning without the stack trace when 2039 // --gmock_verbose=warning is specified. 2040 TEST(FunctionCallMessageTest, 2041 UninterestingCallOnNaggyMockGeneratesNoStackTraceWhenVerboseWarning) { 2042 GMOCK_FLAG(verbose) = kWarningVerbosity; 2043 NaggyMock<MockC> c; 2044 CaptureStdout(); 2045 c.VoidMethod(false, 5, "Hi", NULL, Printable(), Unprintable()); 2046 const std::string output = GetCapturedStdout(); 2047 EXPECT_PRED_FORMAT2(IsSubstring, "GMOCK WARNING", output); 2048 EXPECT_PRED_FORMAT2(IsNotSubstring, "Stack trace:", output); 2049 } 2050 2051 // Tests that an uninteresting mock function call on a naggy mock 2052 // generates a warning containing the stack trace when 2053 // --gmock_verbose=info is specified. 2054 TEST(FunctionCallMessageTest, 2055 UninterestingCallOnNaggyMockGeneratesFyiWithStackTraceWhenVerboseInfo) { 2056 GMOCK_FLAG(verbose) = kInfoVerbosity; 2057 NaggyMock<MockC> c; 2058 CaptureStdout(); 2059 c.VoidMethod(false, 5, "Hi", NULL, Printable(), Unprintable()); 2060 const std::string output = GetCapturedStdout(); 2061 EXPECT_PRED_FORMAT2(IsSubstring, "GMOCK WARNING", output); 2062 EXPECT_PRED_FORMAT2(IsSubstring, "Stack trace:", output); 2063 2064 # ifndef NDEBUG 2065 2066 // We check the stack trace content in dbg-mode only, as opt-mode 2067 // may inline the call we are interested in seeing. 2068 2069 // Verifies that a void mock function's name appears in the stack 2070 // trace. 2071 EXPECT_PRED_FORMAT2(IsSubstring, "VoidMethod(", output); 2072 2073 // Verifies that a non-void mock function's name appears in the 2074 // stack trace. 2075 CaptureStdout(); 2076 c.NonVoidMethod(); 2077 const std::string output2 = GetCapturedStdout(); 2078 EXPECT_PRED_FORMAT2(IsSubstring, "NonVoidMethod(", output2); 2079 2080 # endif // NDEBUG 2081 } 2082 2083 // Tests that an uninteresting mock function call on a naggy mock 2084 // causes the function arguments and return value to be printed. 2085 TEST(FunctionCallMessageTest, 2086 UninterestingCallOnNaggyMockPrintsArgumentsAndReturnValue) { 2087 // A non-void mock function. 2088 NaggyMock<MockB> b; 2089 CaptureStdout(); 2090 b.DoB(); 2091 const std::string output1 = GetCapturedStdout(); 2092 EXPECT_PRED_FORMAT2( 2093 IsSubstring, 2094 "Uninteresting mock function call - returning default value.\n" 2095 " Function call: DoB()\n" 2096 " Returns: 0\n", output1.c_str()); 2097 // Makes sure the return value is printed. 2098 2099 // A void mock function. 2100 NaggyMock<MockC> c; 2101 CaptureStdout(); 2102 c.VoidMethod(false, 5, "Hi", NULL, Printable(), Unprintable()); 2103 const std::string output2 = GetCapturedStdout(); 2104 EXPECT_THAT(output2.c_str(), 2105 ContainsRegex( 2106 "Uninteresting mock function call - returning directly\\.\n" 2107 " Function call: VoidMethod" 2108 "\\(false, 5, \"Hi\", NULL, @.+ " 2109 "Printable, 4-byte object <00-00 00-00>\\)")); 2110 // A void function has no return value to print. 2111 } 2112 2113 // Tests how the --gmock_verbose flag affects Google Mock's output. 2114 2115 class GMockVerboseFlagTest : public VerboseFlagPreservingFixture { 2116 public: 2117 // Verifies that the given Google Mock output is correct. (When 2118 // should_print is true, the output should match the given regex and 2119 // contain the given function name in the stack trace. When it's 2120 // false, the output should be empty.) 2121 void VerifyOutput(const std::string& output, bool should_print, 2122 const std::string& expected_substring, 2123 const std::string& function_name) { 2124 if (should_print) { 2125 EXPECT_THAT(output.c_str(), HasSubstr(expected_substring)); 2126 # ifndef NDEBUG 2127 // We check the stack trace content in dbg-mode only, as opt-mode 2128 // may inline the call we are interested in seeing. 2129 EXPECT_THAT(output.c_str(), HasSubstr(function_name)); 2130 # else 2131 // Suppresses 'unused function parameter' warnings. 2132 static_cast<void>(function_name); 2133 # endif // NDEBUG 2134 } else { 2135 EXPECT_STREQ("", output.c_str()); 2136 } 2137 } 2138 2139 // Tests how the flag affects expected calls. 2140 void TestExpectedCall(bool should_print) { 2141 MockA a; 2142 EXPECT_CALL(a, DoA(5)); 2143 EXPECT_CALL(a, Binary(_, 1)) 2144 .WillOnce(Return(true)); 2145 2146 // A void-returning function. 2147 CaptureStdout(); 2148 a.DoA(5); 2149 VerifyOutput( 2150 GetCapturedStdout(), 2151 should_print, 2152 "Mock function call matches EXPECT_CALL(a, DoA(5))...\n" 2153 " Function call: DoA(5)\n" 2154 "Stack trace:\n", 2155 "DoA"); 2156 2157 // A non-void-returning function. 2158 CaptureStdout(); 2159 a.Binary(2, 1); 2160 VerifyOutput( 2161 GetCapturedStdout(), 2162 should_print, 2163 "Mock function call matches EXPECT_CALL(a, Binary(_, 1))...\n" 2164 " Function call: Binary(2, 1)\n" 2165 " Returns: true\n" 2166 "Stack trace:\n", 2167 "Binary"); 2168 } 2169 2170 // Tests how the flag affects uninteresting calls on a naggy mock. 2171 void TestUninterestingCallOnNaggyMock(bool should_print) { 2172 NaggyMock<MockA> a; 2173 const std::string note = 2174 "NOTE: You can safely ignore the above warning unless this " 2175 "call should not happen. Do not suppress it by blindly adding " 2176 "an EXPECT_CALL() if you don't mean to enforce the call. " 2177 "See https://github.com/google/googletest/blob/master/googlemock/docs/CookBook.md#" 2178 "knowing-when-to-expect for details."; 2179 2180 // A void-returning function. 2181 CaptureStdout(); 2182 a.DoA(5); 2183 VerifyOutput( 2184 GetCapturedStdout(), 2185 should_print, 2186 "\nGMOCK WARNING:\n" 2187 "Uninteresting mock function call - returning directly.\n" 2188 " Function call: DoA(5)\n" + 2189 note, 2190 "DoA"); 2191 2192 // A non-void-returning function. 2193 CaptureStdout(); 2194 a.Binary(2, 1); 2195 VerifyOutput( 2196 GetCapturedStdout(), 2197 should_print, 2198 "\nGMOCK WARNING:\n" 2199 "Uninteresting mock function call - returning default value.\n" 2200 " Function call: Binary(2, 1)\n" 2201 " Returns: false\n" + 2202 note, 2203 "Binary"); 2204 } 2205 }; 2206 2207 // Tests that --gmock_verbose=info causes both expected and 2208 // uninteresting calls to be reported. 2209 TEST_F(GMockVerboseFlagTest, Info) { 2210 GMOCK_FLAG(verbose) = kInfoVerbosity; 2211 TestExpectedCall(true); 2212 TestUninterestingCallOnNaggyMock(true); 2213 } 2214 2215 // Tests that --gmock_verbose=warning causes uninteresting calls to be 2216 // reported. 2217 TEST_F(GMockVerboseFlagTest, Warning) { 2218 GMOCK_FLAG(verbose) = kWarningVerbosity; 2219 TestExpectedCall(false); 2220 TestUninterestingCallOnNaggyMock(true); 2221 } 2222 2223 // Tests that --gmock_verbose=warning causes neither expected nor 2224 // uninteresting calls to be reported. 2225 TEST_F(GMockVerboseFlagTest, Error) { 2226 GMOCK_FLAG(verbose) = kErrorVerbosity; 2227 TestExpectedCall(false); 2228 TestUninterestingCallOnNaggyMock(false); 2229 } 2230 2231 // Tests that --gmock_verbose=SOME_INVALID_VALUE has the same effect 2232 // as --gmock_verbose=warning. 2233 TEST_F(GMockVerboseFlagTest, InvalidFlagIsTreatedAsWarning) { 2234 GMOCK_FLAG(verbose) = "invalid"; // Treated as "warning". 2235 TestExpectedCall(false); 2236 TestUninterestingCallOnNaggyMock(true); 2237 } 2238 2239 #endif // GTEST_HAS_STREAM_REDIRECTION 2240 2241 // A helper class that generates a failure when printed. We use it to 2242 // ensure that Google Mock doesn't print a value (even to an internal 2243 // buffer) when it is not supposed to do so. 2244 class PrintMeNot {}; 2245 2246 void PrintTo(PrintMeNot /* dummy */, ::std::ostream* /* os */) { 2247 ADD_FAILURE() << "Google Mock is printing a value that shouldn't be " 2248 << "printed even to an internal buffer."; 2249 } 2250 2251 class LogTestHelper { 2252 public: 2253 LogTestHelper() {} 2254 2255 MOCK_METHOD1(Foo, PrintMeNot(PrintMeNot)); 2256 2257 private: 2258 GTEST_DISALLOW_COPY_AND_ASSIGN_(LogTestHelper); 2259 }; 2260 2261 class GMockLogTest : public VerboseFlagPreservingFixture { 2262 protected: 2263 LogTestHelper helper_; 2264 }; 2265 2266 TEST_F(GMockLogTest, DoesNotPrintGoodCallInternallyIfVerbosityIsWarning) { 2267 GMOCK_FLAG(verbose) = kWarningVerbosity; 2268 EXPECT_CALL(helper_, Foo(_)) 2269 .WillOnce(Return(PrintMeNot())); 2270 helper_.Foo(PrintMeNot()); // This is an expected call. 2271 } 2272 2273 TEST_F(GMockLogTest, DoesNotPrintGoodCallInternallyIfVerbosityIsError) { 2274 GMOCK_FLAG(verbose) = kErrorVerbosity; 2275 EXPECT_CALL(helper_, Foo(_)) 2276 .WillOnce(Return(PrintMeNot())); 2277 helper_.Foo(PrintMeNot()); // This is an expected call. 2278 } 2279 2280 TEST_F(GMockLogTest, DoesNotPrintWarningInternallyIfVerbosityIsError) { 2281 GMOCK_FLAG(verbose) = kErrorVerbosity; 2282 ON_CALL(helper_, Foo(_)) 2283 .WillByDefault(Return(PrintMeNot())); 2284 helper_.Foo(PrintMeNot()); // This should generate a warning. 2285 } 2286 2287 // Tests Mock::AllowLeak(). 2288 2289 TEST(AllowLeakTest, AllowsLeakingUnusedMockObject) { 2290 MockA* a = new MockA; 2291 Mock::AllowLeak(a); 2292 } 2293 2294 TEST(AllowLeakTest, CanBeCalledBeforeOnCall) { 2295 MockA* a = new MockA; 2296 Mock::AllowLeak(a); 2297 ON_CALL(*a, DoA(_)).WillByDefault(Return()); 2298 a->DoA(0); 2299 } 2300 2301 TEST(AllowLeakTest, CanBeCalledAfterOnCall) { 2302 MockA* a = new MockA; 2303 ON_CALL(*a, DoA(_)).WillByDefault(Return()); 2304 Mock::AllowLeak(a); 2305 } 2306 2307 TEST(AllowLeakTest, CanBeCalledBeforeExpectCall) { 2308 MockA* a = new MockA; 2309 Mock::AllowLeak(a); 2310 EXPECT_CALL(*a, DoA(_)); 2311 a->DoA(0); 2312 } 2313 2314 TEST(AllowLeakTest, CanBeCalledAfterExpectCall) { 2315 MockA* a = new MockA; 2316 EXPECT_CALL(*a, DoA(_)).Times(AnyNumber()); 2317 Mock::AllowLeak(a); 2318 } 2319 2320 TEST(AllowLeakTest, WorksWhenBothOnCallAndExpectCallArePresent) { 2321 MockA* a = new MockA; 2322 ON_CALL(*a, DoA(_)).WillByDefault(Return()); 2323 EXPECT_CALL(*a, DoA(_)).Times(AnyNumber()); 2324 Mock::AllowLeak(a); 2325 } 2326 2327 // Tests that we can verify and clear a mock object's expectations 2328 // when none of its methods has expectations. 2329 TEST(VerifyAndClearExpectationsTest, NoMethodHasExpectations) { 2330 MockB b; 2331 ASSERT_TRUE(Mock::VerifyAndClearExpectations(&b)); 2332 2333 // There should be no expectations on the methods now, so we can 2334 // freely call them. 2335 EXPECT_EQ(0, b.DoB()); 2336 EXPECT_EQ(0, b.DoB(1)); 2337 } 2338 2339 // Tests that we can verify and clear a mock object's expectations 2340 // when some, but not all, of its methods have expectations *and* the 2341 // verification succeeds. 2342 TEST(VerifyAndClearExpectationsTest, SomeMethodsHaveExpectationsAndSucceed) { 2343 MockB b; 2344 EXPECT_CALL(b, DoB()) 2345 .WillOnce(Return(1)); 2346 b.DoB(); 2347 ASSERT_TRUE(Mock::VerifyAndClearExpectations(&b)); 2348 2349 // There should be no expectations on the methods now, so we can 2350 // freely call them. 2351 EXPECT_EQ(0, b.DoB()); 2352 EXPECT_EQ(0, b.DoB(1)); 2353 } 2354 2355 // Tests that we can verify and clear a mock object's expectations 2356 // when some, but not all, of its methods have expectations *and* the 2357 // verification fails. 2358 TEST(VerifyAndClearExpectationsTest, SomeMethodsHaveExpectationsAndFail) { 2359 MockB b; 2360 EXPECT_CALL(b, DoB()) 2361 .WillOnce(Return(1)); 2362 bool result = true; 2363 EXPECT_NONFATAL_FAILURE(result = Mock::VerifyAndClearExpectations(&b), 2364 "Actual: never called"); 2365 ASSERT_FALSE(result); 2366 2367 // There should be no expectations on the methods now, so we can 2368 // freely call them. 2369 EXPECT_EQ(0, b.DoB()); 2370 EXPECT_EQ(0, b.DoB(1)); 2371 } 2372 2373 // Tests that we can verify and clear a mock object's expectations 2374 // when all of its methods have expectations. 2375 TEST(VerifyAndClearExpectationsTest, AllMethodsHaveExpectations) { 2376 MockB b; 2377 EXPECT_CALL(b, DoB()) 2378 .WillOnce(Return(1)); 2379 EXPECT_CALL(b, DoB(_)) 2380 .WillOnce(Return(2)); 2381 b.DoB(); 2382 b.DoB(1); 2383 ASSERT_TRUE(Mock::VerifyAndClearExpectations(&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 verify and clear a mock object's expectations 2392 // when a method has more than one expectation. 2393 TEST(VerifyAndClearExpectationsTest, AMethodHasManyExpectations) { 2394 MockB b; 2395 EXPECT_CALL(b, DoB(0)) 2396 .WillOnce(Return(1)); 2397 EXPECT_CALL(b, DoB(_)) 2398 .WillOnce(Return(2)); 2399 b.DoB(1); 2400 bool result = true; 2401 EXPECT_NONFATAL_FAILURE(result = Mock::VerifyAndClearExpectations(&b), 2402 "Actual: never called"); 2403 ASSERT_FALSE(result); 2404 2405 // There should be no expectations on the methods now, so we can 2406 // freely call them. 2407 EXPECT_EQ(0, b.DoB()); 2408 EXPECT_EQ(0, b.DoB(1)); 2409 } 2410 2411 // Tests that we can call VerifyAndClearExpectations() on the same 2412 // mock object multiple times. 2413 TEST(VerifyAndClearExpectationsTest, CanCallManyTimes) { 2414 MockB b; 2415 EXPECT_CALL(b, DoB()); 2416 b.DoB(); 2417 Mock::VerifyAndClearExpectations(&b); 2418 2419 EXPECT_CALL(b, DoB(_)) 2420 .WillOnce(Return(1)); 2421 b.DoB(1); 2422 Mock::VerifyAndClearExpectations(&b); 2423 Mock::VerifyAndClearExpectations(&b); 2424 2425 // There should be no expectations on the methods now, so we can 2426 // freely call them. 2427 EXPECT_EQ(0, b.DoB()); 2428 EXPECT_EQ(0, b.DoB(1)); 2429 } 2430 2431 // Tests that we can clear a mock object's default actions when none 2432 // of its methods has default actions. 2433 TEST(VerifyAndClearTest, NoMethodHasDefaultActions) { 2434 MockB b; 2435 // If this crashes or generates a failure, the test will catch it. 2436 Mock::VerifyAndClear(&b); 2437 EXPECT_EQ(0, b.DoB()); 2438 } 2439 2440 // Tests that we can clear a mock object's default actions when some, 2441 // but not all of its methods have default actions. 2442 TEST(VerifyAndClearTest, SomeMethodsHaveDefaultActions) { 2443 MockB b; 2444 ON_CALL(b, DoB()) 2445 .WillByDefault(Return(1)); 2446 2447 Mock::VerifyAndClear(&b); 2448 2449 // Verifies that the default action of int DoB() was removed. 2450 EXPECT_EQ(0, b.DoB()); 2451 } 2452 2453 // Tests that we can clear a mock object's default actions when all of 2454 // its methods have default actions. 2455 TEST(VerifyAndClearTest, AllMethodsHaveDefaultActions) { 2456 MockB b; 2457 ON_CALL(b, DoB()) 2458 .WillByDefault(Return(1)); 2459 ON_CALL(b, DoB(_)) 2460 .WillByDefault(Return(2)); 2461 2462 Mock::VerifyAndClear(&b); 2463 2464 // Verifies that the default action of int DoB() was removed. 2465 EXPECT_EQ(0, b.DoB()); 2466 2467 // Verifies that the default action of int DoB(int) was removed. 2468 EXPECT_EQ(0, b.DoB(0)); 2469 } 2470 2471 // Tests that we can clear a mock object's default actions when a 2472 // method has more than one ON_CALL() set on it. 2473 TEST(VerifyAndClearTest, AMethodHasManyDefaultActions) { 2474 MockB b; 2475 ON_CALL(b, DoB(0)) 2476 .WillByDefault(Return(1)); 2477 ON_CALL(b, DoB(_)) 2478 .WillByDefault(Return(2)); 2479 2480 Mock::VerifyAndClear(&b); 2481 2482 // Verifies that the default actions (there are two) of int DoB(int) 2483 // were removed. 2484 EXPECT_EQ(0, b.DoB(0)); 2485 EXPECT_EQ(0, b.DoB(1)); 2486 } 2487 2488 // Tests that we can call VerifyAndClear() on a mock object multiple 2489 // times. 2490 TEST(VerifyAndClearTest, CanCallManyTimes) { 2491 MockB b; 2492 ON_CALL(b, DoB()) 2493 .WillByDefault(Return(1)); 2494 Mock::VerifyAndClear(&b); 2495 Mock::VerifyAndClear(&b); 2496 2497 ON_CALL(b, DoB(_)) 2498 .WillByDefault(Return(1)); 2499 Mock::VerifyAndClear(&b); 2500 2501 EXPECT_EQ(0, b.DoB()); 2502 EXPECT_EQ(0, b.DoB(1)); 2503 } 2504 2505 // Tests that VerifyAndClear() works when the verification succeeds. 2506 TEST(VerifyAndClearTest, Success) { 2507 MockB b; 2508 ON_CALL(b, DoB()) 2509 .WillByDefault(Return(1)); 2510 EXPECT_CALL(b, DoB(1)) 2511 .WillOnce(Return(2)); 2512 2513 b.DoB(); 2514 b.DoB(1); 2515 ASSERT_TRUE(Mock::VerifyAndClear(&b)); 2516 2517 // There should be no expectations on the methods now, so we can 2518 // freely call them. 2519 EXPECT_EQ(0, b.DoB()); 2520 EXPECT_EQ(0, b.DoB(1)); 2521 } 2522 2523 // Tests that VerifyAndClear() works when the verification fails. 2524 TEST(VerifyAndClearTest, Failure) { 2525 MockB b; 2526 ON_CALL(b, DoB(_)) 2527 .WillByDefault(Return(1)); 2528 EXPECT_CALL(b, DoB()) 2529 .WillOnce(Return(2)); 2530 2531 b.DoB(1); 2532 bool result = true; 2533 EXPECT_NONFATAL_FAILURE(result = Mock::VerifyAndClear(&b), 2534 "Actual: never called"); 2535 ASSERT_FALSE(result); 2536 2537 // There should be no expectations on the methods now, so we can 2538 // freely call them. 2539 EXPECT_EQ(0, b.DoB()); 2540 EXPECT_EQ(0, b.DoB(1)); 2541 } 2542 2543 // Tests that VerifyAndClear() works when the default actions and 2544 // expectations are set on a const mock object. 2545 TEST(VerifyAndClearTest, Const) { 2546 MockB b; 2547 ON_CALL(Const(b), DoB()) 2548 .WillByDefault(Return(1)); 2549 2550 EXPECT_CALL(Const(b), DoB()) 2551 .WillOnce(DoDefault()) 2552 .WillOnce(Return(2)); 2553 2554 b.DoB(); 2555 b.DoB(); 2556 ASSERT_TRUE(Mock::VerifyAndClear(&b)); 2557 2558 // There should be no expectations on the methods now, so we can 2559 // freely call them. 2560 EXPECT_EQ(0, b.DoB()); 2561 EXPECT_EQ(0, b.DoB(1)); 2562 } 2563 2564 // Tests that we can set default actions and expectations on a mock 2565 // object after VerifyAndClear() has been called on it. 2566 TEST(VerifyAndClearTest, CanSetDefaultActionsAndExpectationsAfterwards) { 2567 MockB b; 2568 ON_CALL(b, DoB()) 2569 .WillByDefault(Return(1)); 2570 EXPECT_CALL(b, DoB(_)) 2571 .WillOnce(Return(2)); 2572 b.DoB(1); 2573 2574 Mock::VerifyAndClear(&b); 2575 2576 EXPECT_CALL(b, DoB()) 2577 .WillOnce(Return(3)); 2578 ON_CALL(b, DoB(_)) 2579 .WillByDefault(Return(4)); 2580 2581 EXPECT_EQ(3, b.DoB()); 2582 EXPECT_EQ(4, b.DoB(1)); 2583 } 2584 2585 // Tests that calling VerifyAndClear() on one mock object does not 2586 // affect other mock objects (either of the same type or not). 2587 TEST(VerifyAndClearTest, DoesNotAffectOtherMockObjects) { 2588 MockA a; 2589 MockB b1; 2590 MockB b2; 2591 2592 ON_CALL(a, Binary(_, _)) 2593 .WillByDefault(Return(true)); 2594 EXPECT_CALL(a, Binary(_, _)) 2595 .WillOnce(DoDefault()) 2596 .WillOnce(Return(false)); 2597 2598 ON_CALL(b1, DoB()) 2599 .WillByDefault(Return(1)); 2600 EXPECT_CALL(b1, DoB(_)) 2601 .WillOnce(Return(2)); 2602 2603 ON_CALL(b2, DoB()) 2604 .WillByDefault(Return(3)); 2605 EXPECT_CALL(b2, DoB(_)); 2606 2607 b2.DoB(0); 2608 Mock::VerifyAndClear(&b2); 2609 2610 // Verifies that the default actions and expectations of a and b1 2611 // are still in effect. 2612 EXPECT_TRUE(a.Binary(0, 0)); 2613 EXPECT_FALSE(a.Binary(0, 0)); 2614 2615 EXPECT_EQ(1, b1.DoB()); 2616 EXPECT_EQ(2, b1.DoB(0)); 2617 } 2618 2619 TEST(VerifyAndClearTest, 2620 DestroyingChainedMocksDoesNotDeadlockThroughExpectations) { 2621 linked_ptr<MockA> a(new MockA); 2622 ReferenceHoldingMock test_mock; 2623 2624 // EXPECT_CALL stores a reference to a inside test_mock. 2625 EXPECT_CALL(test_mock, AcceptReference(_)) 2626 .WillRepeatedly(SetArgPointee<0>(a)); 2627 2628 // Throw away the reference to the mock that we have in a. After this, the 2629 // only reference to it is stored by test_mock. 2630 a.reset(); 2631 2632 // When test_mock goes out of scope, it destroys the last remaining reference 2633 // to the mock object originally pointed to by a. This will cause the MockA 2634 // destructor to be called from inside the ReferenceHoldingMock destructor. 2635 // The state of all mocks is protected by a single global lock, but there 2636 // should be no deadlock. 2637 } 2638 2639 TEST(VerifyAndClearTest, 2640 DestroyingChainedMocksDoesNotDeadlockThroughDefaultAction) { 2641 linked_ptr<MockA> a(new MockA); 2642 ReferenceHoldingMock test_mock; 2643 2644 // ON_CALL stores a reference to a inside test_mock. 2645 ON_CALL(test_mock, AcceptReference(_)) 2646 .WillByDefault(SetArgPointee<0>(a)); 2647 2648 // Throw away the reference to the mock that we have in a. After this, the 2649 // only reference to it is stored by test_mock. 2650 a.reset(); 2651 2652 // When test_mock goes out of scope, it destroys the last remaining reference 2653 // to the mock object originally pointed to by a. This will cause the MockA 2654 // destructor to be called from inside the ReferenceHoldingMock destructor. 2655 // The state of all mocks is protected by a single global lock, but there 2656 // should be no deadlock. 2657 } 2658 2659 // Tests that a mock function's action can call a mock function 2660 // (either the same function or a different one) either as an explicit 2661 // action or as a default action without causing a dead lock. It 2662 // verifies that the action is not performed inside the critical 2663 // section. 2664 TEST(SynchronizationTest, CanCallMockMethodInAction) { 2665 MockA a; 2666 MockC c; 2667 ON_CALL(a, DoA(_)) 2668 .WillByDefault(IgnoreResult(InvokeWithoutArgs(&c, 2669 &MockC::NonVoidMethod))); 2670 EXPECT_CALL(a, DoA(1)); 2671 EXPECT_CALL(a, DoA(1)) 2672 .WillOnce(Invoke(&a, &MockA::DoA)) 2673 .RetiresOnSaturation(); 2674 EXPECT_CALL(c, NonVoidMethod()); 2675 2676 a.DoA(1); 2677 // This will match the second EXPECT_CALL() and trigger another a.DoA(1), 2678 // which will in turn match the first EXPECT_CALL() and trigger a call to 2679 // c.NonVoidMethod() that was specified by the ON_CALL() since the first 2680 // EXPECT_CALL() did not specify an action. 2681 } 2682 2683 } // namespace 2684 2685 // Allows the user to define their own main and then invoke gmock_main 2686 // from it. This might be necessary on some platforms which require 2687 // specific setup and teardown. 2688 #if GMOCK_RENAME_MAIN 2689 int gmock_main(int argc, char **argv) { 2690 #else 2691 int main(int argc, char **argv) { 2692 #endif // GMOCK_RENAME_MAIN 2693 testing::InitGoogleMock(&argc, argv); 2694 2695 // Ensures that the tests pass no matter what value of 2696 // --gmock_catch_leaked_mocks and --gmock_verbose the user specifies. 2697 testing::GMOCK_FLAG(catch_leaked_mocks) = true; 2698 testing::GMOCK_FLAG(verbose) = testing::internal::kWarningVerbosity; 2699 2700 return RUN_ALL_TESTS(); 2701 } 2702