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