CookBook.md (73461B)
1 # *Trompeloeil* cook book 2 3 - [Integrating with unit test frame works](#unit_test_frameworks) 4 - [Creating Mock Classes](#creating_mock_classes) 5 - [Mocking private or protected member functions](#mocking_non_public) 6 - [Mocking overloaded member functions](#mocking_overloaded) 7 - [Mocking operator()](#mocking_call_operator) 8 - [Mocking a class template](#mocking_class_template) 9 - [Mocking non-virtual member functions](#mocking_non_virtual) 10 - [Mocking free functions](#mocking_free_functions) 11 - [Mocking functions which return a template](#mocking_return_template) 12 - [Setting Expectations](#setting_expectations) 13 - [Matching exact values](#matching_exact_values) 14 - [Matching values with conditions](#matching_conditions) 15 - [Matching strings with regular expressions](#matching_regular_expressions) 16 - [Matching pointers to values](#matching_pointers) 17 - [Matching the opposite of a matcher](#negating_matchers) 18 - [Matching calls with conditions depending on several parameters](#matching_multiconditions) 19 - [Matching `std::unique_ptr<T>` and other non-copyable values](#matching_non_copyable) 20 - [Matching calls to overloaded member functions](#matching_overloads) 21 - [Define side effects for matching calls](#side_effects) 22 - [Return values from matching calls](#return_values) 23 - [Return references from matching calls](#return_references) 24 - [Throwing exceptions from matching calls](#throw) 25 - [Allowing any call](#allowing_any) 26 - [Temporarily disallowing matching calls](#temporary_disallow) 27 - [Expecting several matching calls in some sequences](#sequences) 28 - [Expecting matching calls a certain number of times](#match_count) 29 - [Controlling lifetime of mock objects](#lifetime) 30 - [Customize output format of values](#custom_formatting) 31 - [Tracing mocks](#tracing) 32 - [Using `trompeloeil::stream_tracer`](#stream_tracer) 33 - [Writing custom tracers](#custom_tracer) 34 - [Writing custom matchers](#custom_matchers) 35 - [Typed matchers](#typed_matcher) 36 - [Duck-typed matchers](#duck_typed_matcher) 37 - [Legacy matchers](#legacy_matcher) 38 39 ## <A name="unit_test_frameworks"/> Integrating with unit test frame works 40 41 By default, *Trompeloeil* reports violations by throwing an exception, 42 explaining the problem in the 43 [`what()`](http://en.cppreference.com/w/cpp/error/exception/what) string. 44 45 Depending on your test frame work and your runtime environment, this may, 46 or may not, suffice. 47 48 *Trompeloeil* offers support for adaptation to any test frame work. Some 49 sample adaptations are: 50 51 - [Catch!](#adapt_catch) 52 - [crpcut](#adapt_crpcut) 53 - [CxxTest](#adapt_cxxtest) 54 - [doctest](#adapt_doctest) 55 - [gtest](#adapt_gtest) 56 - [lest](#adapt_lest) 57 - [boost Unit Test Framework](#adapt_boost_unit_test_framework) 58 - [MSTest](#adapt_mstest) 59 - [Criterion](#adapt_criterion) 60 61 There are two mechanisms for adapting to a testing frame work. The compile time 62 adapter and the run time adapter. The compile time adapter is easier to use, 63 especially if you write several test programs, but the runtime adapter allows 64 for more flexibility, for example if you need run-time data like CLI arguments. 65 66 ### Compile time adapter 67 68 If you have a unit testing framework named *my_test*, create a header file 69 `<my_test/trompeloeil.hpp>`. This header file must include `<trompeloeil.hpp>`, 70 and provide an inline specialization of the 71 `trompeloeil::reporter<trompeloeil::specialized>::send()` function. 72 73 Below, as an example, is the adapter for the 74 [*doctest*](https://github.com/onqtam/doctest) unit testing frame work, in the 75 file `<doctest/trompeloeil.hpp>` 76 77 ```Cpp 78 #ifndef TROMPELOEIL_DOCTEST_HPP_ 79 #define TROMPELOEIL_DOCTEST_HPP_ 80 81 #ifndef DOCTEST_VERSION_MAJOR //** 1 **// 82 #error "<doctest.h> must be included before <doctest/trompeloeil.hpp>" 83 #endif 84 85 #include "../trompeloeil.hpp" //** 2 **// 86 87 namespace trompeloeil 88 { 89 template <> 90 inline void reporter<specialized>::send( //** 3 **// 91 severity s, 92 char const* file, 93 unsigned long line, 94 std::string const& msg) 95 { 96 auto f = line ? file : "[file/line unavailable]"; 97 if (s == severity::fatal) 98 { 99 ADD_FAIL_AT(f, line, msg); //** 4 **// 100 } 101 else 102 { 103 ADD_FAIL_CHECK_AT(f, line, msg); //** 4 **// 104 } 105 } 106 } 107 108 109 #endif //TROMPELOEIL_DOCTEST_HPP_ 110 ``` 111 112 The preprocessor check at `//** 1 **//` is not necessary, but it gives a 113 friendly hint about what's missing. The function uses *doctest* macros 114 at `//** 4 **//`, so `<doctest.h>` must be included for this to compile. 115 116 At `//** 2 **//` the include path is relative, since this is the file from 117 the *Trompeloeil* distribution, where the main `trompeloeil.hpp` file is 118 known to be in the parent directory of `doctest/trompeloeil.hpp`. 119 120 At `//** 3 **//` the specialized function is marked `inline`, so as not to 121 cause linker errors if your test program consists of several translation 122 units, each including `<doctest/trompeloeil.hpp>`. 123 124 At `//** 4 **//` the violations are reported in a *doctest* specific 125 manner. 126 127 It is important to understand the first parameter 128 `trompeloeil::severity`. It is an enum with the values 129 `trompeloeil::severity::fatal` and `trompeloeil::severity::nonfatal`. The value 130 `severity::nonfatal` is used when reporting violations during stack rollback, 131 typically during the destruction of an [expectation]( 132 reference.md/#expectation 133 ). In this case it is vital that no exception is 134 thrown, or the process will terminate. If the value is 135 `severity::fatal`, it is instead imperative that the function does not return. 136 It may throw or abort. 137 138 **NOTE!** There are some violations that cannot be attributed to a source code 139 location. An example is an unexpected call to a 140 [mock function](reference.md/#mock_function) for which there 141 are no expectations. In these cases `file` will be `""` string and 142 `line` == 0. 143 144 Please contribute your adapter, so that others can enjoy your unit testing 145 framework together with *Trompeloeil*. 146 147 ### Run time adapter 148 149 Run time adaptation to unit test frame works is done with this function: 150 151 ```Cpp 152 using reporter_func = std::function<void( 153 severity, 154 char const *file, 155 unsigned long line, 156 std::string const &msg)>; 157 using ok_reporter_func = std::function<void(char const *msg)>; 158 159 reporter_func trompeloeil::set_reporter(reporter_func new_reporter); 160 std::pair<reporter_func, ok_reporter_func> trompeloeil::set_reporter( 161 reporter_func new_reporter, ok_reporter_func new_ok_reporter) 162 ``` 163 164 Call it with the adapter to your test frame work. The return value is the old 165 adapter. The overload is provided to allow you to also set an 'OK reporter' at 166 the same time (it also returns the old 'OK reporter') See the next section for 167 details. 168 169 It is important to understand the first parameter 170 `trompeloeil::severity`. It is an enum with the values 171 `trompeloeil::severity::fatal` and `trompeloeil::severity::nonfatal`. The value 172 `severity::nonfatal` is used when reporting violations during stack rollback, 173 typically during the destruction of an 174 [expectation](reference.md/#expectation). In this case it is vital that 175 no exception is thrown, or the process will terminate. If the value is 176 `severity::fatal`, it is instead imperative that the function does not return. 177 It may throw or abort. 178 179 **NOTE!** There are some violations that cannot be attributed to a source code 180 location. An example is an unexpected call to a 181 [mock function](reference.md/#mock_function) for which there 182 are no expectations. In these cases `file` will be `""` string and 183 `line` == 0. 184 185 ### Status OK reporting 186 187 It is possible to make an adaption to the reporter that will be called if 188 a positive expectation is met. This can be useful for correct counting and reporting 189 from the testing framework. Negative expectations like `FORBID_CALL` and 190 `.TIMES(0)` are not counted. 191 192 Either provide your adapter as an inline specialization of the 193 `trompeloeil::reporter<trompeloeil::specialized>::sendOk()` function at 194 compile time or as the second argument to 195 `trompeloeil::set_reporter(new_reporter, new_ok_reporter)` at runtime. 196 The function should call a matcher in the testing framework that always 197 yields true. 198 199 Below, as an example, is the compile time adapter for the Catch2 unit testing frame 200 work, in the file `<catch2/trompeloeil.hpp>` 201 202 ```Cpp 203 template <> 204 inline void reporter<specialized>::sendOk( 205 const char* trompeloeil_mock_calls_done_correctly) 206 { 207 REQUIRE(trompeloeil_mock_calls_done_correctly); 208 } 209 ``` 210 211 If you roll your own `main()`, you may prefer a runtime adapter instead. Please note that the first param given to `set_reporter()` here is a dummy - see the sections below for implementation examples for your unit testing framework of choice. 212 213 ```Cpp 214 trompeloeil::set_reporter( 215 [](auto, auto, auto, auto) {}, // Not relevant here 216 [](const char* trompeloeil_mock_calls_done_correctly) 217 { 218 // Example for Catch2 219 REQUIRE(trompeloeil_mock_calls_done_correctly); 220 } 221 ); 222 ``` 223 224 Below is a simple example for *Catch2*: 225 226 ```Cpp 227 class MockFoo 228 { 229 public: 230 MAKE_MOCK0(func, void()); 231 }; 232 233 TEST_CASE("Foo test") 234 { 235 MockFoo foo; 236 REQUIRE_CALL(foo, func()).TIMES(2,4); 237 foo.func(); 238 foo.func(); 239 } 240 ``` 241 242 When the test is executed we get the following output 243 244 ```sh 245 $ ./footest 246 =============================================================================== 247 All tests passed (2 assertions in 1 test case) 248 ``` 249 250 ### <A name="adapt_catch"/>Use *Trompeloeil* with [Catch2](https://github.com/catchorg/Catch2) 251 252 The easiest way to use *Trompeloeil* with *Catch2* is to 253 `#include <catch2/trompeloeil.hpp>` in your test .cpp files. Note that the 254 inclusion order is important. `<catch.hpp>` must be included before 255 `<catch/trompeloeil.hpp>`. 256 257 Like this: 258 259 ```Cpp 260 #include <catch.hpp> 261 #include <catch2/trompeloeil.hpp> 262 263 TEST_CASE("... 264 ``` 265 266 If you roll your own `main()`, you may prefer a runtime adapter instead. 267 Before running any tests, make sure to call: 268 269 ```Cpp 270 trompeloeil::set_reporter([]( 271 trompeloeil::severity s, 272 const char* file, 273 unsigned long line, 274 std::string const& msg) 275 { 276 std::ostringstream os; 277 if (line) os << file << ':' << line << '\n'; 278 os << msg; 279 auto failure = os.str(); 280 if (s == trompeloeil::severity::fatal) 281 { 282 FAIL(failure); 283 } 284 else 285 { 286 CAPTURE(failure); 287 CHECK(failure.empty()); 288 } 289 }); 290 ``` 291 292 ### <A name="adapt_cxxtest"/>Use *Trompeloeil* with [CxxTest](https://www.cxxtest.com) 293 294 The easiest way to use *Trompeloeil* with *CxxTest* is to 295 `#include <cxxtest/trompeloeil.hpp>` in your test `.hpp` files. Note that the 296 inclusion order is important. `<cxxtest/TestSuite.h>` must be included before 297 `<cxxtest/trompeloeil.hpp>`. 298 299 Like this: 300 301 ```Cpp 302 #include <cxxtest/TestSuite.h> 303 #include <cxxtest/trompeloeil.hpp> 304 305 class TestClass: public CxxTest::TestSuite 306 { 307 public: 308 void TestXXX() 309 { 310 // ... 311 } 312 }; 313 ``` 314 315 If you roll your own `main()`, you may prefer a runtime adapter instead. 316 Before running any tests, make sure to call: 317 318 ```Cpp 319 trompeloeil::set_reporter([]( 320 trompeloeil::severity s, 321 const char* file, 322 unsigned long line, 323 std::string const& msg) 324 { 325 std::ostringstream os; 326 if (line) os << file << ':' << line << '\n'; 327 os << msg; 328 auto failure = os.str(); 329 if (s == severity::fatal) 330 { 331 // Must not return normally i.e. must throw, abort or terminate. 332 TS_FAIL(failure); 333 } 334 else 335 { 336 // nonfatal: violation occurred during stack rollback. 337 // Must not throw an exception. 338 TS_WARN(failure); 339 } 340 }); 341 ``` 342 343 ### <A name="adapt_crpcut"/>Use *Trompeloeil* with [crpcut](http://crpcut.sourceforge.net) 344 345 The easiest way to use *Trompeloeil* with *crpcut* is to 346 `#include <crpcut/trompeloeil.hpp>` in your test .cpp files. Note that the 347 inclusion order is important. `<crpcut.hpp>` must be included before 348 `<crpcut/trompeloeil.hpp>`. 349 350 Like this: 351 352 ```Cpp 353 #include <crpcut.hpp> 354 #include <crpcut/trompeloeil.hpp> 355 356 TEST(... 357 ``` 358 359 If you instead prefer a runtime adapter, make sure to call 360 361 ```Cpp 362 trompeloeil::set_reporter([]( 363 trompeloeil::severity, 364 const char* file, 365 unsigned long line, 366 std::string const& msg) 367 { 368 std::ostringstream os; 369 os << file << ':' << line; 370 auto loc = os.str(); 371 auto location = line == 0U 372 ? ::crpcut::crpcut_test_monitor::current_test()->get_location() 373 : ::crpcut::datatypes::fixed_string::make(loc.c_str(), loc.length()); 374 ::crpcut::comm::report(::crpcut::comm::exit_fail, 375 std::ostringstream(msg), 376 location); 377 }); 378 ``` 379 380 before any tests are run. 381 382 ### <A name="adapt_doctest"/>Use *Trompeloeil* with [doctest](https://github.com/onqtam/doctest) 383 384 - [doctest 1.2 or newer](#doctest12) 385 - [doctest < 1.2](#doctest_old) 386 387 #### <A name="doctest12"/> doctest 1.2 or newer 388 389 The easiest way to use *Trompeloeil* with *doctest* is to 390 `#include <doctest/trompeloeil.hpp>` in your test .cpp files. Note that the 391 inclusion order is important. `<doctest.h>` must be included before 392 `<doctest/trompeloeil.hpp>`. 393 394 Like this: 395 396 ```Cpp 397 #include <doctest.h> 398 #include <doctest/trompeloeil.hpp> 399 400 TEST_CASE("... 401 ``` 402 403 If you roll your own `main()`, you may prefer a runtime adapter instead. 404 Before running any tests, make sure to call: 405 406 ```Cpp 407 trompeloeil::set_reporter([]( 408 trompeloeil::severity s, 409 const char* file, 410 unsigned long line, 411 std::string const& msg) 412 { 413 auto f = line ? file : "[file/line unavailable]"; 414 if (s == severity::fatal) 415 { 416 ADD_FAIL_AT(f, line, msg); 417 } 418 else 419 { 420 ADD_FAIL_CHECK_AT(f, line, msg); 421 } 422 }); 423 ``` 424 425 #### <A name="doctest_old"/> doctest < 1.2 426 427 Create a simple `doctest_violation` type by pasting the below code 428 into the file containing `main()`. 429 430 ```Cpp 431 struct doctest_violation : std::ostringstream 432 { 433 friend std::ostream& operator<<(std::ostream& os, doctest_violation const& v) 434 { 435 return os << v.str(); 436 } 437 }; 438 ``` 439 440 Then, before running any tests, make sure to call: 441 442 ```Cpp 443 trompeloeil::set_reporter([]( 444 trompeloeil::severity s, 445 const char* file, 446 unsigned long line, 447 std::string const& msg) 448 { 449 ::doctest_violation violation; 450 if (line) violation << file << ':' << line << '\n'; 451 violation << msg; 452 if (s == trompeloeil::severity::fatal) 453 { 454 REQUIRE_FALSE(violation); 455 } 456 else 457 { 458 CHECK_FALSE(violation); 459 } 460 }); 461 ``` 462 463 ### <A name="adapt_gtest"/>Use *Trompeloeil* with [gtest](https://code.google.com/p/googletest/) 464 465 The easiest way to use *Trompeloeil* with *gtest* is to 466 `#include <gtest/trompeloeil.hpp>` in your test .cpp files. Note that the 467 inclusion order is important. `<gtest.h>` must be included before 468 `<gtest/trompeloeil.hpp>`. 469 470 Like this: 471 472 ```Cpp 473 #include <gtest.h> 474 #include <gtest/trompeloeil.hpp> 475 476 TEST("... 477 ``` 478 479 If you instead prefer a runtime adapter, make sure to call 480 481 ```Cpp 482 trompeloeil::set_reporter([]( 483 trompeloeil::severity s, 484 const char* file, 485 unsigned long line, 486 std::string const& msg) 487 { 488 if (s == trompeloeil::severity::fatal) 489 { 490 std::ostringstream os; 491 if (line != 0U) 492 { 493 os << file << ':' << line << '\n'; 494 } 495 throw trompeloeil::expectation_violation(os.str() + msg); 496 } 497 498 ADD_FAILURE_AT(file, line) << msg; 499 }); 500 ``` 501 502 before running any tests. 503 504 ### <A name="adapt_lest"/>Use *Trompeloeil* with [lest](https://github.com/martinmoene/lest) 505 506 With *lest*, you always provide your own `main()`. In it, provide a runtime adapter like the one below. 507 508 ```Cpp 509 int main(int argc, char *argv[]) 510 { 511 std::ostream& stream = std::cout; 512 513 trompeloeil::set_reporter([&stream]( 514 trompeloeil::severity s, 515 const char* file, 516 unsigned long line, 517 std::string const& msg) 518 { 519 if (s == trompeloeil::severity::fatal) 520 { 521 throw lest::message{"", lest::location{ line ? file : "[file/line unavailable]", int(line) }, "", msg }; 522 } 523 else 524 { 525 stream << lest::location{ line ? file : "[file/line unavailable]", int(line) } << ": " << msg; 526 } 527 }); 528 529 return lest::run(specification, argc, argv, stream); 530 } 531 ``` 532 533 ### <A name="adapt_boost_unit_test_framework"/>Use *Trompeloeil* with [boost Unit Test Framework](http://www.boost.org/doc/libs/1_59_0/libs/test/doc/html/index.html) 534 535 The easiest way to use *Trompeloeil* with *boost::unit_test* is to 536 `#include <boost/trompeloeil.hpp>` in your test .cpp files. Note that the 537 inclusion order is important. `<boost/test/unit_test.hpp>` must be included before 538 `<boost/trompeloeil.hpp>`. 539 540 Like this: 541 542 ```Cpp 543 #include <boost/test/unit_test.hpp> 544 #include <boost/trompeloeil.hpp> 545 546 BOOST_AUTO_TEST_CASE("... 547 ``` 548 549 If you instead prefer a runtime adapter, make sure to call 550 551 ```Cpp 552 trompeloeil::set_reporter([]( 553 trompeloeil::severity s, 554 const char* file, 555 unsigned long line, 556 std::string const& msg) 557 { 558 std::ostringstream os; 559 if (line != 0U) os << file << ':' << line << '\n'; 560 auto text = os.str() + msg; 561 if (s == trompeloeil::severity::fatal) 562 BOOST_FAIL(text); 563 else 564 BOOST_ERROR(text); 565 }); 566 ``` 567 568 before running any tests. 569 570 ### <A name="adapt_mstest"/> Use *Trompeloeil* with [MSTest](https://msdn.microsoft.com/en-us/library/hh694602.aspx) 571 572 Place the below code snippet in, for example, your `TEST_CLASS_INITIALIZE(...)` 573 574 ```Cpp 575 using namespace trompeloeil; 576 set_reporter([]( 577 severity, 578 char const* file, 579 unsigned long line, 580 std::string const& msg) 581 { 582 std::wstring wideMsg(msg.begin(), msg.end()); 583 std::wstring wfile; 584 if (line > 0) wfile.append(file, file + strlen(file)); 585 __LineInfo loc(wfile.c_str(), "", line); 586 Assert::Fail(wideMsg.c_str(), line == 0 ? nullptr : &loc); 587 }); 588 ``` 589 590 ### <A name="adapt_criterion"/>Use *Trompeloeil* with [Criterion](https://github.com/Snaipe/Criterion) 591 592 The easiest way to use *Trompeloeil* with *Criterion* is to 593 `#include <criterion/trompeloeil.hpp>` in your test .cpp files. Note that the 594 inclusion order is important. `<criterion/criterion.hpp>` must be included before 595 `<criterion/trompeloeil.hpp>`. 596 597 Like this: 598 599 ```Cpp 600 #include <criterion/criterion.hpp> 601 #include <criterion/trompeloeil.hpp> 602 603 Test(... 604 ``` 605 606 If you instead prefer a runtime adapter, make sure to call 607 608 ```Cpp 609 trompeloeil::set_reporter([]( 610 trompeloeil::severity s, 611 const char* file, 612 unsigned long line, 613 std::string const& msg) 614 { 615 struct criterion_assert_stats cr_stat__; 616 cr_stat__.passed = false; 617 cr_stat__.file = file; 618 cr_stat__.line = line; 619 cr_stat__.message = msg; 620 if (s == severity::fatal) 621 { 622 criterion_send_assert(&cr_stat__); 623 CR_FAIL_ABORT_(); 624 } 625 else 626 { 627 criterion_send_assert(&cr_stat__); 628 CR_FAIL_CONTINUES_(); 629 } 630 }); 631 ``` 632 633 before running any tests. 634 635 ## <A name="creating_mock_classes"/> Creating Mock Classes 636 637 A Mock class is any class that [mocks](reference.md/#mock_function) member 638 functions. 639 640 There are two ways to create mocks. A very frequently seen situation is 641 when inheriting from an interface (i.e. an abstract base class with 642 pure virtual functions). When this is the case, the easiest route is to 643 inherit the interface via 644 [`trompeloeil::mock_interface<T>`](#reference.md/mock_interface) 645 and implement the mock functions with the macros 646 [**`IMPLEMENT_MOCKn(...)`**](reference.md/#IMPLEMENT_MOCKn) and 647 [**`IMPLEMENT_CONST_MOCKn(...)`**](reference.md/#IMPLEMENT_CONST_MOCKn). These 648 only work when implementing to an interface, do not handle multiple inheritance 649 and do not handle overloads. 650 651 A more generic technique is to implement free mocks as members of any 652 `struct` or `class` using the macros [**`MAKE_MOCKn`**]( 653 reference.md/#MAKE_MOCKn 654 ) and [**`MAKE_CONST_MOCKn`**]( 655 reference.md/#MAKE_CONST_MOCKn 656 ), where `n` is the number of parameters in the function. 657 658 Example: 659 660 ```Cpp 661 class Dictionary 662 { 663 public: 664 virtual ~Dictionary() = default; 665 virtual std::string& lookup(int n) const = 0; 666 virtual void add(int n, std::string&&) = 0; 667 }; 668 669 class MockDictionary : public trompeloeil::mock_interface<Dictionary> 670 { 671 IMPLEMENT_CONST_MOCK1(lookup); 672 IMPLEMENT_MOCK2(add); 673 }; 674 675 struct Logger 676 { 677 MAKE_MOCK2(log, void(int severity, const std::string& msg)); 678 }; 679 680 ``` 681 682 In the example above, `MockDictionary` is, as the name implies, a mock class for 683 the pure virtual class `Dictionary`. 684 685 The line `IMPLEMENT_CONST_MOCK1(lookup);` implements the function 686 `std::string& lookup(int) const` and the line `IMPLEMENT_MOCK2(add);` implements 687 the function `void add(int, std::string&&)`. 688 689 The line `MAKE_MOCK2(log, void(int severity, const std::string& msg))` 690 creates a mock function `void Logger::log(int, const std::string&)`. If 691 [**`MAKE_MOCKn(...)`**](reference.md/#MAKE_MOCKn) or 692 [**`MAKE_CONST_MOCKn(...)`**](reference.md/#MAKE_CONST_MOCKn) are used 693 to implement a virtual function from a base class, it is always recommended to 694 add a third macro parameter `override` since it gives the compiler an ability to 695 complain about mistakes. 696 697 ### <A name="mocking_non_public"/> Mocking private or protected member functions 698 699 Mocking private or protected member functions using 700 [**`MAKE_MOCKn(...)`**](reference.md/#MAKE_MOCKn) or 701 [**`MAKE_CONST_MOCKn(...)`**](reference.md/#MAKE_CONST_MOCKn) is no different 702 from mocking 703 704 public member functions. Just make them public in the mock class. It may seem 705 strange that you can change access rights of a member function through 706 inheritance, but C\+\+ allows it. 707 708 Example: 709 710 ```Cpp 711 class Base 712 { 713 private: 714 virtual void secret(int); 715 }; 716 717 class Mock : public Base 718 { 719 public: 720 MAKE_MOCK1(secret, void(int), override); // not so secret now 721 }; 722 ``` 723 724 The [mock functions](reference.md/#mock_function) must be public for you to 725 be able to set [expectations](#setting_expectations) on them, but there is 726 nothing preventing a public function from implementing a private virtual function 727 in a base class. 728 729 **NOTE!** Mocking private or protected functions does not work with 730 [**`IMPLEMENT_MOCKn(...)`**](reference.md/#IMPLEMENT_MOCKn) or 731 [**`IMPLEMENT_CONST_MOCKn(...)`**](reference.md/#IMPLEMENT_CONST_MOCKn), since 732 these need full visibility of the function in the base class. 733 734 ### <A name="mocking_overloaded"/> Mocking overloaded member functions 735 736 *Trompeloeil* matches [mock functions](reference.md/#mock_function) by 737 their name and their signature, so there is nothing special about 738 adding several overloads of mocked functions. 739 740 Example: 741 742 ```Cpp 743 class Mock 744 { 745 public: 746 MAKE_MOCK1(overload, void(int)); 747 MAKE_MOCK1(overload, int(const std::string&)); 748 MAKE_MOCK2(overload, int(const char*, size_t)); 749 }; 750 ``` 751 752 Above there are three [mock functions](reference.md/#mock_function) named 753 `overload`, with different signatures. 754 755 See [Matching calls to overloaded member functions](#matching_overloads) 756 for how to place [expectations](reference.md/#expectation) on them. 757 758 **NOTE!** Overloaded member functions cannot be mocked using the 759 macros [**`IMPLEMENT_MOCKn(...)`**](reference.md/IMPLEMENT_MOCKn) or 760 [**`IMPLEMENT_CONST_MOCKn(...)`**](reference.md/IMPLEMENT_CONST_MOCKn)`. 761 762 ### <A name="mocking_call_operator"/> Mocking operator() 763 764 The *Trompeloeil* macros cannot handle `operator()` directly, so to 765 mock the function call operator you have to go via an indirection, where 766 you implement a trivial `operator()` that calls a function that you can mock. 767 768 Example: 769 770 ```Cpp 771 class Mock 772 { 773 public: 774 int operator()(int x) const { return function_call(x); } 775 MAKE_CONST_MOCK1(function_call, int(int)); 776 }; 777 ``` 778 779 ### <A name="mocking_class_template"/> Mocking a class template 780 781 Unlike some *C\+\+* mocking frame works, *Trompeloeil* does not make a 782 distinction between mocks in class templates and mocks in concrete classes. 783 784 Example: 785 786 ```Cpp 787 template <typename T> 788 class Mock 789 { 790 public: 791 MAKE_MOCK1(func, void(int)); 792 MAKE_MOCK2(tfunc, int(const T&, size_t)); 793 }; 794 ``` 795 796 Above, `Mock<T>` is a mock class template with two member functions. The 797 member function `void func(int)` does not depend on the template parameter, 798 whereas the member function `int tfunc(const T&, size_t)` does. This will 799 work for any type `T`. 800 801 ### <A name="mocking_non_virtual"/> Mocking non-virtual member functions 802 803 While it is often the case that mocks are used to implement interfaces, there is 804 no such requirement. Just add the [mock functions][mockfun] that are needed. 805 806 Example: 807 808 ```Cpp 809 class ConcreteMock 810 { 811 public: 812 MAKE_MOCK2(func, bool(size_t, const char*)); 813 }; 814 ``` 815 816 Above `ConcreteMock` is a mock class that implements a non-virtual [mock 817 function][mockfun] `bool func(size_t, const char*)`. 818 819 > **REMINDER**: Non-virtual functions may not be dispatched via polymorphism at 820 > runtime. This feature doesn't alter the underlying semantic rules for virtual 821 > methods. If you upcast to a base type, the mock class implementations of these 822 > methods will _not_ be invoked. 823 824 [mockfun]: reference.md/#mock_function 825 826 ### <A name="mocking_free_functions"/> Mocking free functions 827 828 Free functions on their own cannot be mocked, the calls to them needs to 829 be dispatched to [mock objects](reference.md/#mock_object). Often there are 830 several free functions that together form an API, and then it makes sense 831 to implement one mock class for the API, with 832 [mock functions](reference.md/#mock_function) for each. 833 834 Example, assume a simple C-API 835 836 ```Cpp 837 // C-API.h 838 839 #ifdef __cplusplus 840 extern "C" { 841 #endif 842 843 struct c_api_cookie; 844 845 struct c_api_cookie* c_api_init(); 846 847 int c_api_func1(struct c_api_cookie* cookie, const char* str, size_t len); 848 849 void c_api_end(struct c_api_cookie*); 850 851 #ifdef __cplusplus 852 } 853 #endif 854 ``` 855 856 ```Cpp 857 // unit-test-C-API.h 858 859 #include "C-API.h" 860 861 class API 862 { 863 public: 864 MAKE_MOCK0(c_api_init, c_api_cookie*()); 865 MAKE_MOCK3(c_api_func1, int(c_api_cookie*, const char*, size_t)); 866 MAKE_MOCK1(c_api_end, void(c_api_cookie*)); 867 }; 868 869 extern API c_api_mock; 870 ``` 871 872 Then implement the functions in a test version of the API, which uses the 873 mock. 874 875 ```Cpp 876 // unit-test_c_api.cpp 877 #include "unit-test-C-API.h" 878 879 API c_api_mock; 880 881 extern "C" { 882 c_api_cookie c_api_init() 883 { 884 return api_mock.c_api_init(); 885 } 886 887 int c_api_func1(c_api_cookie* cookie, const char* str, size_t len) 888 { 889 return api_mock.c_api_func1(cookie, str, len); 890 } 891 892 void c_api_end(c_api_cookie* cookie) 893 { 894 api_mock.c_api_end(cookie); 895 } 896 } 897 ``` 898 899 A test program can place [expectations](reference.md/#expectation) on the 900 mock object, and the tested functionality calls the C-API functions which 901 dispatch to the mock object. 902 903 ```Cpp 904 #include "unit-test-C-API.h" 905 906 void a_test() 907 { 908 REQUIRE_CALL(c_api_mock, create()) 909 .RETURN(nullptr); 910 911 REQUIRE_CALL(c_api_mock, c_api_end(nullptr)); 912 913 function_under_test(); 914 } 915 ``` 916 917 ### <A name="mocking_return_template"/> Mocking functions which return a template 918 919 To use template as return type you have to put the signature into parentheses 920 like this: 921 922 ```Cpp 923 struct M 924 { 925 MAKE_MOCK2(make, (std::pair<int,int>(int,int))); 926 }; 927 ``` 928 929 ## <A name="setting_expectations"/> Setting Expectations 930 931 It is with [expectations](reference.md/#expectation) you define the behaviour 932 of your test. By default all calls to 933 [mock functions](reference.md/#mock_function) are illegal and will be reported 934 as violations. You use expectations, long or short lived, wide or narrow, 935 to make some calls legal and define what happens. 936 937 There are three basic types of expectations. 938 939 - [**`ALLOW_CALL(...)`**](reference.md/#ALLOW_CALL) 940 - [**`REQUIRE_CALL(...)`**](reference.md/#REQUIRE_CALL) 941 - [**`FORBID_CALL(...)`**](reference.md/#FORBID_CALL) 942 943 **`ALLOW_CALL(...)`** is often used for a default. It can match any number of 944 times. 945 946 **`REQUIRE_CALL(...)`** is stricter and defaults to match exactly once, although 947 you can change that and control exactly [how many times](#match_count) you want 948 the expectation to match. 949 950 **`FORBID_CALL(...)`** may seem unnecessary since calls are forbidden by 951 default, but it is useful in combination with **`ALLOW_CALL(...)`** or 952 **`REQUIRE_CALL(...)`** to forbid something that would otherwise be accepted. 953 954 If several expectations match a call, it is the last matching expectation 955 created that is used. **`ALLOW_CALL(...)`**, **`REQUIRE_CALL(...)`** and 956 **`FORBID_CALL(...)`** are active until the end of the scope. This means 957 that you can place a wide default, and use temporary special expectations in 958 local scopes, for example to temporarily forbid a call that is otherwise 959 allowed. 960 961 If the scoped lifetime rules are unsuitable, there are also thee named 962 versions of the expectations. 963 964 - [**`NAMED_ALLOW_CALL(...)`**](reference.md/#NAMED_ALLOW_CALL) 965 - [**`NAMED_REQUIRE_CALL(...)`**](reference.md/#NAMED_REQUIRE_CALL) 966 - [**`NAMED_FORBID_CALL(...)`**](reference.md/#NAMED_FORBID_CALL) 967 968 These do the same, but they create a 969 `std::unique_ptr<trompeloeil::expectation>`, which you can bind to variables 970 that you control the life time of. 971 972 ### <A name="matching_exact_values"/> Matching exact values 973 974 The simplest [expectations](reference.md/#expectation) are for calls with exact 975 expected parameter values. You just provide the expected values in the 976 parameter list of the expectation. 977 978 Example: 979 980 ```Cpp 981 class Mock 982 { 983 public: 984 MAKE_MOCK1(func, void(int)); 985 MAKE_MOCK2(func, void(const char*)); 986 }; 987 988 void test() 989 { 990 Mock m; 991 ALLOW_CALL(m, func(1)); // int version any number of times 992 REQUIRE_CALL(m, func(nullptr)); // const char * version exactly once 993 func(&m); 994 // expectations must be met before end of scope 995 } 996 ``` 997 998 ### <A name="matching_conditions"/> Matching values with conditions 999 1000 Instead of using exact values of parameters to match calls with, *Trompeloeil* 1001 provides a set of [matchers](reference.md/#matcher). Simple value matchers are: 1002 1003 - [**`eq(`** *value* **`)`**](reference.md/#eq) matches value equal (using `operator==()`) 1004 - [**`ne(`** *value* **`)`**](reference.md/#ne) matches value not equal (using `operator!=()`) 1005 - [**`gt(`** *value* **`)`**](reference.md/#gt) matches value greater than (using `operator>()`) 1006 - [**`ge(`** *value* **`)`**](reference.md/#ge) matches value greater than or equal (using `operator>=()`) 1007 - [**`lt(`** *value* **`)`**](reference.md/#lt) matches value less than (using `operator<()`) 1008 - [**`le(`** *value* **`)`**](reference.md/#le) matches value less than or equal (using `operator<=()`) 1009 1010 By default, the matchers are [*duck typed*]( 1011 https://en.wikipedia.org/wiki/Duck_typing 1012 ), i.e. they match a parameter that supports the operation. If disambiguation 1013 is necessary to resolve overloads, an explicit type can be specified. 1014 1015 Example: 1016 1017 ```Cpp 1018 class Mock 1019 { 1020 public: 1021 MAKE_MOCK1(func, void(int)); 1022 MAKE_MOCK1(func, void(const char*)); 1023 MAKE_MOCK1(func, void(const std::string&)) 1024 }; 1025 1026 void test() 1027 { 1028 Mock m; 1029 ALLOW_CALL(m, func(trompeloeil::gt(1))); // int version any number of times 1030 REQUIRE_CALL(m, func(trompeloeil::ne<std::string>(""))); // const std::string& version once 1031 func(&m); 1032 // expectations must be met before end of scope 1033 } 1034 ``` 1035 1036 ### <A name="matching_regular_expressions"/> Matching strings with regular expressions 1037 1038 Matching string parameters to regular expressions is convenient with 1039 *Trompeloeil* [**`re(`** *expression* **`)`**](reference.md/#re) regular 1040 expression matchers. 1041 1042 Example: 1043 1044 ```Cpp 1045 class Mock 1046 { 1047 public: 1048 MAKE_MOCK1(func, void(const char*)); 1049 }; 1050 1051 void test() 1052 { 1053 Mock m; 1054 REQUIRE_CALL(m, func(trompeloeil::re("^begin.*end$"))); 1055 func(&m); 1056 // expectation must be met before end of scope 1057 } 1058 ``` 1059 1060 **TIP!** Using `C++` [raw string literals]( 1061 http://www.stroustrup.com/C++11FAQ.html#raw-strings 1062 ) can massively help getting regular expression escapes right. 1063 1064 ### <A name="matching_pointers"/> Matching pointers to values 1065 1066 All [matchers](reference.md/#matcher) can be converted to a pointer matcher 1067 by using the dereference prefix operator [**`*`**](reference.md/#deref_matcher). 1068 This works for smart pointers too. These pointer matchers fail if the pointer parameter is `nullptr`. 1069 1070 Example: 1071 1072 ```Cpp 1073 class Mock 1074 { 1075 public: 1076 MAKE_MOCK1(func, void(int*)); 1077 MAKE_MOCK2(func, void(std::unique_ptr<short>*)); 1078 }; 1079 1080 using trompeloeil::eq; 1081 using trompeloeil::gt; 1082 1083 void test() 1084 { 1085 Mock m; 1086 ALLOW_CALL(m, func(*eq(1))); // pointer to int value 1 any number of times 1087 REQUIRE_CALL(m, func(*gt<short>(5))); // unique_ptr<short> to >5 once 1088 func(&m); 1089 // expectations must be met before end of scope 1090 } 1091 ``` 1092 1093 ### <A name="negating_matchers"/> Matching the opposite of a matcher 1094 1095 All [matchers](reference.md/#matcher) can be negated, allowing what the matcher 1096 disallows and disallowing what the matcher allows, using the operator 1097 [**`!`**](reference.md/#negate_matcher) on the matcher. 1098 1099 Example: 1100 1101 ```Cpp 1102 struct Mock { 1103 MAKE_MOCK1(func, void(const std::string&)); 1104 }; 1105 1106 using trompeloeil::re; // matching regular expressions 1107 1108 TEST(atest) 1109 { 1110 Mock m; 1111 REQUIRE_CALL(m, func(!re("^foo"))); 1112 func(&m); 1113 // m.func() must've been called with a string not beginning with "foo" 1114 } 1115 ``` 1116 1117 ### <A name="matching_multiconditions"/> Matching calls with conditions depending on several parameters 1118 1119 Some times a matching call cannot be judged for individual parameter values 1120 alone, but together they work. Assume for example a C-string API where you have 1121 a `const char*` and a length. 1122 1123 Example: 1124 1125 ```Cpp 1126 class Mock 1127 { 1128 public: 1129 MAKE_MOCK2(func, void(const char*, size_t len)); 1130 }; 1131 1132 using trompeloeil::ne; 1133 using trompeloeil::_; 1134 1135 void test() 1136 { 1137 Mock m; 1138 REQUIRE_CALL(m, func(ne(nullptr), _))) // once 1139 .WITH(std::string(_1, _2) == "meow")); 1140 func(&m); 1141 // expectations must be met before end of scope 1142 } 1143 ``` 1144 1145 [**`_`**](reference.md/#wildcard) is a special matcher that matches everything. 1146 [**`.WITH(...)`**](reference.md/#WITH) is a construction used for when simple 1147 matchers aren't enough. If a call is made which matches the values given in 1148 the [**`REQUIRE_CALL(...)`**](reference.md/#REQUIRE_CALL), the selection process 1149 continues in [**`.WITH(std::string(_1, _2) == "meow")`**](reference.md/#WITH). 1150 1151 **`_1`** and **`_2`** are the parameters to the call, so in this case a 1152 `std::string` is constructed using the non-null `const char*` and the length, 1153 and its value is compared with `"meow"`. 1154 1155 The expression in [**`.WITH(...)`**](reference.md/#WITH) can be anything at all 1156 that returns a boolean value. It can refer to global variables, for example. 1157 1158 It is important to understand that [**`.WITH(...)`**](reference.md/#WITH) 1159 accesses any local variable used in the expression as a copy. If you want to 1160 refer to a local variable by reference, use 1161 [**`.LR_WITH(...)`**](reference.md/#LR_WITH) instead (`LR_` for 1162 "local reference"). 1163 1164 ### <A name="matching_non_copyable"/> Matching `std::unique_ptr<T>` and other non-copyable values 1165 1166 Matching parameter values that you cannot copy, or do not want to copy, 1167 requires a bit of thought. 1168 1169 The wildcards [**`_`**](reference.md/#wildcard) and 1170 [**`ANY(...)`**](reference.md/#ANY) works. For `std::unique_ptr<T>` and 1171 `std::shared_ptr<T>`, the matcher [**`ne(nullptr)`**](reference.md/#ne) also 1172 works. 1173 1174 If you want to be more specific, you will need to use 1175 [**`.WITH(...)`**](reference.md/#WITH) or 1176 [**`.LR_WITH(...)`**](reference.md/#LR_WITH) 1177 1178 Example: 1179 1180 ```Cpp 1181 class Mock 1182 { 1183 public: 1184 MAKE_MOCK1(func, void(std::unique_ptr<int>)); 1185 }; 1186 1187 using trompeloeil::ne; 1188 1189 void test() 1190 { 1191 Mock m; 1192 REQUIRE_CALL(m, func(ne(nullptr))) 1193 .WITH(*_1 == 3); 1194 func(&m); 1195 // expectations must be met before end of scope 1196 } 1197 ``` 1198 1199 Above there is a requirement that the function is called with a non-null 1200 `std::unique_ptr<int>`, which points to a value of `3`. 1201 1202 If the signature of the function is to a reference, you can also use 1203 [`std::ref()`](https://en.cppreference.com/w/cpp/utility/functional/ref) to 1204 bind a reference in the expectation. 1205 1206 ```Cpp 1207 class Mock 1208 { 1209 public: 1210 MAKE_MOCK1(func, void(std::unique_ptr<int>&)); 1211 }; 1212 1213 void func_to_test(Mock& m, std::unique_ptr<int>& ptr); 1214 1215 void test() 1216 { 1217 Mock m; 1218 auto p = std::make_unique<int>(3); 1219 { 1220 REQUIRE_CALL(m, func(std::ref(p))) 1221 .LR_WITH(&_1 == &p); // ensure same object, not just equal value 1222 func_to_test(m, p); 1223 } 1224 } 1225 ``` 1226 1227 Note that the check for a matching parameter defaults to using `operator==`. 1228 If you want to ensure that it is the exact same object, not just one with the 1229 same value, you need to compare the addresses of the parameter and the 1230 expected value, as shown in the example above. 1231 1232 ### <A name="matching_overloads"/> Matching calls to overloaded member functions 1233 1234 Distinguishing between overloads is simple when using exact values to match 1235 since the type follows the values. It is more difficult when you want to use 1236 wildcards and other [matchers](reference.md/#matcher). 1237 1238 One useful matcher is [**`ANY(...)`**](reference.md/#ANY), which behaves 1239 like the open wildcard [**`_`**](reference.md/#wildcard), but has a type. 1240 It is also possible to specify types in the matchers. 1241 1242 Example: 1243 1244 ```Cpp 1245 class Mock 1246 { 1247 public: 1248 MAKE_MOCK1(func, void(int*)); 1249 MAKE_MOCK1(func, void(char*)); 1250 }; 1251 1252 using namespace trompeloeil; 1253 1254 void test() 1255 { 1256 Mock m; 1257 1258 REQUIRE_CALL(m, func(ANY(int*))); 1259 REQUIRE_CALL(m, func(ne<char*>(nullptr))); 1260 1261 func(&m); 1262 } 1263 ``` 1264 1265 Above, each of the `func` overloads must be called once, the `int*` version with 1266 any pointer value at all, and the `char*` version with a non-null value. 1267 1268 Matching overloads on constness is done by placing the expectation on 1269 a const or non-const object. 1270 1271 Example: 1272 1273 ```Cpp 1274 class Mock 1275 { 1276 public: 1277 MAKE_MOCK1(func, void(int)); 1278 MAKE_CONST_MOCK1(func, void(int)); 1279 }; 1280 1281 void test() 1282 { 1283 Mock m; 1284 1285 REQUIRE_CALL(m, func(3)); // non-const overload 1286 1287 const Mock& mc = m; 1288 REQUIRE_CALL(mc, func(-3)); // const overload 1289 1290 m.func(3); // calls non-const overload 1291 mc.func(-3); // calls const overload 1292 } 1293 ``` 1294 1295 ### <A name="side_effects"/> Define side effects for matching calls 1296 1297 A side effect, in *Trompeloeil* parlance, is something that is done after 1298 a match has been made for an [expectation](reference.md/#expectation), and 1299 before returning (or throwing). 1300 1301 Typical side effects are: 1302 1303 - Setting out parameters 1304 - Capturing in parameters 1305 - Calling other functions 1306 1307 Example: 1308 1309 ```Cpp 1310 class Dispatcher 1311 { 1312 public: 1313 MAKE_MOCK1(subscribe, void(std::function<void(const std::string&)>)); 1314 }; 1315 1316 using trompeloeil::_; 1317 1318 void test() 1319 { 1320 Dispatcher d; 1321 1322 std::vector<std::function<void(const std::string&)>> clients; 1323 1324 { 1325 REQUIRE_CALL(d, subscribe(_)) 1326 .LR_SIDE_EFFECT(clients.push_back(std::move(_1))) 1327 .TIMES(AT_LEAST(1)); 1328 1329 func(&d); 1330 } 1331 for (auto& cb : clients) cb("meow"); 1332 } 1333 ``` 1334 1335 Above, any call to `d.subscribe(...)` will have the side effect that the 1336 parameter value is stored in the local vector `clients`. 1337 1338 The test then goes on to call all subscribers. 1339 1340 [**`LR_SIDE_EFFECT(...)`**](reference.md/#LR_SIDE_EFFECT) accesses references 1341 to local variables. There is also 1342 [**`SIDE_EFFECT(...)`**](reference.md/#SIDE_EFFECT), which accesses copies of 1343 local variables. 1344 1345 ### <A name="return_values"/> Return values from matching calls 1346 1347 An [expectation](reference.md/#expectation) on a non-void function 1348 must return something or [throw](#throw) an exception. There are no default 1349 values. Returning is easy, however. Just use a 1350 [**`.RETURN(...)`**](reference.md/#RETURN) or 1351 [**`.LR_RETURN(...)`**](reference.md/#LR_RETURN) with an expression of 1352 the right type. 1353 1354 Example: 1355 1356 ```Cpp 1357 class Dictionary 1358 { 1359 public: 1360 using id_t = size_t; 1361 MAKE_MOCK1(lookup, std::string(id_t)); 1362 }; 1363 1364 using trompeloeil::ge; // greater than or equal 1365 using trompeloeil::lt; // less than 1366 1367 void test() 1368 { 1369 Dictionary d; 1370 std::vector<std::string> dict{...}; 1371 1372 ALLOW_CALL(d, lookup(ge(dict.size()))) 1373 .RETURN(""); // create std::string from "" 1374 ALLOW_CALL(d, lookup(lt(dict.size()))) 1375 .LR_RETURN(dict[_1]); // access element in vector 1376 func(&d); 1377 } 1378 ``` 1379 1380 Above, the [matchers](reference.md/#matcher) [**`lt(...)`**](reference.md/#lt) 1381 and [**`ge(...)`**](reference.md/#ge) are used to ensure that the indexing 1382 in the local variable `dict` can be made safely. Note that the first 1383 [expectation](reference.md/#expectation) does not match the return type 1384 exactly, but is something that can be implicitly converted. 1385 1386 [**`LR_RETURN(...)`**](reference.md/#LR_RETURN) is used in the second to 1387 avoid copying the vector, since [**`RETURN(...)`**](reference.md/#RETURN) 1388 always accesses copies of local variables. 1389 1390 ### <A name="return_references"/> Return references from matching calls 1391 1392 Returning references from matching [expectations](reference.md/#expectation) 1393 exposes some peculiarities in the language. Specifically, it is not 1394 allowed to return a captured local variable as a reference in 1395 [**`RETURN(...)`**](reference.md/#RETURN), and in 1396 [**`LR_RETURN(...)`**](reference.md/#LR_RETURN) a returned variable must be 1397 decorated to ensure that a reference is intended. 1398 1399 Example: 1400 1401 ```Cpp 1402 class Dictionary 1403 { 1404 public: 1405 using id_t = size_t; 1406 MAKE_MOCK1(lookup, const std::string&(id_t)); 1407 }; 1408 1409 using trompeloeil::gt; // greater than or equal 1410 using trompeloeil::lt; // less than 1411 1412 std::string global_empty; 1413 1414 void test() 1415 { 1416 Dictionary d; 1417 std::vector<std::string> dict{...}; 1418 1419 std::string empty; 1420 1421 ALLOW_CALL(d, lookup(gt(dict.size()))) 1422 .LR_RETURN((empty)); // extra () -> reference to local variable 1423 ALLOW_CALL(d, lookup(dict.size())) 1424 .LR_RETURN(std::ref(empty)); // reference to local variable 1425 ALLOW_CALL(d, lookup(lt(dict.size()))) 1426 .LR_RETURN(dict[_1]); // result of function call 1427 ALLOW_CALL(d, lookup(0)) 1428 .RETURN(std::ref(global_empty)); // reference to global variable 1429 func(&d); 1430 } 1431 ``` 1432 1433 Captured variables that are returned as references must either be enclosed in 1434 extra parenthesis, or 1435 [`std::ref()`](http://en.cppreference.com/w/cpp/utility/functional/ref). 1436 1437 Returning a reference obtained from a function call, however, does not 1438 require any extra decoration, as the third 1439 [expectation](reference.md/#expectation) above, which looks up values in 1440 `dict` shows. 1441 1442 ### <A name="throw"/> Throwing exceptions from matching calls 1443 1444 To throw an exception, just add a [**`.THROW(...)`**](reference.md/#THROW) 1445 or [**`.LR_THROW(...)`**](reference.md/#LR_THROW), with the value to throw. 1446 For non-void functions, [**`.LR_THROW(...)`**](reference.md/#LR_THROW) and 1447 [**`.THROW(...)`**](reference.md/#THROW) takes the place of a 1448 [**`.RETURN(...)`**](reference.md/#RETURN) or 1449 [**`.LR_RETURN(...)`**](reference.md/#LR_RETURN). 1450 1451 Example: 1452 1453 ```Cpp 1454 class Dictionary 1455 { 1456 public: 1457 using id_t = size_t; 1458 MAKE_CONST_MOCK1(lookup, const std::string&(id_t)); 1459 }; 1460 1461 using trompeloeil::_; // matches anything 1462 1463 void test() 1464 { 1465 Dictionary d; 1466 std::vector<std::string> dict{...}; 1467 1468 ALLOW_CALL(d, lookup(_)) 1469 .LR_WITH(_1 >= dict.size()) 1470 .THROW(std::out_of_range("index too large for dictionary")); 1471 1472 ALLOW_CALL(d, lookup(_)) 1473 .LR_WITH(_1 < dict.size()) 1474 .LR_RETURN(dict[_1]); 1475 1476 func(&d); 1477 } 1478 ``` 1479 1480 Above, any call to `d.lookup(...)` with an index within the size of the 1481 vector will return the string reference, while any call with an index 1482 outside the size of the vector will throw a `std::out_of_range` exception. 1483 1484 ### <A name="allowing_any"/> Allowing any call 1485 1486 By default it is illegal to call any 1487 [mock function](reference.md/#mock_function) and you provide narrow specific 1488 expectations according to the needs of your test. However, sometimes it makes 1489 sense to have a wide-open default. That is done with the 1490 [expectations](reference.md/#expectation) 1491 [**`ALLOW_CALL(...)`**](reference.md/#ALLOW_CALL) and 1492 [**`NAMED_ALLOW_CALL(...)`**](reference.md/#NAMED_ALLOW_CALL). The difference 1493 between them is that **`ALLOW_CALL`** is local in nature and is only valid 1494 until the end of the scope, while **`NAMED_ALLOW_CALL(...)`** can be bound 1495 to a `std::unique_ptr<trompeloeil::expectation>`, which you can control the 1496 lifetime of. 1497 1498 Example: 1499 1500 ```Cpp 1501 template <typename T> 1502 class Allocator 1503 { 1504 public: 1505 MAKE_MOCK1(allocate, T*(size_t)); 1506 MAKE_MOCK1(deallocate, void(T*)); 1507 }; 1508 1509 using trompeloeil::_; 1510 1511 void test_no_mem() 1512 { 1513 Allocator<int> ai; 1514 1515 ALLOW_CALL(ai, allocate(_)) 1516 .RETURN(nullptr); 1517 1518 ALLOW_CALL(ai, deallocate(nullptr)); 1519 1520 hairy_int_job(&ai); 1521 } 1522 ``` 1523 1524 The simplistic allocator above is rigged to allow any attempts to allocate 1525 memory, but always return `nullptr`, and only allow deallocation of 1526 `nullptr`. 1527 1528 ### <A name="temporary_disallow"/> Temporarily disallowing matching calls 1529 1530 Just as it is sometimes convenient to provide a blanket default behaviour, 1531 it is sometimes desirable to temporarily ban calls. 1532 1533 Example: 1534 1535 ```Cpp 1536 #include "hairy_job.h" 1537 1538 template <typename T> 1539 class Allocator 1540 { 1541 public: 1542 MAKE_MOCK1(allocate, T*(size_t)); 1543 MAKE_MOCK1(deallocate, void(T*)); 1544 }; 1545 1546 using trompeloeil::_; 1547 1548 void test_restricted_mem() 1549 { 1550 Allocator<int> ai; 1551 1552 ALLOW_CALL(ai, allocate(_)) 1553 .RETURN(new int[_1]); 1554 1555 ALLOW_CALL(ai, deallocate(_)) 1556 .SIDE_EFFECT(delete[] _1); 1557 1558 hairy_job<int, Allocator<int>> job(ai, initial_data); 1559 1560 { 1561 FORBID_CALL(ai, allocate(_)); 1562 1563 job.churn(); // must not allocate memory 1564 } 1565 1566 job.get_result(); // may allocate memory 1567 } 1568 ``` 1569 1570 Above we see a simplistic Allocator that by default allocates and deallocates 1571 arrays. 1572 1573 The `hairy_job` uses the Allocator for its setup, and is expected to allocate 1574 all memory it needs for `churn()` in its constructor. 1575 1576 That `churn()` doesn't use the allocator is ensured by the local scope, in 1577 which all calls to `allocate(...)` are forbidden. 1578 1579 This pattern is quite common when writing tests with *Trompeloeil*. Use 1580 wide defaults in the scope of the test case (or in a fixture), and use 1581 local scopes with specifics, be they forbidden or exact requirements. 1582 1583 ### <A name="sequences"/> Expecting several matching calls in some sequences 1584 1585 By default all [expectations](reference.md/#expectation) are equal, and the 1586 only sequencing relationship is that if several match a call, the one last 1587 created is the one matched. 1588 1589 This means that [expectations](reference.md/#expectation) that do not compete 1590 for matching the same call have no ordering relationship at all, they are 1591 logically parallel. 1592 1593 Often this is exactly what you want. When you poke an object, you want this and 1594 that thing to happen and the order between them is irrelevant. For example, 1595 if calling callbacks stored in a hash table, you don't want to impose an 1596 order of those calls. 1597 1598 There are two very different reasons for using sequence control with 1599 *Trompeloeil*. 1600 1601 One is hinted at above, to impose an order between 1602 [expectations](reference.md/#expectation) that are logically parallel. The 1603 other is to set an exact order of indistinguishable 1604 [expectations](reference.md/#expectation). The latter can be achieved by setting 1605 them up in reverse order of matching, but this can make the test code very 1606 difficult to read. 1607 1608 First example. Impose an order between logically parallel calls: 1609 1610 ```Cpp 1611 class FileOps 1612 { 1613 public: 1614 using handle = int; 1615 MAKE_MOCK1(open, handle(const std::string&)); 1616 MAKE_MOCK3(write, size_t(handle, const char*, size_t)); 1617 MAKE_MOCK1(close, void(handle)); 1618 }; 1619 1620 using trompeloeil::ne; 1621 1622 void test() 1623 { 1624 FileOps ops; 1625 1626 trompeloeil::sequence seq; 1627 1628 int handle = 4711; 1629 1630 REQUIRE_CALL(ops, open("name")) 1631 .RETURN(handle) 1632 .IN_SEQUENCE(seq); 1633 1634 REQUIRE_CALL(ops, write(handle, ne(nullptr), ne(0))) 1635 .RETURN(_3) 1636 .IN_SEQUENCE(seq); 1637 1638 REQUIRE_CALL(ops, close(handle)) 1639 .IN_SEQUENCE(seq); 1640 1641 test_writes(&ops); 1642 } 1643 ``` 1644 1645 Without the use of `trompeloeil::sequence` above, all three 1646 [expectations](reference.md/#expectation) would be logically parallel and 1647 all permutations of matches would be considered equally correct. 1648 1649 By imposing an order between them, there is now only one legal sequence 1650 of calls. 1651 1652 The other example is to provide an order between equally matching calls. 1653 Suppose we want the `write` function above to first return 0 once and then 1654 give the desired result: 1655 1656 ```Cpp 1657 class FileOps 1658 { 1659 public: 1660 using handle = int; 1661 MAKE_MOCK1(open, handle(const std::string&)); 1662 MAKE_MOCK3(write, size_t(handle, const char*, size_t)); 1663 MAKE_MOCK1(close, void(handle)); 1664 }; 1665 1666 using trompeloeil::ne; 1667 1668 void test() 1669 { 1670 FileOps ops; 1671 1672 trompeloeil::sequence seq; 1673 1674 int handle = 4711; 1675 1676 REQUIRE_CALL(ops, open("name")) 1677 .RETURN(handle) 1678 .IN_SEQUENCE(seq); 1679 1680 REQUIRE_CALL(ops, write(handle, ne(nullptr), ne(0))) 1681 .RETURN(0) // indicate failure 1682 .IN_SEQUENCE(seq); 1683 1684 REQUIRE_CALL(ops, write(handle, ne(nullptr), ne(0))) 1685 .RETURN(_3) // successful retry 1686 .IN_SEQUENCE(seq); 1687 1688 REQUIRE_CALL(ops, close(handle)) 1689 .IN_SEQUENCE(seq); 1690 1691 test_writes(&ops); 1692 } 1693 ``` 1694 1695 Here the two calls to `write` are supposed to be made with exactly the same 1696 parameters, so they cannot be distinguished that way. We want the first 1697 call to indicate intermittent failure, and to be followed by a retry 1698 that will succeed. 1699 1700 [**`.IN_SEQUENCE(...)`**](reference.md/#IN_SEQUENCE) can refer to several 1701 sequence objects, which is a way to allow some variation in order, without 1702 being too lax. For a more thorough walk through, see the blog post [Sequence 1703 control with the Trompeloeil C\+\+14 Mocking Framework](http://playfulprogramming.blogspot.se/2015/01/sequence-control-with-trompeloeil-c.html) 1704 1705 [**`.IN_SEQUENCE(...)`**](reference.md/#IN_SEQUENCE) can also be used on 1706 [**`REQUIRE_DESTRUCTION(...)`**](reference.md/#REQUIRE_DESTRUCTION) and 1707 [**`NAMED_REQUIRE_DESTRUCTION(...)`**](reference.md/#NAMED_REQUIRE_DESTRUCTION). 1708 1709 ### <A name="match_count"/> Expecting matching calls a certain number of times 1710 1711 By default [**`REQUIRE_CALL(...)`**](reference.md/#REQUIRE_CALL) needs exactly 1712 one matching call, otherwise a violation is reported. Sometimes the need is 1713 for something else. A modifier [**`TIMES(...)`**](reference.md/#TIMES) is used 1714 to change that. You can either specify an exact number of times matching calls 1715 must be made, or a range of numbers. 1716 1717 Example: 1718 1719 ```Cpp 1720 class Mock 1721 { 1722 public: 1723 MAKE_MOCK1(func, void(int)); 1724 }; 1725 1726 void some_test() 1727 { 1728 Mock m; 1729 1730 REQUIRE_CALL(m, func(0)) 1731 .TIMES(2); 1732 1733 REQUIRE_CALL(m, func(1)) 1734 .TIMES(3, 5); 1735 1736 REQUIRE_CALL(m, func(2)) 1737 .TIMES(AT_LEAST(3)); 1738 1739 REQUIRE_CALL(m, func(3)) 1740 .TIMES(AT_MOST(4)); 1741 1742 func(&m); 1743 } 1744 ``` 1745 1746 Above, `m.func(0)` must be called exactly twice. `m.func(1)` must be called three, 1747 four or five times. The call `m.func(2)` must be made three or more times. Finally 1748 `m.func(4)` must not be called more than four times. 1749 1750 ## <A name="lifetime"/> Controlling lifetime of mock objects 1751 1752 If you test a case where you hand over ownership of a 1753 [mock object](reference.md/#mock_object), you may want to test that the mock 1754 object is destroyed when intended. For this there is a modifier class 1755 template `trompeloeil::deathwatched<T>` and the macros 1756 [**`REQUIRE_DESTRUCTION(...)`**](reference.md/#REQUIRE_DESTRUCTION) and 1757 [**`NAMED_REQUIRE_DESTRUCTION(...)`**](reference.md/#NAMED_REQUIRE_DESTRUCTION). 1758 1759 Example: 1760 1761 ```Cpp 1762 class Mock 1763 { 1764 public: 1765 virtual ~Mock() {} // virtual destructor required for deathwatched<> 1766 MAKE_MOCK1(func, void(int)); 1767 } 1768 1769 template <typename T> 1770 class consumer 1771 { 1772 public: 1773 consumer(T&&); 1774 void poke(int n); 1775 private: 1776 ... 1777 }; 1778 1779 void consume_test() 1780 { 1781 auto owner = std::make_unique<trompeloeil::deathwatched<Mock>>(); 1782 1783 auto mock = owner.get(); // use raw unowned pointer 1784 1785 consumer<Mock> c(std::move(owner)); 1786 1787 { 1788 REQUIRE_CALL(*mock, func(3)); 1789 1790 c.poke(3); 1791 } 1792 { 1793 REQUIRE_CALL(*mock, func(-1)); 1794 REQUIRE_DESTRUCTION(*mock); 1795 1796 c.poke(0); 1797 } 1798 } 1799 ``` 1800 1801 Above, the constructor of object `c` takes ownership of the 1802 [mock object](reference.md/#mock_object). 1803 1804 Since the mock object is on deathwatch, destruction is reported as a violation. 1805 Thus we can be sure that if the constructor destroys the mock object, the 1806 test will fail. Likewise if the call `c.poke(3)` would destroy the mock object. 1807 1808 The local scope afterwards has a requirement that the mock object *is* destroyed. 1809 If the call `c.poke(0)` does not destroy the mock, a violation will be reported 1810 and fail the test. There is an implied order that the mock function 1811 `func(-1)` is called before the destruction of the mock object, 1812 since destroying any mock object that still has 1813 [expectations](reference.md/#expectation) is reported as a violation. It is also 1814 possible to be explicit with the sequencing by using 1815 [**`IN_SEQUENCE(...)`**](reference.md/#IN_SEQUENCE) on both 1816 [**`REQUIRE_CALL(...)`**](reference.md/#REQUIRE_CALL) and 1817 [**`REQUIRE_DESTRUCTION(...)`**](reference.md/#REQUIRE_DESTRUCTION), as below: 1818 1819 ```Cpp 1820 { 1821 trompeloeil::sequence s; 1822 REQUIRE_CALL(*mock, func(-1)); 1823 .IN_SEQUENCE(s); 1824 REQUIRE_DESTRUCTION(*mock); 1825 .IN_SEQUENCE(s); 1826 1827 c.poke(0); 1828 } 1829 ``` 1830 1831 ## <A name="custom_formatting"/> Customize output format of values 1832 1833 When [tracing](#tracing) or printing parameter values in violation reports, 1834 the values are printed using their 1835 [stream insertion operators](http://en.cppreference.com/w/cpp/io/basic_ostream/operator_ltlt), 1836 if available, or hexadecimal dumps otherwise. If this is not what you want, you 1837 can provide your own output formatting used solely for testing. 1838 1839 The simple way to do this is to specialize a template [`printer<T>`](reference.md/#printer), 1840 in namespace `trompeloeil`, and its static member function `print`, for your type `T`. 1841 1842 Example: 1843 1844 ```Cpp 1845 class char_buff : public std::vector<char> 1846 { 1847 ... 1848 }; 1849 1850 namespace trompeloeil { 1851 template <> 1852 struct printer<char_buff> 1853 { 1854 static void print(std::ostream& os, const char_buff& b) 1855 { 1856 os << b.size() << "#{ "; 1857 for (auto v : b) { os << int(v) << " "; } 1858 os << "}"; 1859 } 1860 }; 1861 } 1862 ``` 1863 1864 Any reports involving the `char_buff` above will be printed using the 1865 `trompeloeil::print<char_buff>(...)` function, showing the size and integer values. 1866 1867 Note that partial specializations also work. Example: 1868 1869 ```Cpp 1870 template <typename T> 1871 class buff : public std::vector<T> 1872 { 1873 ... 1874 }; 1875 1876 namespace trompeloeil { 1877 template <typename T> 1878 struct printer<buff<T>> 1879 { 1880 static void print(std::ostream& os, const buff<T>& b) 1881 { 1882 os << b.size() << "#{ "; 1883 for (auto v : b) { os << v << " "; } 1884 os << "}"; 1885 } 1886 }; 1887 } 1888 ``` 1889 1890 **NOTE!** Older documentation refers to specializing a function 1891 [`trompeloeil::print(sd::ostream&, T const&)`](reference.md/#print). This still works, but has the 1892 disadvantage that partial specializations are not possible. 1893 1894 ## <A name="tracing"/> Tracing mocks 1895 1896 *Trompeloeil* offers tracing as a way of manually following the calls of mocks. 1897 In pure [TDD](https://en.wikipedia.org/wiki/Test-driven_development) this is 1898 hardly ever needed, but if you are in the undesirable situation of exploring 1899 the behaviour of code written without tests, tracing can vastly simplify your 1900 job. 1901 1902 Simply put, tracing is exposing which mocks are called with which values. 1903 1904 *Trompeloeil* offers a [*`stream_tracer`*](#stream_tracer), which outputs 1905 all calls to a 1906 [`std::ostream`](http://en.cppreference.com/w/cpp/io/basic_ostream), but you 1907 can also write your own [custom tracer](#custom_tracer). 1908 1909 ### <A name="stream_tracer"/> Using `trompeloeil::stream_tracer` 1910 1911 *`stream_tracer`* is a mechanism used to find out how 1912 [mock functions](reference.md/#mock_function) are called, by simply 1913 printing the calls with their parameter values on a 1914 [`std::ostream`](http://en.cppreference.com/w/cpp/io/basic_ostream) like 1915 [`std::cout`](http://en.cppreference.com/w/cpp/io/cout). 1916 1917 There is no requirement from *Trompeloeil* on the 1918 [expectations](reference.md/#expectation) placed on the mocks, but open 1919 blanket [**`ALLOW_CALL(...)`**](reference.md/#ALLOW_CALL) can be a good 1920 start until more detailed tests can be written. 1921 1922 Example: 1923 1924 ```Cpp 1925 class Mock 1926 { 1927 public: 1928 MAKE_MOCK1(create, int(const std::string&)); 1929 MAKE_MOCK1(func, std::string(int)); 1930 }; 1931 1932 using trompeloeil::_; 1933 1934 void tracing_test() 1935 { 1936 trompeloeil::stream_tracer tracer{std::cout}; 1937 1938 Mock m; 1939 1940 ALLOW_CALL(m, create(_)) 1941 .RETURN(3); 1942 1943 ALLOW_CALL(m, func(_)) 1944 .RETURN("value"); 1945 1946 weird_func(&m); 1947 } 1948 ``` 1949 1950 Running the above test will print on `std::cout` all calls made. A sample 1951 output may be: 1952 1953 ```text 1954 /tmp/t.cpp:33 1955 m.create(_) with. 1956 param _1 = hello 1957 1958 /tmp/t.cpp:36 1959 m.func(_) with. 1960 param _1 = 3 1961 1962 /tmp/t.cpp:36 1963 m.func(_) with. 1964 param _1 = 2 1965 1966 /tmp/t.cpp:36 1967 m.func(_) with. 1968 param _1 = 1 1969 ``` 1970 1971 ### <A name="custom_tracer"/> Writing custom tracers 1972 1973 If tracing is important, but the `trompeloeil::stream_tracer` for some reason 1974 does not satisfy your needs, you can easily write your own tracer. 1975 1976 There is a base class: 1977 1978 ```Cpp 1979 namespace trompeloeil { 1980 1981 class tracer { 1982 public: 1983 tracer(); 1984 virtual ~tracer(); 1985 virtual void trace(const char* file, 1986 unsigned long line, 1987 const std::string& call) = 0; 1988 }; 1989 1990 } 1991 ``` 1992 1993 Write your own class inheriting from `trompeloeil::tracer`, and implement the 1994 member function `trace`, to do what you need, and you're done. 1995 1996 ## <A name="custom_matchers"/> Writing custom matchers 1997 1998 If you need additional matchers over the ones provided by *Trompeloeil* 1999 ([**`eq(...)`**](reference.md/#eq), [**`ne(...)`**](reference.md/#ne), 2000 [**`lt(...)`**](reference.md/#lt), [**`le(...)`**](reference.md/#le), 2001 [**`gt(...)`**](reference.md/#gt) or [**`ge(...)`**](reference.md/#ge), 2002 and [**`re(...)`**](reference.md/#re)), you can easily do so. 2003 2004 Matchers are created using the aptly named function template 2005 [**`trompeloeil::make_matcher<Type>(...)`**](reference.md/#make_matcher), 2006 which takes a predicate lambda to check the condition, a print lambda for 2007 error messages, and any number of stored values. 2008 2009 All matchers, including your own custom designed matchers, can be used as 2010 [pointer matchers](#matching_pointers) by using the unary prefix `*` 2011 dereference operator. 2012 2013 ### <A name="typed_matcher"/> Typed matcher 2014 2015 The simplest matcher is a typed matcher. As an example of a typed matcher, an 2016 `any_of` matcher is shown, checking if a value is included in a range of 2017 values. It is implemented using the standard library algorithm 2018 [`std::any_of`](http://en.cppreference.com/w/cpp/algorithm/all_any_none_of), 2019 allowing a parameter to match any of a set of values. 2020 2021 To create a matcher, you provide a function that calls 2022 [**`trompeloeil::make_matcher<Type>(...)`**](reference.md/#make_matcher). 2023 2024 Below is the code for the function `any_of(std::initializer_list<int>)` 2025 which creates the matcher. 2026 2027 ```Cpp 2028 inline auto any_of(std::initializer_list<int> elements) 2029 { 2030 return trompeloeil::make_matcher<int>( // matcher of int 2031 2032 // predicate lambda that checks the condition 2033 [](int value, std::vector<int> const & alternatives) { 2034 return std::any_of(std::begin(alternatives), std::end(alternatives), 2035 [&value](int element) { return value == element; }); 2036 }, 2037 2038 // print lambda for error message 2039 [](std::ostream& os, std::vector<int> const& alternatives) { 2040 os << " matching any_of({"; 2041 char const* prefix=" "; 2042 for (auto& element : alternatives) 2043 { 2044 os << prefix << element; 2045 prefix = ", "; 2046 } 2047 os << " }"; 2048 }, 2049 2050 // stored value 2051 std::vector<int>(elements) 2052 ) 2053 } 2054 ``` 2055 2056 The *predicate* lambda is called with the value to check, and the stored values 2057 in order. 2058 2059 The *print* lambda is called with an `ostream&`, and the stored values in 2060 order. 2061 2062 You can capture values in the lambdas instead of storing in the matcher, but 2063 capturing them twice wastes memory, and what's in the lambda capture for the 2064 *predicate* lambda is not accessible in the *print* lambda. 2065 2066 Example usage: 2067 2068 ```Cpp 2069 class Mock 2070 { 2071 public: 2072 MAKE_MOCK1(func, void(int)); 2073 }; 2074 2075 void test() 2076 { 2077 Mock m; 2078 REQUIRE_CALL(m, func(any_of({1, 2, 4, 8}))); 2079 2080 m.func(7); 2081 } 2082 ``` 2083 2084 The *print* lambda is only called if a failure is reported. 2085 The report in the above example will look like: 2086 2087 ```text 2088 No match for call of m.func with signature void(int) with. 2089 param _1 = 7 2090 2091 Tried m.func(any_of({1, 2, 4, 8}) at file.cpp:12 2092 Expected _1 matching any_of({ 1, 2, 4, 8 }); 2093 ``` 2094 2095 Where everything after `Expected _1` is the output from the *print* lambda. 2096 2097 Extending the example above to work with any type, using a template, is 2098 straight forward: 2099 2100 ```Cpp 2101 template <typename T> 2102 inline auto any_of(std::initializer_list<T> elements) 2103 { 2104 return trompeloeil::make_matcher<T>( // matcher of T 2105 2106 // predicate lambda that checks the condition 2107 [](T const& value, std::vector<T> const & alternatives) { 2108 return std::any_of(std::begin(alternatives), std::end(alternatives), 2109 [&value](T const& element) { return value == element; }); 2110 }, 2111 2112 // print lambda for error message 2113 [](std::ostream& os, std::vector<T> const& alternatives) { 2114 os << " matching any_of({"; 2115 char const* prefix=" "; 2116 for (auto& element : alternatives) 2117 { 2118 os << prefix; 2119 ::trompeloeil::print(os, element); 2120 prefix = ", "; 2121 } 2122 os << " }"; 2123 }, 2124 2125 // stored value 2126 std::vector<T>(elements) 2127 ) 2128 } 2129 ``` 2130 2131 The only difference compared to the `int` version, is that the *predicate* 2132 lambda accepts values by `const&` instead of by value, since `T` might be 2133 expensive to copy, and that the *print* lambda uses 2134 [**`trompeloeil::print(...)`**](reference.md/#print) to print the elements. 2135 2136 ### <A name="duck_typed_matcher"/> Duck-typed matcher 2137 2138 A duck-typed matcher accepts any type that matches a required set of 2139 operations. An example of a duck-typed matcher is a 2140 [`not_empty()`](#not_empty) matcher, requiring that a `.empty()` member function 2141 of the parameter returns false. Another example is an 2142 [`is_clamped(min, max)`](#is_clamped) matcher, that ensures 2143 `min <= value && value <= max`. 2144 2145 A duck-typed matcher is created by specifying 2146 [**`trompeloeil::wildcard`**](reference.md/#wildcard) as the type to 2147 to [**`trompeloeil::make_matcher<Type>(...)`**](reference.md/#make_matcher). 2148 2149 It is also important that the *predicate* lambda uses a 2150 [trailing return type](http://arne-mertz.de/2015/08/new-c-features-auto-for-functions) 2151 specifier, which uses the required operations, in order to filter out calls 2152 that would not compile. 2153 2154 #### <A name="not_empty"/> A `not_empty()` matcher 2155 2156 Here's an implementation of a `not_empty()` matcher. 2157 2158 ```Cpp 2159 inline auto not_empty() 2160 { 2161 return trompeloeil::make_matcher<trompeloeil::wildcard>( // duck typed 2162 2163 // predicate lambda that checks the condition 2164 [](auto const& value) -> decltype(!value.empty()) { 2165 return !value.empty(); 2166 }, 2167 2168 // print lambda for error message 2169 [](std::ostream& os) { 2170 os << " is not empty"; 2171 } 2172 2173 // no stored values 2174 ); 2175 } 2176 ``` 2177 2178 It is unfortunate that the `!value.empty()` condition is expressed twice, 2179 but those are the rules of the language. 2180 2181 Here's an example of the usage. 2182 2183 ```Cpp 2184 struct C 2185 { 2186 MAKE_MOCK1(func, void(int)); 2187 MAKE_MOCK1(func, void(std::string&&)); 2188 MAKE_MOCK1(func2, void(std::vector<int> const&); 2189 }; 2190 2191 void test() 2192 { 2193 C obj; 2194 REQUIRE_CALL(obj, func(not_empty())); // std::string&& 2195 REQUIRE_CALL(obj, func2(not_empty())); // std::vector<int> const& 2196 func_under_test(&obj); 2197 } 2198 ``` 2199 2200 The expectation placed on `func()` is not ambiguous. While `func()` is 2201 overloaded on both `int` and `std::string&&`, the trailing return type 2202 specification on the *predicate* lambda causes 2203 [`SFINAE`](http://en.cppreference.com/w/cpp/language/sfinae) to kick in and 2204 chose only the `std::string&&` overload, since `.empty()` on an `int` would 2205 not compile. 2206 2207 If you make a mistake and place an expectation with a duck-typed matcher 2208 that cannot be used, the 2209 [`SFINAE`](http://en.cppreference.com/w/cpp/language/sfinae) on the 2210 trailing return type specification of the *predicate* lambda, ensures a 2211 compilation error at the site of 2212 use ([**`REQUIRE_CALL()`**](reference.md/#REQUIRE_CALL), 2213 [**`ALLOW_CALL()`**](reference.md/#ALLOW_CALL) or 2214 [**`FORBID_CALL()`**](reference.md/#FORBID_CALL).) 2215 2216 **TIP!** The expectation on `func()` in the example above is not 2217 ambiguous, as explained, but what if `func2` had been yet an overload of 2218 `func()` instead? You can easily make your matchers typed or duck-typed 2219 at the user's discretion. Alter the `not_empty()` to be a function template, 2220 with `trompeloeil::wildcard` as the default. 2221 2222 ```Cpp 2223 template <typename Type = trompeloeil::wildcard> 2224 inline auto not_empty() 2225 { 2226 return trompeloeil::make_matcher<Type>( // typed or duck typed 2227 2228 // predicate lambda that checks the condition 2229 [](auto const& value) -> decltype(!value.empty()) { 2230 return !value.empty(); 2231 }, 2232 2233 // print lambda for error message 2234 [](std::ostream& os) { 2235 os << " is not empty"; 2236 } 2237 2238 // no stored values 2239 ); 2240 } 2241 ``` 2242 2243 Now, if the user writes `EXPECT_CALL(obj, func(not_empty()))`, it is 2244 duck-typed, but if the user writes `EXPECT_CALL(obj, func<std::string&&>()` 2245 it will only match a call with a `std::string&&` parameter. 2246 2247 #### <A name="is_clamped"/> An `is_clamped(min, max)` matcher 2248 2249 Here's an implementation of an `is_clamped(min, max)` matcher. 2250 2251 ```Cpp 2252 template <typename Type = trompeloeil::wildcard, typename T, typename U> 2253 inline auto is_clamped(T const& min, U const& max) 2254 { 2255 return trompeloeil::make_matcher<Type>( // typed or duck typed 2256 2257 // predicate lambda that checks the condition 2258 [](auto const& value, auto const& lower, auto const& upper) 2259 -> decltype(lower <= value && value <= upper) 2260 { 2261 return !trompeloeil::is_null(value) && lower <= value && value <= upper; 2262 }, 2263 2264 // print lambda for error message 2265 [](std::ostream& os, auto const& lower, auto const& upper) { 2266 os << " clamped by ["; 2267 trompeloeil::print(os, lower); 2268 os << ", "; 2269 trompeloeil::print(os, upper); 2270 os << "]"; 2271 } 2272 2273 // stored values 2274 min, 2275 max 2276 ); 2277 } 2278 ``` 2279 2280 The [`trompeloeil::is_null(value)`](reference.md/#is_null) in the *predicate* 2281 lambda is there to prevent against e.g. clamp checks for `const char*` between 2282 two [`std::string`s](http://en.cppreference.com/w/cpp/string/basic_string), 2283 where the `const char*` may be *null*. The `is_null()` check is omitted in the 2284 trailing return specification, 2285 because it does not add anything to it - it always returns a `bool` and 2286 it works for all types. 2287 2288 By allowing `min` and `max` to be different types, it becomes possible to, 2289 e.g. check that a 2290 [`std::string_view`](http://en.cppreference.com/w/cpp/string/basic_string_view) 2291 is clamped by a 2292 [`std::string`](http://en.cppreference.com/w/cpp/string/basic_string) 2293 and a `const char*`. 2294 2295 **NOTE!** There is a bug in [GCC](https://gcc.gnu.org) versions 5.3 and 2296 lower, that does not allow trailing return type specifications in 2297 lambdas expressed in template functions. The work around is annoying but 2298 simple: 2299 2300 ```Cpp 2301 inline auto is_clamped_predicate() 2302 { 2303 return [](auto const& value, auto const& lower, auto const& upper) 2304 -> decltype(lower <= value && value <= upper) { 2305 return !trompeloeil::is_null(value) && lower <= value && value <= upper; 2306 }; 2307 } 2308 2309 template <typename Type = trompeloeil::wildcard, typename T, typename U> 2310 inline auto is_clamped(T const& min, U const% max) 2311 { 2312 return trompeloeil::make_matcher<Type>( // duck typed 2313 2314 // predicate lambda that checks the condition 2315 is_clamped_predicate(), 2316 ... 2317 ``` 2318 2319 **NOTE!** There is also a bug in 2320 [VisualStudio 2015 Update 3](https://www.visualstudio.com/en-us/news/releasenotes/vs2015-update3-vs), 2321 which does not respect the trailing return type specifications of 2322 lambdas in the context of template deduction. The work around is annoying but 2323 simple - use a `struct` instead: 2324 2325 ```Cpp 2326 struct is_clamped_predicate 2327 { 2328 template <typename T, typename L, typename U> 2329 auto operator()(T const& value, L const& lower, U const& upper) 2330 -> decltype(lower <= value && value <= upper) 2331 { 2332 return !trompeloeil::is_null(value) && lower <= value && value <= upper; 2333 } 2334 }; 2335 2336 template <typename Type = trompeloeil::wildcard, typename T, typename U> 2337 inline auto is_clamped(T const& min, U const% max) 2338 { 2339 return trompeloeil::make_matcher<Type>( // duck typed 2340 2341 // predicate lambda that checks the condition 2342 is_clamped_predicate(), 2343 ... 2344 ``` 2345 2346 ### <A name="legacy_matcher"/> Legacy Matchers 2347 2348 Before [**`trompeloeil::make_matcher<Type>(...)`**](reference.md/#make_matcher) 2349 was introduced in *Trompeloeil* v18, writing matchers was more elaborate. 2350 This section is here for those who need to maintain old matcher code. 2351 2352 All legacy matchers 2353 2354 - inherit from `trompeloeil::matcher` or `trompeloeil::typed_matcher<T>` 2355 - implement a `bool matches(parameter_value) const` member function 2356 - implement an output stream insertion operator 2357 2358 All legacy matchers can be used as 2359 [pointer matchers](#matching_pointers) by using the unary prefix `*` dereference 2360 operator. 2361 2362 ### Typed legacy matcher 2363 2364 Typed legacy matchers are relatively easy to understand. As an example of 2365 a typed matcher, an `any_of` matcher is shown, mimicking the behaviour of 2366 the standard library algorithm 2367 [`std::any_of`](http://en.cppreference.com/w/cpp/algorithm/all_any_none_of), 2368 allowing a parameter to match any of a set of values. 2369 2370 For templated matchers, it is often convenient to provide a function that 2371 creates the matcher object. Below is the code for `any_of_t<T>`, which is the 2372 matcher created by the `any_of(std::vector<T>)` function template. 2373 2374 ```Cpp 2375 template <typename T> 2376 class any_of_t : public trompeloeil::typed_matcher<T> 2377 { 2378 public: 2379 any_of_t(std::initializer_list<T> elements) 2380 : alternatives(elements) 2381 { 2382 } 2383 bool matches(T const& t) const 2384 { 2385 return std::any_of(std::begin(alternatives), std::end(alternatives), 2386 [&t](T const& val) { return t == val; }); 2387 } 2388 friend std::ostream& operator<<(std::ostream& os, any_of_t<T> const& t) 2389 { 2390 os << " matching any_of({"; 2391 char const* prefix=" "; 2392 for (auto& n : t.alternatives) 2393 { 2394 os << prefix; 2395 trompeloeil::print(os, n); 2396 prefix = ", "; 2397 } 2398 return os << " })"; 2399 } 2400 private: 2401 std::vector<T> alternatives; 2402 }; 2403 2404 template <typename T> 2405 auto any_of(std::initializer_list<T> elements) 2406 { 2407 return any_of_t<T>(elements); 2408 } 2409 ``` 2410 2411 The `matches` member function at accepts the parameter and returns 2412 `true` if the value is in the specified set, in this case if it is any 2413 of the values stored in the `alternatives` vector, otherwise `false`. 2414 2415 Example usage: 2416 2417 ```Cpp 2418 class Mock 2419 { 2420 public: 2421 MAKE_MOCK1(func, void(int)); 2422 }; 2423 2424 void test() 2425 { 2426 Mock m; 2427 REQUIRE_CALL(m, func(any_of({1, 2, 4, 8})); 2428 2429 m.func(7); 2430 } 2431 ``` 2432 2433 The output stream insertion operator is only called if a failure is reported. 2434 The report in the above example will look like: 2435 2436 ```text 2437 No match for call of m.func with signature void(int) with. 2438 param _1 = 7 2439 2440 Tried m.func(any_of({1, 2, 4, 8}) at file.cpp:12 2441 Expected _1 matching any_of({ 1, 2, 4, 8 }); 2442 ``` 2443 2444 Where everything after `Expected _1` is the output from the stream insertion 2445 operator. 2446 2447 ### Duck-typed legacy matcher 2448 2449 A duck-typed matcher accepts any type that matches a required set of 2450 operations. Duck-typed legacy matchers have a type conversion operator that 2451 selects which types it can operate on. The conversion operator is 2452 never implemented, but the signature must be available since it 2453 is used at compile time to select overload. 2454 2455 As an example of a duck-typed matcher is a `not_empty` matcher, requiring 2456 that a `.empty()` member function of the parameter returns false. 2457 2458 First the restricting 2459 [SFINAE](http://en.wikipedia.org/wiki/Substitution_failure_is_not_an_error) 2460 predicate used to match only types that has a `.empty()` member function. 2461 2462 ```Cpp 2463 template <typename T> 2464 class has_empty 2465 { 2466 template <typename U> 2467 static constexpr std::false_type func(...) { return {}; } 2468 template <typename U> 2469 static constexpr auto func(U const* u) -> decltype(u->empty(),std::true_type{}) 2470 { 2471 return {}; 2472 } 2473 public: 2474 static const bool value = func<T>(nullptr); 2475 }; 2476 ``` 2477 2478 Here `has_empty<T>::value` is true only for types `T` that has a `.empty()` 2479 member function callable on const objects. 2480 2481 ```Cpp 2482 class not_empty : public trompeloeil::matcher 2483 { 2484 public: 2485 template <typename T, 2486 typename = std::enable_if_t<has_empty<T>::value>> 2487 operator T() const; //1 2488 template <typename T> 2489 bool matches(T const& t) const //2 2490 { 2491 return !t.empty(); 2492 } 2493 friend std::ostream& operator<<(std::ostream& os, not_empty const&) 2494 { 2495 return os << " is not empty"; 2496 } 2497 }; 2498 ``` 2499 2500 At **//1** the type conversion operator selects for types that has a 2501 `.empty()` member function. 2502 [`std::enable_if_t<>`](http://en.cppreference.com/w/cpp/types/enable_if) 2503 ensures that no calls to mismatching types will occur, and that if no 2504 matching call can be found, a compilation error is generated at the site of 2505 use ([**`REQUIRE_CALL()`**](reference.md/#REQUIRE_CALL), 2506 [**`ALLOW_CALL()`**](reference.md/#ALLOW_CALL) or 2507 [**`FORBID_CALL()`**](reference.md/#FORBID_CALL).) 2508 2509 The `matches(T const&)` member function at **//2** becomes very simple. It 2510 does not need the [SFINAE]( 2511 http://en.wikipedia.org/wiki/Substitution_failure_is_not_an_error 2512 ) [`std::enable_if_t<>`]( 2513 http://en.cppreference.com/w/cpp/types/enable_if 2514 ) to select valid types, since a type mismatch gives a compilation error 2515 on the type conversion operator at **//1**. 2516 2517 The output stream insertion operator is neither more or less tricky than with 2518 typed matchers. Making violation reports readable may require some thought, 2519 however.