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 31// Google Mock - a framework for writing C++ mock classes. 32// 33// This file tests the spec builder syntax. 34 35#include "gmock/gmock-spec-builders.h" 36 37#include <ostream> // NOLINT 38#include <sstream> 39#include <string> 40 41#include "gmock/gmock.h" 42#include "gmock/internal/gmock-port.h" 43#include "gtest/gtest.h" 44#include "gtest/gtest-spi.h" 45#include "gtest/internal/gtest-port.h" 46 47namespace testing { 48namespace internal { 49 50// Helper class for testing the Expectation class template. 51class ExpectationTester { 52 public: 53 // Sets the call count of the given expectation to the given number. 54 void SetCallCount(int n, ExpectationBase* exp) { 55 exp->call_count_ = n; 56 } 57}; 58 59} // namespace internal 60} // namespace testing 61 62namespace { 63 64using testing::_; 65using testing::AnyNumber; 66using testing::AtLeast; 67using testing::AtMost; 68using testing::Between; 69using testing::Cardinality; 70using testing::CardinalityInterface; 71using testing::ContainsRegex; 72using testing::Const; 73using testing::DoAll; 74using testing::DoDefault; 75using testing::Eq; 76using testing::Expectation; 77using testing::ExpectationSet; 78using testing::GMOCK_FLAG(verbose); 79using testing::Gt; 80using testing::InSequence; 81using testing::Invoke; 82using testing::InvokeWithoutArgs; 83using testing::IsNotSubstring; 84using testing::IsSubstring; 85using testing::Lt; 86using testing::Message; 87using testing::Mock; 88using testing::NaggyMock; 89using testing::Ne; 90using testing::Return; 91using testing::SaveArg; 92using testing::Sequence; 93using testing::SetArgPointee; 94using testing::internal::ExpectationTester; 95using testing::internal::FormatFileLocation; 96using testing::internal::kAllow; 97using testing::internal::kErrorVerbosity; 98using testing::internal::kFail; 99using testing::internal::kInfoVerbosity; 100using testing::internal::kWarn; 101using testing::internal::kWarningVerbosity; 102using testing::internal::linked_ptr; 103 104#if GTEST_HAS_STREAM_REDIRECTION 105using testing::HasSubstr; 106using testing::internal::CaptureStdout; 107using testing::internal::GetCapturedStdout; 108#endif 109 110class Incomplete { 111}; 112 113class MockIncomplete { 114 public: 115 // This line verifies that a mock method can take a by-reference 116 // argument of an incomplete type. 117 MOCK_METHOD1(ByRefFunc, void(const Incomplete& x)); 118}; 119 120// Tells Google Mock how to print a value of type Incomplete. 121void PrintTo(const Incomplete& x, ::std::ostream* os); 122 123TEST(MockMethodTest, CanInstantiateWithIncompleteArgType) { 124 // Even though this mock class contains a mock method that takes 125 // by-reference an argument whose type is incomplete, we can still 126 // use the mock, as long as Google Mock knows how to print the 127 // argument. 128 MockIncomplete incomplete; 129 EXPECT_CALL(incomplete, ByRefFunc(_)) 130 .Times(AnyNumber()); 131} 132 133// The definition of the printer for the argument type doesn't have to 134// be visible where the mock is used. 135void PrintTo(const Incomplete& /* x */, ::std::ostream* os) { 136 *os << "incomplete"; 137} 138 139class Result {}; 140 141// A type that's not default constructible. 142class NonDefaultConstructible { 143 public: 144 explicit NonDefaultConstructible(int /* dummy */) {} 145}; 146 147class MockA { 148 public: 149 MockA() {} 150 151 MOCK_METHOD1(DoA, void(int n)); 152 MOCK_METHOD1(ReturnResult, Result(int n)); 153 MOCK_METHOD0(ReturnNonDefaultConstructible, NonDefaultConstructible()); 154 MOCK_METHOD2(Binary, bool(int x, int y)); 155 MOCK_METHOD2(ReturnInt, int(int x, int y)); 156 157 private: 158 GTEST_DISALLOW_COPY_AND_ASSIGN_(MockA); 159}; 160 161class MockB { 162 public: 163 MockB() {} 164 165 MOCK_CONST_METHOD0(DoB, int()); // NOLINT 166 MOCK_METHOD1(DoB, int(int n)); // NOLINT 167 168 private: 169 GTEST_DISALLOW_COPY_AND_ASSIGN_(MockB); 170}; 171 172class ReferenceHoldingMock { 173 public: 174 ReferenceHoldingMock() {} 175 176 MOCK_METHOD1(AcceptReference, void(linked_ptr<MockA>*)); 177 178 private: 179 GTEST_DISALLOW_COPY_AND_ASSIGN_(ReferenceHoldingMock); 180}; 181 182// Tests that EXPECT_CALL and ON_CALL compile in a presence of macro 183// redefining a mock method name. This could happen, for example, when 184// the tested code #includes Win32 API headers which define many APIs 185// as macros, e.g. #define TextOut TextOutW. 186 187#define Method MethodW 188 189class CC { 190 public: 191 virtual ~CC() {} 192 virtual int Method() = 0; 193}; 194class MockCC : public CC { 195 public: 196 MockCC() {} 197 198 MOCK_METHOD0(Method, int()); 199 200 private: 201 GTEST_DISALLOW_COPY_AND_ASSIGN_(MockCC); 202}; 203 204// Tests that a method with expanded name compiles. 205TEST(OnCallSyntaxTest, CompilesWithMethodNameExpandedFromMacro) { 206 MockCC cc; 207 ON_CALL(cc, Method()); 208} 209 210// Tests that the method with expanded name not only compiles but runs 211// and returns a correct value, too. 212TEST(OnCallSyntaxTest, WorksWithMethodNameExpandedFromMacro) { 213 MockCC cc; 214 ON_CALL(cc, Method()).WillByDefault(Return(42)); 215 EXPECT_EQ(42, cc.Method()); 216} 217 218// Tests that a method with expanded name compiles. 219TEST(ExpectCallSyntaxTest, CompilesWithMethodNameExpandedFromMacro) { 220 MockCC cc; 221 EXPECT_CALL(cc, Method()); 222 cc.Method(); 223} 224 225// Tests that it works, too. 226TEST(ExpectCallSyntaxTest, WorksWithMethodNameExpandedFromMacro) { 227 MockCC cc; 228 EXPECT_CALL(cc, Method()).WillOnce(Return(42)); 229 EXPECT_EQ(42, cc.Method()); 230} 231 232#undef Method // Done with macro redefinition tests. 233 234// Tests that ON_CALL evaluates its arguments exactly once as promised 235// by Google Mock. 236TEST(OnCallSyntaxTest, EvaluatesFirstArgumentOnce) { 237 MockA a; 238 MockA* pa = &a; 239 240 ON_CALL(*pa++, DoA(_)); 241 EXPECT_EQ(&a + 1, pa); 242} 243 244TEST(OnCallSyntaxTest, EvaluatesSecondArgumentOnce) { 245 MockA a; 246 int n = 0; 247 248 ON_CALL(a, DoA(n++)); 249 EXPECT_EQ(1, n); 250} 251 252// Tests that the syntax of ON_CALL() is enforced at run time. 253 254TEST(OnCallSyntaxTest, WithIsOptional) { 255 MockA a; 256 257 ON_CALL(a, DoA(5)) 258 .WillByDefault(Return()); 259 ON_CALL(a, DoA(_)) 260 .With(_) 261 .WillByDefault(Return()); 262} 263 264TEST(OnCallSyntaxTest, WithCanAppearAtMostOnce) { 265 MockA a; 266 267 EXPECT_NONFATAL_FAILURE({ // NOLINT 268 ON_CALL(a, ReturnResult(_)) 269 .With(_) 270 .With(_) 271 .WillByDefault(Return(Result())); 272 }, ".With() cannot appear more than once in an ON_CALL()"); 273} 274 275TEST(OnCallSyntaxTest, WillByDefaultIsMandatory) { 276 MockA a; 277 278 EXPECT_DEATH_IF_SUPPORTED({ 279 ON_CALL(a, DoA(5)); 280 a.DoA(5); 281 }, ""); 282} 283 284TEST(OnCallSyntaxTest, WillByDefaultCanAppearAtMostOnce) { 285 MockA a; 286 287 EXPECT_NONFATAL_FAILURE({ // NOLINT 288 ON_CALL(a, DoA(5)) 289 .WillByDefault(Return()) 290 .WillByDefault(Return()); 291 }, ".WillByDefault() must appear exactly once in an ON_CALL()"); 292} 293 294// Tests that EXPECT_CALL evaluates its arguments exactly once as 295// promised by Google Mock. 296TEST(ExpectCallSyntaxTest, EvaluatesFirstArgumentOnce) { 297 MockA a; 298 MockA* pa = &a; 299 300 EXPECT_CALL(*pa++, DoA(_)); 301 a.DoA(0); 302 EXPECT_EQ(&a + 1, pa); 303} 304 305TEST(ExpectCallSyntaxTest, EvaluatesSecondArgumentOnce) { 306 MockA a; 307 int n = 0; 308 309 EXPECT_CALL(a, DoA(n++)); 310 a.DoA(0); 311 EXPECT_EQ(1, n); 312} 313 314// Tests that the syntax of EXPECT_CALL() is enforced at run time. 315 316TEST(ExpectCallSyntaxTest, WithIsOptional) { 317 MockA a; 318 319 EXPECT_CALL(a, DoA(5)) 320 .Times(0); 321 EXPECT_CALL(a, DoA(6)) 322 .With(_) 323 .Times(0); 324} 325 326TEST(ExpectCallSyntaxTest, WithCanAppearAtMostOnce) { 327 MockA a; 328 329 EXPECT_NONFATAL_FAILURE({ // NOLINT 330 EXPECT_CALL(a, DoA(6)) 331 .With(_) 332 .With(_); 333 }, ".With() cannot appear more than once in an EXPECT_CALL()"); 334 335 a.DoA(6); 336} 337 338TEST(ExpectCallSyntaxTest, WithMustBeFirstClause) { 339 MockA a; 340 341 EXPECT_NONFATAL_FAILURE({ // NOLINT 342 EXPECT_CALL(a, DoA(1)) 343 .Times(1) 344 .With(_); 345 }, ".With() must be the first clause in an EXPECT_CALL()"); 346 347 a.DoA(1); 348 349 EXPECT_NONFATAL_FAILURE({ // NOLINT 350 EXPECT_CALL(a, DoA(2)) 351 .WillOnce(Return()) 352 .With(_); 353 }, ".With() must be the first clause in an EXPECT_CALL()"); 354 355 a.DoA(2); 356} 357 358TEST(ExpectCallSyntaxTest, TimesCanBeInferred) { 359 MockA a; 360 361 EXPECT_CALL(a, DoA(1)) 362 .WillOnce(Return()); 363 364 EXPECT_CALL(a, DoA(2)) 365 .WillOnce(Return()) 366 .WillRepeatedly(Return()); 367 368 a.DoA(1); 369 a.DoA(2); 370 a.DoA(2); 371} 372 373TEST(ExpectCallSyntaxTest, TimesCanAppearAtMostOnce) { 374 MockA a; 375 376 EXPECT_NONFATAL_FAILURE({ // NOLINT 377 EXPECT_CALL(a, DoA(1)) 378 .Times(1) 379 .Times(2); 380 }, ".Times() cannot appear more than once in an EXPECT_CALL()"); 381 382 a.DoA(1); 383 a.DoA(1); 384} 385 386TEST(ExpectCallSyntaxTest, TimesMustBeBeforeInSequence) { 387 MockA a; 388 Sequence s; 389 390 EXPECT_NONFATAL_FAILURE({ // NOLINT 391 EXPECT_CALL(a, DoA(1)) 392 .InSequence(s) 393 .Times(1); 394 }, ".Times() cannot appear after "); 395 396 a.DoA(1); 397} 398 399TEST(ExpectCallSyntaxTest, InSequenceIsOptional) { 400 MockA a; 401 Sequence s; 402 403 EXPECT_CALL(a, DoA(1)); 404 EXPECT_CALL(a, DoA(2)) 405 .InSequence(s); 406 407 a.DoA(1); 408 a.DoA(2); 409} 410 411TEST(ExpectCallSyntaxTest, InSequenceCanAppearMultipleTimes) { 412 MockA a; 413 Sequence s1, s2; 414 415 EXPECT_CALL(a, DoA(1)) 416 .InSequence(s1, s2) 417 .InSequence(s1); 418 419 a.DoA(1); 420} 421 422TEST(ExpectCallSyntaxTest, InSequenceMustBeBeforeAfter) { 423 MockA a; 424 Sequence s; 425 426 Expectation e = EXPECT_CALL(a, DoA(1)) 427 .Times(AnyNumber()); 428 EXPECT_NONFATAL_FAILURE({ // NOLINT 429 EXPECT_CALL(a, DoA(2)) 430 .After(e) 431 .InSequence(s); 432 }, ".InSequence() cannot appear after "); 433 434 a.DoA(2); 435} 436 437TEST(ExpectCallSyntaxTest, InSequenceMustBeBeforeWillOnce) { 438 MockA a; 439 Sequence s; 440 441 EXPECT_NONFATAL_FAILURE({ // NOLINT 442 EXPECT_CALL(a, DoA(1)) 443 .WillOnce(Return()) 444 .InSequence(s); 445 }, ".InSequence() cannot appear after "); 446 447 a.DoA(1); 448} 449 450TEST(ExpectCallSyntaxTest, AfterMustBeBeforeWillOnce) { 451 MockA a; 452 453 Expectation e = EXPECT_CALL(a, DoA(1)); 454 EXPECT_NONFATAL_FAILURE({ 455 EXPECT_CALL(a, DoA(2)) 456 .WillOnce(Return()) 457 .After(e); 458 }, ".After() cannot appear after "); 459 460 a.DoA(1); 461 a.DoA(2); 462} 463 464TEST(ExpectCallSyntaxTest, WillIsOptional) { 465 MockA a; 466 467 EXPECT_CALL(a, DoA(1)); 468 EXPECT_CALL(a, DoA(2)) 469 .WillOnce(Return()); 470 471 a.DoA(1); 472 a.DoA(2); 473} 474 475TEST(ExpectCallSyntaxTest, WillCanAppearMultipleTimes) { 476 MockA a; 477 478 EXPECT_CALL(a, DoA(1)) 479 .Times(AnyNumber()) 480 .WillOnce(Return()) 481 .WillOnce(Return()) 482 .WillOnce(Return()); 483} 484 485TEST(ExpectCallSyntaxTest, WillMustBeBeforeWillRepeatedly) { 486 MockA a; 487 488 EXPECT_NONFATAL_FAILURE({ // NOLINT 489 EXPECT_CALL(a, DoA(1)) 490 .WillRepeatedly(Return()) 491 .WillOnce(Return()); 492 }, ".WillOnce() cannot appear after "); 493 494 a.DoA(1); 495} 496 497TEST(ExpectCallSyntaxTest, WillRepeatedlyIsOptional) { 498 MockA a; 499 500 EXPECT_CALL(a, DoA(1)) 501 .WillOnce(Return()); 502 EXPECT_CALL(a, DoA(2)) 503 .WillOnce(Return()) 504 .WillRepeatedly(Return()); 505 506 a.DoA(1); 507 a.DoA(2); 508 a.DoA(2); 509} 510 511TEST(ExpectCallSyntaxTest, WillRepeatedlyCannotAppearMultipleTimes) { 512 MockA a; 513 514 EXPECT_NONFATAL_FAILURE({ // NOLINT 515 EXPECT_CALL(a, DoA(1)) 516 .WillRepeatedly(Return()) 517 .WillRepeatedly(Return()); 518 }, ".WillRepeatedly() cannot appear more than once in an " 519 "EXPECT_CALL()"); 520} 521 522TEST(ExpectCallSyntaxTest, WillRepeatedlyMustBeBeforeRetiresOnSaturation) { 523 MockA a; 524 525 EXPECT_NONFATAL_FAILURE({ // NOLINT 526 EXPECT_CALL(a, DoA(1)) 527 .RetiresOnSaturation() 528 .WillRepeatedly(Return()); 529 }, ".WillRepeatedly() cannot appear after "); 530} 531 532TEST(ExpectCallSyntaxTest, RetiresOnSaturationIsOptional) { 533 MockA a; 534 535 EXPECT_CALL(a, DoA(1)); 536 EXPECT_CALL(a, DoA(1)) 537 .RetiresOnSaturation(); 538 539 a.DoA(1); 540 a.DoA(1); 541} 542 543TEST(ExpectCallSyntaxTest, RetiresOnSaturationCannotAppearMultipleTimes) { 544 MockA a; 545 546 EXPECT_NONFATAL_FAILURE({ // NOLINT 547 EXPECT_CALL(a, DoA(1)) 548 .RetiresOnSaturation() 549 .RetiresOnSaturation(); 550 }, ".RetiresOnSaturation() cannot appear more than once"); 551 552 a.DoA(1); 553} 554 555TEST(ExpectCallSyntaxTest, DefaultCardinalityIsOnce) { 556 { 557 MockA a; 558 EXPECT_CALL(a, DoA(1)); 559 a.DoA(1); 560 } 561 EXPECT_NONFATAL_FAILURE({ // NOLINT 562 MockA a; 563 EXPECT_CALL(a, DoA(1)); 564 }, "to be called once"); 565 EXPECT_NONFATAL_FAILURE({ // NOLINT 566 MockA a; 567 EXPECT_CALL(a, DoA(1)); 568 a.DoA(1); 569 a.DoA(1); 570 }, "to be called once"); 571} 572 573#if GTEST_HAS_STREAM_REDIRECTION 574 575// Tests that Google Mock doesn't print a warning when the number of 576// WillOnce() is adequate. 577TEST(ExpectCallSyntaxTest, DoesNotWarnOnAdequateActionCount) { 578 CaptureStdout(); 579 { 580 MockB b; 581 582 // It's always fine to omit WillOnce() entirely. 583 EXPECT_CALL(b, DoB()) 584 .Times(0); 585 EXPECT_CALL(b, DoB(1)) 586 .Times(AtMost(1)); 587 EXPECT_CALL(b, DoB(2)) 588 .Times(1) 589 .WillRepeatedly(Return(1)); 590 591 // It's fine for the number of WillOnce()s to equal the upper bound. 592 EXPECT_CALL(b, DoB(3)) 593 .Times(Between(1, 2)) 594 .WillOnce(Return(1)) 595 .WillOnce(Return(2)); 596 597 // It's fine for the number of WillOnce()s to be smaller than the 598 // upper bound when there is a WillRepeatedly(). 599 EXPECT_CALL(b, DoB(4)) 600 .Times(AtMost(3)) 601 .WillOnce(Return(1)) 602 .WillRepeatedly(Return(2)); 603 604 // Satisfies the above expectations. 605 b.DoB(2); 606 b.DoB(3); 607 } 608 EXPECT_STREQ("", GetCapturedStdout().c_str()); 609} 610 611// Tests that Google Mock warns on having too many actions in an 612// expectation compared to its cardinality. 613TEST(ExpectCallSyntaxTest, WarnsOnTooManyActions) { 614 CaptureStdout(); 615 { 616 MockB b; 617 618 // Warns when the number of WillOnce()s is larger than the upper bound. 619 EXPECT_CALL(b, DoB()) 620 .Times(0) 621 .WillOnce(Return(1)); // #1 622 EXPECT_CALL(b, DoB()) 623 .Times(AtMost(1)) 624 .WillOnce(Return(1)) 625 .WillOnce(Return(2)); // #2 626 EXPECT_CALL(b, DoB(1)) 627 .Times(1) 628 .WillOnce(Return(1)) 629 .WillOnce(Return(2)) 630 .RetiresOnSaturation(); // #3 631 632 // Warns when the number of WillOnce()s equals the upper bound and 633 // there is a WillRepeatedly(). 634 EXPECT_CALL(b, DoB()) 635 .Times(0) 636 .WillRepeatedly(Return(1)); // #4 637 EXPECT_CALL(b, DoB(2)) 638 .Times(1) 639 .WillOnce(Return(1)) 640 .WillRepeatedly(Return(2)); // #5 641 642 // Satisfies the above expectations. 643 b.DoB(1); 644 b.DoB(2); 645 } 646 const std::string output = GetCapturedStdout(); 647 EXPECT_PRED_FORMAT2( 648 IsSubstring, 649 "Too many actions specified in EXPECT_CALL(b, DoB())...\n" 650 "Expected to be never called, but has 1 WillOnce().", 651 output); // #1 652 EXPECT_PRED_FORMAT2( 653 IsSubstring, 654 "Too many actions specified in EXPECT_CALL(b, DoB())...\n" 655 "Expected to be called at most once, " 656 "but has 2 WillOnce()s.", 657 output); // #2 658 EXPECT_PRED_FORMAT2( 659 IsSubstring, 660 "Too many actions specified in EXPECT_CALL(b, DoB(1))...\n" 661 "Expected to be called once, but has 2 WillOnce()s.", 662 output); // #3 663 EXPECT_PRED_FORMAT2( 664 IsSubstring, 665 "Too many actions specified in EXPECT_CALL(b, DoB())...\n" 666 "Expected to be never called, but has 0 WillOnce()s " 667 "and a WillRepeatedly().", 668 output); // #4 669 EXPECT_PRED_FORMAT2( 670 IsSubstring, 671 "Too many actions specified in EXPECT_CALL(b, DoB(2))...\n" 672 "Expected to be called once, but has 1 WillOnce() " 673 "and a WillRepeatedly().", 674 output); // #5 675} 676 677// Tests that Google Mock warns on having too few actions in an 678// expectation compared to its cardinality. 679TEST(ExpectCallSyntaxTest, WarnsOnTooFewActions) { 680 MockB b; 681 682 EXPECT_CALL(b, DoB()) 683 .Times(Between(2, 3)) 684 .WillOnce(Return(1)); 685 686 CaptureStdout(); 687 b.DoB(); 688 const std::string output = GetCapturedStdout(); 689 EXPECT_PRED_FORMAT2( 690 IsSubstring, 691 "Too few actions specified in EXPECT_CALL(b, DoB())...\n" 692 "Expected to be called between 2 and 3 times, " 693 "but has only 1 WillOnce().", 694 output); 695 b.DoB(); 696} 697 698TEST(ExpectCallSyntaxTest, WarningIsErrorWithFlag) { 699 int original_behavior = testing::GMOCK_FLAG(default_mock_behavior); 700 701 testing::GMOCK_FLAG(default_mock_behavior) = kAllow; 702 CaptureStdout(); 703 { 704 MockA a; 705 a.DoA(0); 706 } 707 std::string output = GetCapturedStdout(); 708 EXPECT_TRUE(output.empty()) << output; 709 710 testing::GMOCK_FLAG(default_mock_behavior) = kWarn; 711 CaptureStdout(); 712 { 713 MockA a; 714 a.DoA(0); 715 } 716 std::string warning_output = GetCapturedStdout(); 717 EXPECT_PRED_FORMAT2(IsSubstring, "GMOCK WARNING", warning_output); 718 EXPECT_PRED_FORMAT2(IsSubstring, "Uninteresting mock function call", 719 warning_output); 720 721 testing::GMOCK_FLAG(default_mock_behavior) = kFail; 722 EXPECT_NONFATAL_FAILURE({ 723 MockA a; 724 a.DoA(0); 725 }, "Uninteresting mock function call"); 726 727 // Out of bounds values are converted to kWarn 728 testing::GMOCK_FLAG(default_mock_behavior) = -1; 729 CaptureStdout(); 730 { 731 MockA a; 732 a.DoA(0); 733 } 734 warning_output = GetCapturedStdout(); 735 EXPECT_PRED_FORMAT2(IsSubstring, "GMOCK WARNING", warning_output); 736 EXPECT_PRED_FORMAT2(IsSubstring, "Uninteresting mock function call", 737 warning_output); 738 testing::GMOCK_FLAG(default_mock_behavior) = 3; 739 CaptureStdout(); 740 { 741 MockA a; 742 a.DoA(0); 743 } 744 warning_output = GetCapturedStdout(); 745 EXPECT_PRED_FORMAT2(IsSubstring, "GMOCK WARNING", warning_output); 746 EXPECT_PRED_FORMAT2(IsSubstring, "Uninteresting mock function call", 747 warning_output); 748 749 testing::GMOCK_FLAG(default_mock_behavior) = original_behavior; 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. 758TEST(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. 767TEST(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. 777TEST(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. 793TEST(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. 806TEST(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. 817TEST(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. 831TEST(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 863TEST(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. 894TEST(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. 908TEST(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(). 923TEST(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 954TEST(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 968TEST(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. 984TEST(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. 999TEST(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. 1025TEST(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. 1074TEST(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. 1094TEST(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. 1108TEST(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. 1121TEST(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 1176TEST(UndefinedReturnValueTest, 1177 ReturnValueIsMandatoryWhenNotDefaultConstructible) { 1178 MockA a; 1179 // FIXME: 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. 1191TEST(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. 1217TEST(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. 1231TEST(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 1247TEST(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 1264TEST(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 1287TEST(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. 1307TEST(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. 1335TEST(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. 1359TEST(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. 1378class 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 1406TEST_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 1417TEST_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 1427TEST_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 1437TEST_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 1447TEST(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 1466TEST(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 1498TEST(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 1513TEST(ExpectationSetTest, MemberTypesAreCorrect) { 1514 ::testing::StaticAssertTypeEq<Expectation, ExpectationSet::value_type>(); 1515} 1516 1517TEST(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 1546TEST(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 1556TEST(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 1576TEST(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 1590TEST(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 1604TEST(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 1617TEST(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(). 1635TEST(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(). 1657TEST(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. 1681TEST(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. 1703TEST(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(). 1724TEST(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. 1743TEST(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. 1760TEST(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. 1779TEST(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. 1806TEST(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. 1823TEST(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. 1851TEST(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 1883ACTION_P(Delete, ptr) { delete ptr; } 1884 1885#ifdef _MSC_VER 1886# pragma warning(pop) 1887#endif 1888 1889TEST(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 1895TEST(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. 1903TEST(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. 1929TEST(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 1953class 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 1971Cardinality EvenNumber() { 1972 return Cardinality(new EvenNumberCardinality); 1973} 1974 1975TEST(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 1998struct Printable { 1999}; 2000 2001inline void operator<<(::std::ostream& os, const Printable&) { 2002 os << "Printable"; 2003} 2004 2005struct Unprintable { 2006 Unprintable() : value(0) {} 2007 int value; 2008}; 2009 2010class 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 2022class 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. 2040TEST(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. 2054TEST(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. 2085TEST(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 2115class 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 " 2178 "https://github.com/google/googletest/blob/master/googlemock/docs/" 2179 "CookBook.md#" 2180 "knowing-when-to-expect for details."; 2181 2182 // A void-returning function. 2183 CaptureStdout(); 2184 a.DoA(5); 2185 VerifyOutput( 2186 GetCapturedStdout(), 2187 should_print, 2188 "\nGMOCK WARNING:\n" 2189 "Uninteresting mock function call - returning directly.\n" 2190 " Function call: DoA(5)\n" + 2191 note, 2192 "DoA"); 2193 2194 // A non-void-returning function. 2195 CaptureStdout(); 2196 a.Binary(2, 1); 2197 VerifyOutput( 2198 GetCapturedStdout(), 2199 should_print, 2200 "\nGMOCK WARNING:\n" 2201 "Uninteresting mock function call - returning default value.\n" 2202 " Function call: Binary(2, 1)\n" 2203 " Returns: false\n" + 2204 note, 2205 "Binary"); 2206 } 2207}; 2208 2209// Tests that --gmock_verbose=info causes both expected and 2210// uninteresting calls to be reported. 2211TEST_F(GMockVerboseFlagTest, Info) { 2212 GMOCK_FLAG(verbose) = kInfoVerbosity; 2213 TestExpectedCall(true); 2214 TestUninterestingCallOnNaggyMock(true); 2215} 2216 2217// Tests that --gmock_verbose=warning causes uninteresting calls to be 2218// reported. 2219TEST_F(GMockVerboseFlagTest, Warning) { 2220 GMOCK_FLAG(verbose) = kWarningVerbosity; 2221 TestExpectedCall(false); 2222 TestUninterestingCallOnNaggyMock(true); 2223} 2224 2225// Tests that --gmock_verbose=warning causes neither expected nor 2226// uninteresting calls to be reported. 2227TEST_F(GMockVerboseFlagTest, Error) { 2228 GMOCK_FLAG(verbose) = kErrorVerbosity; 2229 TestExpectedCall(false); 2230 TestUninterestingCallOnNaggyMock(false); 2231} 2232 2233// Tests that --gmock_verbose=SOME_INVALID_VALUE has the same effect 2234// as --gmock_verbose=warning. 2235TEST_F(GMockVerboseFlagTest, InvalidFlagIsTreatedAsWarning) { 2236 GMOCK_FLAG(verbose) = "invalid"; // Treated as "warning". 2237 TestExpectedCall(false); 2238 TestUninterestingCallOnNaggyMock(true); 2239} 2240 2241#endif // GTEST_HAS_STREAM_REDIRECTION 2242 2243// A helper class that generates a failure when printed. We use it to 2244// ensure that Google Mock doesn't print a value (even to an internal 2245// buffer) when it is not supposed to do so. 2246class PrintMeNot {}; 2247 2248void PrintTo(PrintMeNot /* dummy */, ::std::ostream* /* os */) { 2249 ADD_FAILURE() << "Google Mock is printing a value that shouldn't be " 2250 << "printed even to an internal buffer."; 2251} 2252 2253class LogTestHelper { 2254 public: 2255 LogTestHelper() {} 2256 2257 MOCK_METHOD1(Foo, PrintMeNot(PrintMeNot)); 2258 2259 private: 2260 GTEST_DISALLOW_COPY_AND_ASSIGN_(LogTestHelper); 2261}; 2262 2263class GMockLogTest : public VerboseFlagPreservingFixture { 2264 protected: 2265 LogTestHelper helper_; 2266}; 2267 2268TEST_F(GMockLogTest, DoesNotPrintGoodCallInternallyIfVerbosityIsWarning) { 2269 GMOCK_FLAG(verbose) = kWarningVerbosity; 2270 EXPECT_CALL(helper_, Foo(_)) 2271 .WillOnce(Return(PrintMeNot())); 2272 helper_.Foo(PrintMeNot()); // This is an expected call. 2273} 2274 2275TEST_F(GMockLogTest, DoesNotPrintGoodCallInternallyIfVerbosityIsError) { 2276 GMOCK_FLAG(verbose) = kErrorVerbosity; 2277 EXPECT_CALL(helper_, Foo(_)) 2278 .WillOnce(Return(PrintMeNot())); 2279 helper_.Foo(PrintMeNot()); // This is an expected call. 2280} 2281 2282TEST_F(GMockLogTest, DoesNotPrintWarningInternallyIfVerbosityIsError) { 2283 GMOCK_FLAG(verbose) = kErrorVerbosity; 2284 ON_CALL(helper_, Foo(_)) 2285 .WillByDefault(Return(PrintMeNot())); 2286 helper_.Foo(PrintMeNot()); // This should generate a warning. 2287} 2288 2289// Tests Mock::AllowLeak(). 2290 2291TEST(AllowLeakTest, AllowsLeakingUnusedMockObject) { 2292 MockA* a = new MockA; 2293 Mock::AllowLeak(a); 2294} 2295 2296TEST(AllowLeakTest, CanBeCalledBeforeOnCall) { 2297 MockA* a = new MockA; 2298 Mock::AllowLeak(a); 2299 ON_CALL(*a, DoA(_)).WillByDefault(Return()); 2300 a->DoA(0); 2301} 2302 2303TEST(AllowLeakTest, CanBeCalledAfterOnCall) { 2304 MockA* a = new MockA; 2305 ON_CALL(*a, DoA(_)).WillByDefault(Return()); 2306 Mock::AllowLeak(a); 2307} 2308 2309TEST(AllowLeakTest, CanBeCalledBeforeExpectCall) { 2310 MockA* a = new MockA; 2311 Mock::AllowLeak(a); 2312 EXPECT_CALL(*a, DoA(_)); 2313 a->DoA(0); 2314} 2315 2316TEST(AllowLeakTest, CanBeCalledAfterExpectCall) { 2317 MockA* a = new MockA; 2318 EXPECT_CALL(*a, DoA(_)).Times(AnyNumber()); 2319 Mock::AllowLeak(a); 2320} 2321 2322TEST(AllowLeakTest, WorksWhenBothOnCallAndExpectCallArePresent) { 2323 MockA* a = new MockA; 2324 ON_CALL(*a, DoA(_)).WillByDefault(Return()); 2325 EXPECT_CALL(*a, DoA(_)).Times(AnyNumber()); 2326 Mock::AllowLeak(a); 2327} 2328 2329// Tests that we can verify and clear a mock object's expectations 2330// when none of its methods has expectations. 2331TEST(VerifyAndClearExpectationsTest, NoMethodHasExpectations) { 2332 MockB b; 2333 ASSERT_TRUE(Mock::VerifyAndClearExpectations(&b)); 2334 2335 // There should be no expectations on the methods now, so we can 2336 // freely call them. 2337 EXPECT_EQ(0, b.DoB()); 2338 EXPECT_EQ(0, b.DoB(1)); 2339} 2340 2341// Tests that we can verify and clear a mock object's expectations 2342// when some, but not all, of its methods have expectations *and* the 2343// verification succeeds. 2344TEST(VerifyAndClearExpectationsTest, SomeMethodsHaveExpectationsAndSucceed) { 2345 MockB b; 2346 EXPECT_CALL(b, DoB()) 2347 .WillOnce(Return(1)); 2348 b.DoB(); 2349 ASSERT_TRUE(Mock::VerifyAndClearExpectations(&b)); 2350 2351 // There should be no expectations on the methods now, so we can 2352 // freely call them. 2353 EXPECT_EQ(0, b.DoB()); 2354 EXPECT_EQ(0, b.DoB(1)); 2355} 2356 2357// Tests that we can verify and clear a mock object's expectations 2358// when some, but not all, of its methods have expectations *and* the 2359// verification fails. 2360TEST(VerifyAndClearExpectationsTest, SomeMethodsHaveExpectationsAndFail) { 2361 MockB b; 2362 EXPECT_CALL(b, DoB()) 2363 .WillOnce(Return(1)); 2364 bool result = true; 2365 EXPECT_NONFATAL_FAILURE(result = Mock::VerifyAndClearExpectations(&b), 2366 "Actual: never called"); 2367 ASSERT_FALSE(result); 2368 2369 // There should be no expectations on the methods now, so we can 2370 // freely call them. 2371 EXPECT_EQ(0, b.DoB()); 2372 EXPECT_EQ(0, b.DoB(1)); 2373} 2374 2375// Tests that we can verify and clear a mock object's expectations 2376// when all of its methods have expectations. 2377TEST(VerifyAndClearExpectationsTest, AllMethodsHaveExpectations) { 2378 MockB b; 2379 EXPECT_CALL(b, DoB()) 2380 .WillOnce(Return(1)); 2381 EXPECT_CALL(b, DoB(_)) 2382 .WillOnce(Return(2)); 2383 b.DoB(); 2384 b.DoB(1); 2385 ASSERT_TRUE(Mock::VerifyAndClearExpectations(&b)); 2386 2387 // There should be no expectations on the methods now, so we can 2388 // freely call them. 2389 EXPECT_EQ(0, b.DoB()); 2390 EXPECT_EQ(0, b.DoB(1)); 2391} 2392 2393// Tests that we can verify and clear a mock object's expectations 2394// when a method has more than one expectation. 2395TEST(VerifyAndClearExpectationsTest, AMethodHasManyExpectations) { 2396 MockB b; 2397 EXPECT_CALL(b, DoB(0)) 2398 .WillOnce(Return(1)); 2399 EXPECT_CALL(b, DoB(_)) 2400 .WillOnce(Return(2)); 2401 b.DoB(1); 2402 bool result = true; 2403 EXPECT_NONFATAL_FAILURE(result = Mock::VerifyAndClearExpectations(&b), 2404 "Actual: never called"); 2405 ASSERT_FALSE(result); 2406 2407 // There should be no expectations on the methods now, so we can 2408 // freely call them. 2409 EXPECT_EQ(0, b.DoB()); 2410 EXPECT_EQ(0, b.DoB(1)); 2411} 2412 2413// Tests that we can call VerifyAndClearExpectations() on the same 2414// mock object multiple times. 2415TEST(VerifyAndClearExpectationsTest, CanCallManyTimes) { 2416 MockB b; 2417 EXPECT_CALL(b, DoB()); 2418 b.DoB(); 2419 Mock::VerifyAndClearExpectations(&b); 2420 2421 EXPECT_CALL(b, DoB(_)) 2422 .WillOnce(Return(1)); 2423 b.DoB(1); 2424 Mock::VerifyAndClearExpectations(&b); 2425 Mock::VerifyAndClearExpectations(&b); 2426 2427 // There should be no expectations on the methods now, so we can 2428 // freely call them. 2429 EXPECT_EQ(0, b.DoB()); 2430 EXPECT_EQ(0, b.DoB(1)); 2431} 2432 2433// Tests that we can clear a mock object's default actions when none 2434// of its methods has default actions. 2435TEST(VerifyAndClearTest, NoMethodHasDefaultActions) { 2436 MockB b; 2437 // If this crashes or generates a failure, the test will catch it. 2438 Mock::VerifyAndClear(&b); 2439 EXPECT_EQ(0, b.DoB()); 2440} 2441 2442// Tests that we can clear a mock object's default actions when some, 2443// but not all of its methods have default actions. 2444TEST(VerifyAndClearTest, SomeMethodsHaveDefaultActions) { 2445 MockB b; 2446 ON_CALL(b, DoB()) 2447 .WillByDefault(Return(1)); 2448 2449 Mock::VerifyAndClear(&b); 2450 2451 // Verifies that the default action of int DoB() was removed. 2452 EXPECT_EQ(0, b.DoB()); 2453} 2454 2455// Tests that we can clear a mock object's default actions when all of 2456// its methods have default actions. 2457TEST(VerifyAndClearTest, AllMethodsHaveDefaultActions) { 2458 MockB b; 2459 ON_CALL(b, DoB()) 2460 .WillByDefault(Return(1)); 2461 ON_CALL(b, DoB(_)) 2462 .WillByDefault(Return(2)); 2463 2464 Mock::VerifyAndClear(&b); 2465 2466 // Verifies that the default action of int DoB() was removed. 2467 EXPECT_EQ(0, b.DoB()); 2468 2469 // Verifies that the default action of int DoB(int) was removed. 2470 EXPECT_EQ(0, b.DoB(0)); 2471} 2472 2473// Tests that we can clear a mock object's default actions when a 2474// method has more than one ON_CALL() set on it. 2475TEST(VerifyAndClearTest, AMethodHasManyDefaultActions) { 2476 MockB b; 2477 ON_CALL(b, DoB(0)) 2478 .WillByDefault(Return(1)); 2479 ON_CALL(b, DoB(_)) 2480 .WillByDefault(Return(2)); 2481 2482 Mock::VerifyAndClear(&b); 2483 2484 // Verifies that the default actions (there are two) of int DoB(int) 2485 // were removed. 2486 EXPECT_EQ(0, b.DoB(0)); 2487 EXPECT_EQ(0, b.DoB(1)); 2488} 2489 2490// Tests that we can call VerifyAndClear() on a mock object multiple 2491// times. 2492TEST(VerifyAndClearTest, CanCallManyTimes) { 2493 MockB b; 2494 ON_CALL(b, DoB()) 2495 .WillByDefault(Return(1)); 2496 Mock::VerifyAndClear(&b); 2497 Mock::VerifyAndClear(&b); 2498 2499 ON_CALL(b, DoB(_)) 2500 .WillByDefault(Return(1)); 2501 Mock::VerifyAndClear(&b); 2502 2503 EXPECT_EQ(0, b.DoB()); 2504 EXPECT_EQ(0, b.DoB(1)); 2505} 2506 2507// Tests that VerifyAndClear() works when the verification succeeds. 2508TEST(VerifyAndClearTest, Success) { 2509 MockB b; 2510 ON_CALL(b, DoB()) 2511 .WillByDefault(Return(1)); 2512 EXPECT_CALL(b, DoB(1)) 2513 .WillOnce(Return(2)); 2514 2515 b.DoB(); 2516 b.DoB(1); 2517 ASSERT_TRUE(Mock::VerifyAndClear(&b)); 2518 2519 // There should be no expectations on the methods now, so we can 2520 // freely call them. 2521 EXPECT_EQ(0, b.DoB()); 2522 EXPECT_EQ(0, b.DoB(1)); 2523} 2524 2525// Tests that VerifyAndClear() works when the verification fails. 2526TEST(VerifyAndClearTest, Failure) { 2527 MockB b; 2528 ON_CALL(b, DoB(_)) 2529 .WillByDefault(Return(1)); 2530 EXPECT_CALL(b, DoB()) 2531 .WillOnce(Return(2)); 2532 2533 b.DoB(1); 2534 bool result = true; 2535 EXPECT_NONFATAL_FAILURE(result = Mock::VerifyAndClear(&b), 2536 "Actual: never called"); 2537 ASSERT_FALSE(result); 2538 2539 // There should be no expectations on the methods now, so we can 2540 // freely call them. 2541 EXPECT_EQ(0, b.DoB()); 2542 EXPECT_EQ(0, b.DoB(1)); 2543} 2544 2545// Tests that VerifyAndClear() works when the default actions and 2546// expectations are set on a const mock object. 2547TEST(VerifyAndClearTest, Const) { 2548 MockB b; 2549 ON_CALL(Const(b), DoB()) 2550 .WillByDefault(Return(1)); 2551 2552 EXPECT_CALL(Const(b), DoB()) 2553 .WillOnce(DoDefault()) 2554 .WillOnce(Return(2)); 2555 2556 b.DoB(); 2557 b.DoB(); 2558 ASSERT_TRUE(Mock::VerifyAndClear(&b)); 2559 2560 // There should be no expectations on the methods now, so we can 2561 // freely call them. 2562 EXPECT_EQ(0, b.DoB()); 2563 EXPECT_EQ(0, b.DoB(1)); 2564} 2565 2566// Tests that we can set default actions and expectations on a mock 2567// object after VerifyAndClear() has been called on it. 2568TEST(VerifyAndClearTest, CanSetDefaultActionsAndExpectationsAfterwards) { 2569 MockB b; 2570 ON_CALL(b, DoB()) 2571 .WillByDefault(Return(1)); 2572 EXPECT_CALL(b, DoB(_)) 2573 .WillOnce(Return(2)); 2574 b.DoB(1); 2575 2576 Mock::VerifyAndClear(&b); 2577 2578 EXPECT_CALL(b, DoB()) 2579 .WillOnce(Return(3)); 2580 ON_CALL(b, DoB(_)) 2581 .WillByDefault(Return(4)); 2582 2583 EXPECT_EQ(3, b.DoB()); 2584 EXPECT_EQ(4, b.DoB(1)); 2585} 2586 2587// Tests that calling VerifyAndClear() on one mock object does not 2588// affect other mock objects (either of the same type or not). 2589TEST(VerifyAndClearTest, DoesNotAffectOtherMockObjects) { 2590 MockA a; 2591 MockB b1; 2592 MockB b2; 2593 2594 ON_CALL(a, Binary(_, _)) 2595 .WillByDefault(Return(true)); 2596 EXPECT_CALL(a, Binary(_, _)) 2597 .WillOnce(DoDefault()) 2598 .WillOnce(Return(false)); 2599 2600 ON_CALL(b1, DoB()) 2601 .WillByDefault(Return(1)); 2602 EXPECT_CALL(b1, DoB(_)) 2603 .WillOnce(Return(2)); 2604 2605 ON_CALL(b2, DoB()) 2606 .WillByDefault(Return(3)); 2607 EXPECT_CALL(b2, DoB(_)); 2608 2609 b2.DoB(0); 2610 Mock::VerifyAndClear(&b2); 2611 2612 // Verifies that the default actions and expectations of a and b1 2613 // are still in effect. 2614 EXPECT_TRUE(a.Binary(0, 0)); 2615 EXPECT_FALSE(a.Binary(0, 0)); 2616 2617 EXPECT_EQ(1, b1.DoB()); 2618 EXPECT_EQ(2, b1.DoB(0)); 2619} 2620 2621TEST(VerifyAndClearTest, 2622 DestroyingChainedMocksDoesNotDeadlockThroughExpectations) { 2623 linked_ptr<MockA> a(new MockA); 2624 ReferenceHoldingMock test_mock; 2625 2626 // EXPECT_CALL stores a reference to a inside test_mock. 2627 EXPECT_CALL(test_mock, AcceptReference(_)) 2628 .WillRepeatedly(SetArgPointee<0>(a)); 2629 2630 // Throw away the reference to the mock that we have in a. After this, the 2631 // only reference to it is stored by test_mock. 2632 a.reset(); 2633 2634 // When test_mock goes out of scope, it destroys the last remaining reference 2635 // to the mock object originally pointed to by a. This will cause the MockA 2636 // destructor to be called from inside the ReferenceHoldingMock destructor. 2637 // The state of all mocks is protected by a single global lock, but there 2638 // should be no deadlock. 2639} 2640 2641TEST(VerifyAndClearTest, 2642 DestroyingChainedMocksDoesNotDeadlockThroughDefaultAction) { 2643 linked_ptr<MockA> a(new MockA); 2644 ReferenceHoldingMock test_mock; 2645 2646 // ON_CALL stores a reference to a inside test_mock. 2647 ON_CALL(test_mock, AcceptReference(_)) 2648 .WillByDefault(SetArgPointee<0>(a)); 2649 2650 // Throw away the reference to the mock that we have in a. After this, the 2651 // only reference to it is stored by test_mock. 2652 a.reset(); 2653 2654 // When test_mock goes out of scope, it destroys the last remaining reference 2655 // to the mock object originally pointed to by a. This will cause the MockA 2656 // destructor to be called from inside the ReferenceHoldingMock destructor. 2657 // The state of all mocks is protected by a single global lock, but there 2658 // should be no deadlock. 2659} 2660 2661// Tests that a mock function's action can call a mock function 2662// (either the same function or a different one) either as an explicit 2663// action or as a default action without causing a dead lock. It 2664// verifies that the action is not performed inside the critical 2665// section. 2666TEST(SynchronizationTest, CanCallMockMethodInAction) { 2667 MockA a; 2668 MockC c; 2669 ON_CALL(a, DoA(_)) 2670 .WillByDefault(IgnoreResult(InvokeWithoutArgs(&c, 2671 &MockC::NonVoidMethod))); 2672 EXPECT_CALL(a, DoA(1)); 2673 EXPECT_CALL(a, DoA(1)) 2674 .WillOnce(Invoke(&a, &MockA::DoA)) 2675 .RetiresOnSaturation(); 2676 EXPECT_CALL(c, NonVoidMethod()); 2677 2678 a.DoA(1); 2679 // This will match the second EXPECT_CALL() and trigger another a.DoA(1), 2680 // which will in turn match the first EXPECT_CALL() and trigger a call to 2681 // c.NonVoidMethod() that was specified by the ON_CALL() since the first 2682 // EXPECT_CALL() did not specify an action. 2683} 2684 2685TEST(ParameterlessExpectationsTest, CanSetExpectationsWithoutMatchers) { 2686 MockA a; 2687 int do_a_arg0 = 0; 2688 ON_CALL(a, DoA).WillByDefault(SaveArg<0>(&do_a_arg0)); 2689 int do_a_47_arg0 = 0; 2690 ON_CALL(a, DoA(47)).WillByDefault(SaveArg<0>(&do_a_47_arg0)); 2691 2692 a.DoA(17); 2693 EXPECT_THAT(do_a_arg0, 17); 2694 EXPECT_THAT(do_a_47_arg0, 0); 2695 a.DoA(47); 2696 EXPECT_THAT(do_a_arg0, 17); 2697 EXPECT_THAT(do_a_47_arg0, 47); 2698 2699 ON_CALL(a, Binary).WillByDefault(Return(true)); 2700 ON_CALL(a, Binary(_, 14)).WillByDefault(Return(false)); 2701 EXPECT_THAT(a.Binary(14, 17), true); 2702 EXPECT_THAT(a.Binary(17, 14), false); 2703} 2704 2705TEST(ParameterlessExpectationsTest, CanSetExpectationsForOverloadedMethods) { 2706 MockB b; 2707 ON_CALL(b, DoB()).WillByDefault(Return(9)); 2708 ON_CALL(b, DoB(5)).WillByDefault(Return(11)); 2709 2710 EXPECT_THAT(b.DoB(), 9); 2711 EXPECT_THAT(b.DoB(1), 0); // default value 2712 EXPECT_THAT(b.DoB(5), 11); 2713} 2714 2715struct MockWithConstMethods { 2716 public: 2717 MOCK_CONST_METHOD1(Foo, int(int)); 2718 MOCK_CONST_METHOD2(Bar, int(int, const char*)); 2719}; 2720 2721TEST(ParameterlessExpectationsTest, CanSetExpectationsForConstMethods) { 2722 MockWithConstMethods mock; 2723 ON_CALL(mock, Foo).WillByDefault(Return(7)); 2724 ON_CALL(mock, Bar).WillByDefault(Return(33)); 2725 2726 EXPECT_THAT(mock.Foo(17), 7); 2727 EXPECT_THAT(mock.Bar(27, "purple"), 33); 2728} 2729 2730class MockConstOverload { 2731 public: 2732 MOCK_METHOD1(Overloaded, int(int)); 2733 MOCK_CONST_METHOD1(Overloaded, int(int)); 2734}; 2735 2736TEST(ParameterlessExpectationsTest, 2737 CanSetExpectationsForConstOverloadedMethods) { 2738 MockConstOverload mock; 2739 ON_CALL(mock, Overloaded(_)).WillByDefault(Return(7)); 2740 ON_CALL(mock, Overloaded(5)).WillByDefault(Return(9)); 2741 ON_CALL(Const(mock), Overloaded(5)).WillByDefault(Return(11)); 2742 ON_CALL(Const(mock), Overloaded(7)).WillByDefault(Return(13)); 2743 2744 EXPECT_THAT(mock.Overloaded(1), 7); 2745 EXPECT_THAT(mock.Overloaded(5), 9); 2746 EXPECT_THAT(mock.Overloaded(7), 7); 2747 2748 const MockConstOverload& const_mock = mock; 2749 EXPECT_THAT(const_mock.Overloaded(1), 0); 2750 EXPECT_THAT(const_mock.Overloaded(5), 11); 2751 EXPECT_THAT(const_mock.Overloaded(7), 13); 2752} 2753 2754} // namespace 2755 2756// Allows the user to define their own main and then invoke gmock_main 2757// from it. This might be necessary on some platforms which require 2758// specific setup and teardown. 2759#if GMOCK_RENAME_MAIN 2760int gmock_main(int argc, char **argv) { 2761#else 2762int main(int argc, char **argv) { 2763#endif // GMOCK_RENAME_MAIN 2764 testing::InitGoogleMock(&argc, argv); 2765 // Ensures that the tests pass no matter what value of 2766 // --gmock_catch_leaked_mocks and --gmock_verbose the user specifies. 2767 testing::GMOCK_FLAG(catch_leaked_mocks) = true; 2768 testing::GMOCK_FLAG(verbose) = testing::internal::kWarningVerbosity; 2769 2770 return RUN_ALL_TESTS(); 2771} 2772