diff options
author | Jonathan Wendeborn <jonathan.wendeborn@bruker.com> | 2018-10-16 06:38:34 (GMT) |
---|---|---|
committer | Jonathan Wendeborn <jonathan.wendeborn@bruker.com> | 2018-10-16 06:38:34 (GMT) |
commit | 96d16157721cda1fd6981e6ce70645acb44220da (patch) | |
tree | c68f2939aaf8904f06e7235dfa4607f167fbb758 /googlemock | |
parent | 386391b0144201e0cf5f66d8ba1cb60a1076f673 (diff) | |
parent | 8c82ba48e433005b9e25835b4a342ef4dcc0cfc0 (diff) | |
download | googletest-96d16157721cda1fd6981e6ce70645acb44220da.zip googletest-96d16157721cda1fd6981e6ce70645acb44220da.tar.gz googletest-96d16157721cda1fd6981e6ce70645acb44220da.tar.bz2 |
Merge branch 'isnice' of https://github.com/BrukerJWD/googletest into isnice
Diffstat (limited to 'googlemock')
99 files changed, 7758 insertions, 19889 deletions
diff --git a/googlemock/CHANGES b/googlemock/CHANGES deleted file mode 100644 index d6f2f76..0000000 --- a/googlemock/CHANGES +++ /dev/null @@ -1,126 +0,0 @@ -Changes for 1.7.0: - -* All new improvements in Google Test 1.7.0. -* New feature: matchers DoubleNear(), FloatNear(), - NanSensitiveDoubleNear(), NanSensitiveFloatNear(), - UnorderedElementsAre(), UnorderedElementsAreArray(), WhenSorted(), - WhenSortedBy(), IsEmpty(), and SizeIs(). -* Improvement: Google Mock can now be built as a DLL. -* Improvement: when compiled by a C++11 compiler, matchers AllOf() - and AnyOf() can accept an arbitrary number of matchers. -* Improvement: when compiled by a C++11 compiler, matchers - ElementsAreArray() can accept an initializer list. -* Improvement: when exceptions are enabled, a mock method with no - default action now throws instead crashing the test. -* Improvement: added class testing::StringMatchResultListener to aid - definition of composite matchers. -* Improvement: function return types used in MOCK_METHOD*() macros can - now contain unprotected commas. -* Improvement (potentially breaking): EXPECT_THAT() and ASSERT_THAT() - are now more strict in ensuring that the value type and the matcher - type are compatible, catching potential bugs in tests. -* Improvement: Pointee() now works on an optional<T>. -* Improvement: the ElementsAreArray() matcher can now take a vector or - iterator range as input, and makes a copy of its input elements - before the conversion to a Matcher. -* Improvement: the Google Mock Generator can now generate mocks for - some class templates. -* Bug fix: mock object destruction triggerred by another mock object's - destruction no longer hangs. -* Improvement: Google Mock Doctor works better with newer Clang and - GCC now. -* Compatibility fixes. -* Bug/warning fixes. - -Changes for 1.6.0: - -* Compilation is much faster and uses much less memory, especially - when the constructor and destructor of a mock class are moved out of - the class body. -* New matchers: Pointwise(), Each(). -* New actions: ReturnPointee() and ReturnRefOfCopy(). -* CMake support. -* Project files for Visual Studio 2010. -* AllOf() and AnyOf() can handle up-to 10 arguments now. -* Google Mock doctor understands Clang error messages now. -* SetArgPointee<> now accepts string literals. -* gmock_gen.py handles storage specifier macros and template return - types now. -* Compatibility fixes. -* Bug fixes and implementation clean-ups. -* Potentially incompatible changes: disables the harmful 'make install' - command in autotools. - -Potentially breaking changes: - -* The description string for MATCHER*() changes from Python-style - interpolation to an ordinary C++ string expression. -* SetArgumentPointee is deprecated in favor of SetArgPointee. -* Some non-essential project files for Visual Studio 2005 are removed. - -Changes for 1.5.0: - - * New feature: Google Mock can be safely used in multi-threaded tests - on platforms having pthreads. - * New feature: function for printing a value of arbitrary type. - * New feature: function ExplainMatchResult() for easy definition of - composite matchers. - * The new matcher API lets user-defined matchers generate custom - explanations more directly and efficiently. - * Better failure messages all around. - * NotNull() and IsNull() now work with smart pointers. - * Field() and Property() now work when the matcher argument is a pointer - passed by reference. - * Regular expression matchers on all platforms. - * Added GCC 4.0 support for Google Mock Doctor. - * Added gmock_all_test.cc for compiling most Google Mock tests - in a single file. - * Significantly cleaned up compiler warnings. - * Bug fixes, better test coverage, and implementation clean-ups. - - Potentially breaking changes: - - * Custom matchers defined using MatcherInterface or MakePolymorphicMatcher() - need to be updated after upgrading to Google Mock 1.5.0; matchers defined - using MATCHER or MATCHER_P* aren't affected. - * Dropped support for 'make install'. - -Changes for 1.4.0 (we skipped 1.2.* and 1.3.* to match the version of -Google Test): - - * Works in more environments: Symbian and minGW, Visual C++ 7.1. - * Lighter weight: comes with our own implementation of TR1 tuple (no - more dependency on Boost!). - * New feature: --gmock_catch_leaked_mocks for detecting leaked mocks. - * New feature: ACTION_TEMPLATE for defining templatized actions. - * New feature: the .After() clause for specifying expectation order. - * New feature: the .With() clause for for specifying inter-argument - constraints. - * New feature: actions ReturnArg<k>(), ReturnNew<T>(...), and - DeleteArg<k>(). - * New feature: matchers Key(), Pair(), Args<...>(), AllArgs(), IsNull(), - and Contains(). - * New feature: utility class MockFunction<F>, useful for checkpoints, etc. - * New feature: functions Value(x, m) and SafeMatcherCast<T>(m). - * New feature: copying a mock object is rejected at compile time. - * New feature: a script for fusing all Google Mock and Google Test - source files for easy deployment. - * Improved the Google Mock doctor to diagnose more diseases. - * Improved the Google Mock generator script. - * Compatibility fixes for Mac OS X and gcc. - * Bug fixes and implementation clean-ups. - -Changes for 1.1.0: - - * New feature: ability to use Google Mock with any testing framework. - * New feature: macros for easily defining new matchers - * New feature: macros for easily defining new actions. - * New feature: more container matchers. - * New feature: actions for accessing function arguments and throwing - exceptions. - * Improved the Google Mock doctor script for diagnosing compiler errors. - * Bug fixes and implementation clean-ups. - -Changes for 1.0.0: - - * Initial Open Source release of Google Mock diff --git a/googlemock/CMakeLists.txt b/googlemock/CMakeLists.txt index beb259a..1fd758e 100644 --- a/googlemock/CMakeLists.txt +++ b/googlemock/CMakeLists.txt @@ -5,10 +5,6 @@ # ctest. You can select which tests to run using 'ctest -R regex'. # For more options, run 'ctest --help'. -# BUILD_SHARED_LIBS is a standard CMake variable, but we declare it here to -# make it prominent in the GUI. -option(BUILD_SHARED_LIBS "Build shared libraries (DLLs)." OFF) - option(gmock_build_tests "Build all of Google Mock's own tests." OFF) # A directory to find Google Test sources. @@ -37,8 +33,13 @@ endif() # as ${gmock_SOURCE_DIR} and to the root binary directory as # ${gmock_BINARY_DIR}. # Language "C" is required for find_package(Threads). -project(gmock CXX C) -cmake_minimum_required(VERSION 2.6.2) +if (CMAKE_VERSION VERSION_LESS 3.0) + project(gmock CXX C) +else() + cmake_policy(SET CMP0048 NEW) + project(gmock VERSION ${GOOGLETEST_VERSION} LANGUAGES CXX C) +endif() +cmake_minimum_required(VERSION 2.6.4) if (COMMAND set_up_hermetic_build) set_up_hermetic_build() @@ -50,28 +51,29 @@ endif() # if they are the same (the default). add_subdirectory("${gtest_dir}" "${gmock_BINARY_DIR}/gtest") + +# These commands only run if this is the main project +if(CMAKE_PROJECT_NAME STREQUAL "gmock" OR CMAKE_PROJECT_NAME STREQUAL "googletest-distribution") + # BUILD_SHARED_LIBS is a standard CMake variable, but we declare it here to + # make it prominent in the GUI. + option(BUILD_SHARED_LIBS "Build shared libraries (DLLs)." OFF) +else() + mark_as_advanced(gmock_build_tests) +endif() + # Although Google Test's CMakeLists.txt calls this function, the # changes there don't affect the current scope. Therefore we have to # call it again here. config_compiler_and_linker() # from ${gtest_dir}/cmake/internal_utils.cmake # Adds Google Mock's and Google Test's header directories to the search path. -include_directories("${gmock_SOURCE_DIR}/include" - "${gmock_SOURCE_DIR}" - "${gtest_SOURCE_DIR}/include" - # This directory is needed to build directly from Google - # Test sources. - "${gtest_SOURCE_DIR}") - -# Summary of tuple support for Microsoft Visual Studio: -# Compiler version(MS) version(cmake) Support -# ---------- ----------- -------------- ----------------------------- -# <= VS 2010 <= 10 <= 1600 Use Google Tests's own tuple. -# VS 2012 11 1700 std::tr1::tuple + _VARIADIC_MAX=10 -# VS 2013 12 1800 std::tr1::tuple -if (MSVC AND MSVC_VERSION EQUAL 1700) - add_definitions(/D _VARIADIC_MAX=10) -endif() +set(gmock_build_include_dirs + "${gmock_SOURCE_DIR}/include" + "${gmock_SOURCE_DIR}" + "${gtest_SOURCE_DIR}/include" + # This directory is needed to build directly from Google Test sources. + "${gtest_SOURCE_DIR}") +include_directories(${gmock_build_include_dirs}) ######################################################################## # @@ -81,32 +83,39 @@ endif() # Google Mock libraries. We build them using more strict warnings than what # are used for other targets, to ensure that Google Mock can be compiled by # a user aggressive about warnings. -cxx_library(gmock - "${cxx_strict}" - "${gtest_dir}/src/gtest-all.cc" - src/gmock-all.cc) - -cxx_library(gmock_main - "${cxx_strict}" - "${gtest_dir}/src/gtest-all.cc" - src/gmock-all.cc - src/gmock_main.cc) - +if (MSVC) + cxx_library(gmock + "${cxx_strict}" + "${gtest_dir}/src/gtest-all.cc" + src/gmock-all.cc) + + cxx_library(gmock_main + "${cxx_strict}" + "${gtest_dir}/src/gtest-all.cc" + src/gmock-all.cc + src/gmock_main.cc) +else() + cxx_library(gmock "${cxx_strict}" src/gmock-all.cc) + target_link_libraries(gmock PUBLIC gtest) + cxx_library(gmock_main "${cxx_strict}" src/gmock_main.cc) + target_link_libraries(gmock_main PUBLIC gmock) +endif() # If the CMake version supports it, attach header directory information # to the targets for when we are part of a parent build (ie being pulled # in via add_subdirectory() rather than being a standalone build). if (DEFINED CMAKE_VERSION AND NOT "${CMAKE_VERSION}" VERSION_LESS "2.8.11") - target_include_directories(gmock INTERFACE "${gmock_SOURCE_DIR}/include") - target_include_directories(gmock_main INTERFACE "${gmock_SOURCE_DIR}/include") + target_include_directories(gmock SYSTEM INTERFACE + "$<BUILD_INTERFACE:${gmock_build_include_dirs}>" + "$<INSTALL_INTERFACE:$<INSTALL_PREFIX>/${CMAKE_INSTALL_INCLUDEDIR}>") + target_include_directories(gmock_main SYSTEM INTERFACE + "$<BUILD_INTERFACE:${gmock_build_include_dirs}>" + "$<INSTALL_INTERFACE:$<INSTALL_PREFIX>/${CMAKE_INSTALL_INCLUDEDIR}>") endif() ######################################################################## # # Install rules -install(TARGETS gmock gmock_main - DESTINATION lib) -install(DIRECTORY ${gmock_SOURCE_DIR}/include/gmock - DESTINATION include) +install_project(gmock gmock_main) ######################################################################## # @@ -124,6 +133,20 @@ if (gmock_build_tests) # 'make test' or ctest. enable_testing() + if (WIN32) + file(GENERATE OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/$<CONFIG>/RunTest.ps1" + CONTENT +"$project_bin = \"${CMAKE_BINARY_DIR}/bin/$<CONFIG>\" +$env:Path = \"$project_bin;$env:Path\" +& $args") + elseif (MINGW) + file(GENERATE OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/RunTest.ps1" + CONTENT +"$project_bin = (cygpath --windows ${CMAKE_BINARY_DIR}/bin) +$env:Path = \"$project_bin;$env:Path\" +& $args") + endif() + ############################################################ # C++ tests built with standard compiler flags. @@ -136,6 +159,9 @@ if (gmock_build_tests) cxx_test(gmock-generated-matchers_test gmock_main) cxx_test(gmock-internal-utils_test gmock_main) cxx_test(gmock-matchers_test gmock_main) + if (MINGW) + target_compile_options(gmock-matchers_test PRIVATE "-Wa,-mbig-obj") + endif() cxx_test(gmock-more-actions_test gmock_main) cxx_test(gmock-nice-strict_test gmock_main) cxx_test(gmock-port_test gmock_main) @@ -143,7 +169,7 @@ if (gmock_build_tests) cxx_test(gmock_link_test gmock_main test/gmock_link2_test.cc) cxx_test(gmock_test gmock_main) - if (CMAKE_USE_PTHREADS_INIT) + if (DEFINED GTEST_HAS_PTHREAD) cxx_test(gmock_stress_test gmock) endif() @@ -154,23 +180,20 @@ if (gmock_build_tests) ############################################################ # C++ tests built with non-standard compiler flags. - cxx_library(gmock_main_no_exception "${cxx_no_exception}" - "${gtest_dir}/src/gtest-all.cc" src/gmock-all.cc src/gmock_main.cc) - - cxx_library(gmock_main_no_rtti "${cxx_no_rtti}" - "${gtest_dir}/src/gtest-all.cc" src/gmock-all.cc src/gmock_main.cc) + if (MSVC) + cxx_library(gmock_main_no_exception "${cxx_no_exception}" + "${gtest_dir}/src/gtest-all.cc" src/gmock-all.cc src/gmock_main.cc) - if (NOT MSVC OR MSVC_VERSION LESS 1600) # 1600 is Visual Studio 2010. - # Visual Studio 2010, 2012, and 2013 define symbols in std::tr1 that - # conflict with our own definitions. Therefore using our own tuple does not - # work on those compilers. - cxx_library(gmock_main_use_own_tuple "${cxx_use_own_tuple}" + cxx_library(gmock_main_no_rtti "${cxx_no_rtti}" "${gtest_dir}/src/gtest-all.cc" src/gmock-all.cc src/gmock_main.cc) - cxx_test_with_flags(gmock_use_own_tuple_test "${cxx_use_own_tuple}" - gmock_main_use_own_tuple test/gmock-spec-builders_test.cc) - endif() + else() + cxx_library(gmock_main_no_exception "${cxx_no_exception}" src/gmock_main.cc) + target_link_libraries(gmock_main_no_exception PUBLIC gmock) + cxx_library(gmock_main_no_rtti "${cxx_no_rtti}" src/gmock_main.cc) + target_link_libraries(gmock_main_no_rtti PUBLIC gmock) + endif() cxx_test_with_flags(gmock-more-actions_no_exception_test "${cxx_no_exception}" gmock_main_no_exception test/gmock-more-actions_test.cc) diff --git a/googlemock/README.md b/googlemock/README.md index 332beab..fced671 100644 --- a/googlemock/README.md +++ b/googlemock/README.md @@ -35,7 +35,7 @@ We hope you find it useful! * Does automatic verification of expectations (no record-and-replay needed). * Allows arbitrary (partial) ordering constraints on function calls to be expressed,. - * Lets a user extend it by defining new matchers and actions. + * Lets an user extend it by defining new matchers and actions. * Does not use exceptions. * Is easy to learn and use. @@ -53,18 +53,18 @@ the Apache License, which is different from Google Mock's license. If you are new to the project, we suggest that you read the user documentation in the following order: - * Learn the [basics](../googletest/docs/Primer.md) of + * Learn the [basics](../googletest/docs/primer.md) of Google Test, if you choose to use Google Mock with it (recommended). - * Read [Google Mock for Dummies](docs/ForDummies.md). + * Read [Google Mock for Dummies](../googlemock/docs/ForDummies.md). * Read the instructions below on how to build Google Mock. You can also watch Zhanyong's [talk](http://www.youtube.com/watch?v=sYpCyLI47rM) on Google Mock's usage and implementation. Once you understand the basics, check out the rest of the docs: - * [CheatSheet](docs/CheatSheet.md) - all the commonly used stuff + * [CheatSheet](../googlemock/docs/CheatSheet.md) - all the commonly used stuff at a glance. - * [CookBook](docs/CookBook.md) - recipes for getting things done, + * [CookBook](../googlemock/docs/CookBook.md) - recipes for getting things done, including advanced techniques. If you need help, please check the @@ -78,8 +78,8 @@ posting a question on the Google Mock is not a testing framework itself. Instead, it needs a testing framework for writing tests. Google Mock works seamlessly -with [Google Test](http://code.google.com/p/googletest/), but -you can also use it with [any C++ testing framework](googlemock/ForDummies.md#Using_Google_Mock_with_Any_Testing_Framework). +with [Google Test](https://github.com/google/googletest), but +you can also use it with [any C++ testing framework](../googlemock/docs/ForDummies.md#using-google-mock-with-any-testing-framework). ### Requirements for End Users ### @@ -90,7 +90,7 @@ You must use the bundled version of Google Test when using Google Mock. You can also easily configure Google Mock to work with another testing framework, although it will still need Google Test. Please read ["Using_Google_Mock_with_Any_Testing_Framework"]( - docs/ForDummies.md#Using_Google_Mock_with_Any_Testing_Framework) + ../googlemock/docs/ForDummies.md#using-google-mock-with-any-testing-framework) for instructions. Google Mock depends on advanced C++ features and thus requires a more @@ -125,6 +125,26 @@ build Google Mock and its tests, which has further requirements: ### Building Google Mock ### +#### Using CMake #### + +If you have CMake available, it is recommended that you follow the +[build instructions][gtest_cmakebuild] +as described for Google Test. + +If are using Google Mock with an +existing CMake project, the section +[Incorporating Into An Existing CMake Project][gtest_incorpcmake] +may be of particular interest. +To make it work for Google Mock you will need to change + + target_link_libraries(example gtest_main) + +to + + target_link_libraries(example gmock_main) + +This works because `gmock_main` library is compiled with Google Test. + #### Preparing to Build (Unix only) #### If you are using a Unix system and plan to use the GNU Autotools build @@ -226,35 +246,6 @@ We list the most frequently used macros below. For a complete list, see file [${GTEST\_DIR}/include/gtest/internal/gtest-port.h]( ../googletest/include/gtest/internal/gtest-port.h). -### Choosing a TR1 Tuple Library ### - -Google Mock uses the C++ Technical Report 1 (TR1) tuple library -heavily. Unfortunately TR1 tuple is not yet widely available with all -compilers. The good news is that Google Test 1.4.0+ implements a -subset of TR1 tuple that's enough for Google Mock's need. Google Mock -will automatically use that implementation when the compiler doesn't -provide TR1 tuple. - -Usually you don't need to care about which tuple library Google Test -and Google Mock use. However, if your project already uses TR1 tuple, -you need to tell Google Test and Google Mock to use the same TR1 tuple -library the rest of your project uses, or the two tuple -implementations will clash. To do that, add - - -DGTEST_USE_OWN_TR1_TUPLE=0 - -to the compiler flags while compiling Google Test, Google Mock, and -your tests. If you want to force Google Test and Google Mock to use -their own tuple library, just add - - -DGTEST_USE_OWN_TR1_TUPLE=1 - -to the compiler flags instead. - -If you want to use Boost's TR1 tuple library with Google Mock, please -refer to the Boost website (http://www.boost.org/) for how to obtain -it and set it up. - ### As a Shared Library (DLL) ### Google Mock is compact, so most users can build and link it as a static @@ -279,55 +270,24 @@ do if you are upgrading from an earlier version of Google Mock. You may need to explicitly enable or disable Google Test's own TR1 tuple library. See the instructions in section "[Choosing a TR1 Tuple -Library](../googletest/#choosing-a-tr1-tuple-library)". +Library](#choosing-a-tr1-tuple-library)". #### Upgrading from 1.4.0 or Earlier #### On platforms where the pthread library is available, Google Test and Google Mock use it in order to be thread-safe. For this to work, you may need to tweak your compiler and/or linker flags. Please see the -"[Multi-threaded Tests](../googletest#multi-threaded-tests -)" section in file Google Test's README for what you may need to do. +"[Multi-threaded Tests](../googletest/README.md#multi-threaded-tests)" section in file Google Test's README for what you may need to do. If you have custom matchers defined using `MatcherInterface` or `MakePolymorphicMatcher()`, you'll need to update their definitions to use the new matcher API ( -[monomorphic](http://code.google.com/p/googlemock/wiki/CookBook#Writing_New_Monomorphic_Matchers), -[polymorphic](http://code.google.com/p/googlemock/wiki/CookBook#Writing_New_Polymorphic_Matchers)). +[monomorphic](./docs/CookBook.md#writing-new-monomorphic-matchers), +[polymorphic](./docs/CookBook.md#writing-new-polymorphic-matchers)). Matchers defined using `MATCHER()` or `MATCHER_P*()` aren't affected. -### Developing Google Mock ### - -This section discusses how to make your own changes to Google Mock. - -#### Testing Google Mock Itself #### - -To make sure your changes work as intended and don't break existing -functionality, you'll want to compile and run Google Test's own tests. -For that you'll need Autotools. First, make sure you have followed -the instructions above to configure Google Mock. -Then, create a build output directory and enter it. Next, - - ${GMOCK_DIR}/configure # try --help for more info - -Once you have successfully configured Google Mock, the build steps are -standard for GNU-style OSS packages. - - make # Standard makefile following GNU conventions - make check # Builds and runs all tests - all should pass. - -Note that when building your project against Google Mock, you are building -against Google Test as well. There is no need to configure Google Test -separately. - -#### Contributing a Patch #### - -We welcome patches. -Please read the [Developer's Guide](docs/DevGuide.md) -for how you can contribute. In particular, make sure you have signed -the Contributor License Agreement, or we won't be able to accept the -patch. - Happy testing! [gtest_readme]: ../googletest/README.md "googletest" +[gtest_cmakebuild]: ../googletest/README.md#using-cmake "Using CMake" +[gtest_incorpcmake]: ../googletest/README.md#incorporating-into-an-existing-cmake-project "Incorporating Into An Existing CMake Project" diff --git a/googlemock/cmake/gmock.pc.in b/googlemock/cmake/gmock.pc.in new file mode 100644 index 0000000..2ef0fbc --- /dev/null +++ b/googlemock/cmake/gmock.pc.in @@ -0,0 +1,10 @@ +libdir=@CMAKE_INSTALL_FULL_LIBDIR@ +includedir=@CMAKE_INSTALL_FULL_INCLUDEDIR@ + +Name: gmock +Description: GoogleMock (without main() function) +Version: @PROJECT_VERSION@ +URL: https://github.com/google/googletest +Requires: gtest +Libs: -L${libdir} -lgmock @CMAKE_THREAD_LIBS_INIT@ +Cflags: -I${includedir} @GTEST_HAS_PTHREAD_MACRO@ @CMAKE_THREAD_LIBS_INIT@ diff --git a/googlemock/cmake/gmock_main.pc.in b/googlemock/cmake/gmock_main.pc.in new file mode 100644 index 0000000..04658fe --- /dev/null +++ b/googlemock/cmake/gmock_main.pc.in @@ -0,0 +1,10 @@ +libdir=@CMAKE_INSTALL_FULL_LIBDIR@ +includedir=@CMAKE_INSTALL_FULL_INCLUDEDIR@ + +Name: gmock_main +Description: GoogleMock (with main() function) +Version: @PROJECT_VERSION@ +URL: https://github.com/google/googletest +Requires: gmock +Libs: -L${libdir} -lgmock_main @CMAKE_THREAD_LIBS_INIT@ +Cflags: -I${includedir} @GTEST_HAS_PTHREAD_MACRO@ @CMAKE_THREAD_LIBS_INIT@ diff --git a/googlemock/configure.ac b/googlemock/configure.ac index 3b740f2..cb5e1a6 100644 --- a/googlemock/configure.ac +++ b/googlemock/configure.ac @@ -1,7 +1,7 @@ m4_include(../googletest/m4/acx_pthread.m4) AC_INIT([Google C++ Mocking Framework], - [1.7.0], + [1.8.0], [googlemock@googlegroups.com], [gmock]) @@ -101,7 +101,7 @@ AC_ARG_VAR([GTEST_VERSION], [The version of Google Test available.]) HAVE_BUILT_GTEST="no" -GTEST_MIN_VERSION="1.7.0" +GTEST_MIN_VERSION="1.8.0" AS_IF([test "x${enable_external_gtest}" = "xyes"], [# Begin filling in variables as we are able. @@ -129,8 +129,8 @@ AS_IF([test "x${HAVE_BUILT_GTEST}" = "xyes"], GTEST_LDFLAGS=`${GTEST_CONFIG} --ldflags` GTEST_LIBS=`${GTEST_CONFIG} --libs` GTEST_VERSION=`${GTEST_CONFIG} --version`], - [AC_CONFIG_SUBDIRS([../googletest]) - # GTEST_CONFIG needs to be executable both in a Makefile environmont and + [ + # GTEST_CONFIG needs to be executable both in a Makefile environment and # in a shell script environment, so resolve an absolute path for it here. GTEST_CONFIG="`pwd -P`/../googletest/scripts/gtest-config" GTEST_CPPFLAGS='-I$(top_srcdir)/../googletest/include' diff --git a/googlemock/docs/CheatSheet.md b/googlemock/docs/CheatSheet.md index ef4451b..d5757b2 100644 --- a/googlemock/docs/CheatSheet.md +++ b/googlemock/docs/CheatSheet.md @@ -5,7 +5,7 @@ ## Mocking a Normal Class ## Given -``` +```cpp class Foo { ... virtual ~Foo(); @@ -16,7 +16,7 @@ class Foo { }; ``` (note that `~Foo()` **must** be virtual) we can define its mock as -``` +```cpp #include "gmock/gmock.h" class MockFoo : public Foo { @@ -29,7 +29,7 @@ class MockFoo : public Foo { To create a "nice" mock object which ignores all uninteresting calls, or a "strict" mock object, which treats them as failures: -``` +```cpp NiceMock<MockFoo> nice_foo; // The type is a subclass of MockFoo. StrictMock<MockFoo> strict_foo; // The type is a subclass of MockFoo. ``` @@ -37,7 +37,7 @@ StrictMock<MockFoo> strict_foo; // The type is a subclass of MockFoo. ## Mocking a Class Template ## To mock -``` +```cpp template <typename Elem> class StackInterface { public: @@ -48,7 +48,7 @@ class StackInterface { }; ``` (note that `~StackInterface()` **must** be virtual) just append `_T` to the `MOCK_*` macros: -``` +```cpp template <typename Elem> class MockStack : public StackInterface<Elem> { public: @@ -64,8 +64,8 @@ If your mock function doesn't use the default calling convention, you can specify it by appending `_WITH_CALLTYPE` to any of the macros described in the previous two sections and supplying the calling convention as the first argument to the macro. For example, -``` - MOCK_METHOD_1_WITH_CALLTYPE(STDMETHODCALLTYPE, Foo, bool(int n)); +```cpp + MOCK_METHOD1_WITH_CALLTYPE(STDMETHODCALLTYPE, Foo, bool(int n)); MOCK_CONST_METHOD2_WITH_CALLTYPE(STDMETHODCALLTYPE, Bar, int(double x, double y)); ``` where `STDMETHODCALLTYPE` is defined by `<objbase.h>` on Windows. @@ -81,8 +81,8 @@ The typical flow is: 1. When a mock objects is destructed, Google Mock automatically verifies that all expectations on it have been satisfied. Here is an example: -``` -using ::testing::Return; // #1 +```cpp +using ::testing::Return; // #1 TEST(BarTest, DoesThis) { MockFoo foo; // #2 @@ -106,7 +106,7 @@ Google Mock has a **built-in default action** for any function that returns `void`, `bool`, a numeric value, or a pointer. To customize the default action for functions with return type `T` globally: -``` +```cpp using ::testing::DefaultValue; // Sets the default value to be returned. T must be CopyConstructible. @@ -120,7 +120,7 @@ DefaultValue<T>::Clear(); ``` To customize the default action for a particular method, use `ON_CALL()`: -``` +```cpp ON_CALL(mock_object, method(matchers)) .With(multi_argument_matcher) ? .WillByDefault(action); @@ -130,7 +130,7 @@ ON_CALL(mock_object, method(matchers)) `EXPECT_CALL()` sets **expectations** on a mock method (How will it be called? What will it do?): -``` +```cpp EXPECT_CALL(mock_object, method(matchers)) .With(multi_argument_matcher) ? .Times(cardinality) ? @@ -155,22 +155,25 @@ A **matcher** matches a _single_ argument. You can use it inside `ON_CALL()` or `EXPECT_CALL()`, or use it to validate a value directly: +| Matcher | Description | +|:--------|:------------| | `EXPECT_THAT(value, matcher)` | Asserts that `value` matches `matcher`. | -|:------------------------------|:----------------------------------------| | `ASSERT_THAT(value, matcher)` | The same as `EXPECT_THAT(value, matcher)`, except that it generates a **fatal** failure. | Built-in matchers (where `argument` is the function argument) are divided into several categories: ## Wildcard ## +| Matcher | Description | +|:--------|:------------| |`_`|`argument` can be any value of the correct type.| -|:--|:-----------------------------------------------| |`A<type>()` or `An<type>()`|`argument` can be any value of type `type`. | ## Generic Comparison ## -|`Eq(value)` or `value`|`argument == value`| +| Matcher | Description | |:---------------------|:------------------| +|`Eq(value)` or `value`|`argument == value`| |`Ge(value)` |`argument >= value`| |`Gt(value)` |`argument > value` | |`Le(value)` |`argument <= value`| @@ -178,6 +181,7 @@ divided into several categories: |`Ne(value)` |`argument != value`| |`IsNull()` |`argument` is a `NULL` pointer (raw or smart).| |`NotNull()` |`argument` is a non-null pointer (raw or smart).| +|`VariantWith<T>(m)` |`argument` is `variant<>` that holds the alternative of type T with a value matching `m`.| |`Ref(variable)` |`argument` is a reference to `variable`.| |`TypedEq<type>(value)`|`argument` has type `type` and is equal to `value`. You may need to use this instead of `Eq(value)` when the mock function is overloaded.| @@ -190,11 +194,12 @@ matcher will be changed. ## Floating-Point Matchers ## -|`DoubleEq(a_double)`|`argument` is a `double` value approximately equal to `a_double`, treating two NaNs as unequal.| -|:-------------------|:----------------------------------------------------------------------------------------------| -|`FloatEq(a_float)` |`argument` is a `float` value approximately equal to `a_float`, treating two NaNs as unequal. | -|`NanSensitiveDoubleEq(a_double)`|`argument` is a `double` value approximately equal to `a_double`, treating two NaNs as equal. | -|`NanSensitiveFloatEq(a_float)`|`argument` is a `float` value approximately equal to `a_float`, treating two NaNs as equal. | +| Matcher | Description | +|:-------------------|:---------------------------------------------------------------------------------------------------------| +|`DoubleEq(a_double)`|`argument` is a `double` value approximately equal to `a_double`, treating two NaNs as unequal. | +|`FloatEq(a_float)` |`argument` is a `float` value approximately equal to `a_float`, treating two NaNs as unequal. | +|`NanSensitiveDoubleEq(a_double)`|`argument` is a `double` value approximately equal to `a_double`, treating two NaNs as equal. | +|`NanSensitiveFloatEq(a_float)`|`argument` is a `float` value approximately equal to `a_float`, treating two NaNs as equal. | The above matchers use ULP-based comparison (the same as used in [Google Test](../../googletest/)). They @@ -204,30 +209,32 @@ the IEEE standard, which requires comparing two NaNs for equality to return false. The `NanSensitive*` version instead treats two NaNs as equal, which is often what a user wants. +| Matcher | Description | +|:--------|:------------| |`DoubleNear(a_double, max_abs_error)`|`argument` is a `double` value close to `a_double` (absolute error <= `max_abs_error`), treating two NaNs as unequal.| -|:------------------------------------|:--------------------------------------------------------------------------------------------------------------------| -|`FloatNear(a_float, max_abs_error)` |`argument` is a `float` value close to `a_float` (absolute error <= `max_abs_error`), treating two NaNs as unequal. | -|`NanSensitiveDoubleNear(a_double, max_abs_error)`|`argument` is a `double` value close to `a_double` (absolute error <= `max_abs_error`), treating two NaNs as equal. | -|`NanSensitiveFloatNear(a_float, max_abs_error)`|`argument` is a `float` value close to `a_float` (absolute error <= `max_abs_error`), treating two NaNs as equal. | +|`FloatNear(a_float, max_abs_error)`|`argument` is a `float` value close to `a_float` (absolute error <= `max_abs_error`), treating two NaNs as unequal.| +|`NanSensitiveDoubleNear(a_double, max_abs_error)`|`argument` is a `double` value close to `a_double` (absolute error <= `max_abs_error`), treating two NaNs as equal.| +|`NanSensitiveFloatNear(a_float, max_abs_error)`|`argument` is a `float` value close to `a_float` (absolute error <= `max_abs_error`), treating two NaNs as equal.| ## String Matchers ## The `argument` can be either a C string or a C++ string object: -|`ContainsRegex(string)`|`argument` matches the given regular expression.| -|:----------------------|:-----------------------------------------------| -|`EndsWith(suffix)` |`argument` ends with string `suffix`. | -|`HasSubstr(string)` |`argument` contains `string` as a sub-string. | +| Matcher | Description | +|:----------------------|:--------------------------------------------------| +|`ContainsRegex(string)`|`argument` matches the given regular expression. | +|`EndsWith(suffix)` |`argument` ends with string `suffix`. | +|`HasSubstr(string)` |`argument` contains `string` as a sub-string. | |`MatchesRegex(string)` |`argument` matches the given regular expression with the match starting at the first character and ending at the last character.| -|`StartsWith(prefix)` |`argument` starts with string `prefix`. | -|`StrCaseEq(string)` |`argument` is equal to `string`, ignoring case. | +|`StartsWith(prefix)` |`argument` starts with string `prefix`. | +|`StrCaseEq(string)` |`argument` is equal to `string`, ignoring case. | |`StrCaseNe(string)` |`argument` is not equal to `string`, ignoring case.| -|`StrEq(string)` |`argument` is equal to `string`. | -|`StrNe(string)` |`argument` is not equal to `string`. | +|`StrEq(string)` |`argument` is equal to `string`. | +|`StrNe(string)` |`argument` is not equal to `string`. | `ContainsRegex()` and `MatchesRegex()` use the regular expression syntax defined -[here](../../googletest/docs/AdvancedGuide.md#regular-expression-syntax). +[here](../../googletest/docs/advanced.md#regular-expression-syntax). `StrCaseEq()`, `StrCaseNe()`, `StrEq()`, and `StrNe()` work for wide strings as well. @@ -238,29 +245,30 @@ Most STL-style containers support `==`, so you can use container exactly. If you want to write the elements in-line, match them more flexibly, or get more informative messages, you can use: +| Matcher | Description | +|:--------|:------------| | `ContainerEq(container)` | The same as `Eq(container)` except that the failure message also includes which elements are in one container but not the other. | -|:-------------------------|:---------------------------------------------------------------------------------------------------------------------------------| -| `Contains(e)` | `argument` contains an element that matches `e`, which can be either a value or a matcher. | -| `Each(e)` | `argument` is a container where _every_ element matches `e`, which can be either a value or a matcher. | +| `Contains(e)` | `argument` contains an element that matches `e`, which can be either a value or a matcher. | +| `Each(e)` | `argument` is a container where _every_ element matches `e`, which can be either a value or a matcher. | | `ElementsAre(e0, e1, ..., en)` | `argument` has `n + 1` elements, where the i-th element matches `ei`, which can be a value or a matcher. 0 to 10 arguments are allowed. | | `ElementsAreArray({ e0, e1, ..., en })`, `ElementsAreArray(array)`, or `ElementsAreArray(array, count)` | The same as `ElementsAre()` except that the expected element values/matchers come from an initializer list, STL-style container, or C-style array. | -| `IsEmpty()` | `argument` is an empty container (`container.empty()`). | +| `IsEmpty()` | `argument` is an empty container (`container.empty()`). | | `Pointwise(m, container)` | `argument` contains the same number of elements as in `container`, and for all i, (the i-th element in `argument`, the i-th element in `container`) match `m`, which is a matcher on 2-tuples. E.g. `Pointwise(Le(), upper_bounds)` verifies that each element in `argument` doesn't exceed the corresponding element in `upper_bounds`. See more detail below. | -| `SizeIs(m)` | `argument` is a container whose size matches `m`. E.g. `SizeIs(2)` or `SizeIs(Lt(2))`. | +| `SizeIs(m)` | `argument` is a container whose size matches `m`. E.g. `SizeIs(2)` or `SizeIs(Lt(2))`. | | `UnorderedElementsAre(e0, e1, ..., en)` | `argument` has `n + 1` elements, and under some permutation each element matches an `ei` (for a different `i`), which can be a value or a matcher. 0 to 10 arguments are allowed. | | `UnorderedElementsAreArray({ e0, e1, ..., en })`, `UnorderedElementsAreArray(array)`, or `UnorderedElementsAreArray(array, count)` | The same as `UnorderedElementsAre()` except that the expected element values/matchers come from an initializer list, STL-style container, or C-style array. | -| `WhenSorted(m)` | When `argument` is sorted using the `<` operator, it matches container matcher `m`. E.g. `WhenSorted(UnorderedElementsAre(1, 2, 3))` verifies that `argument` contains elements `1`, `2`, and `3`, ignoring order. | +| `WhenSorted(m)` | When `argument` is sorted using the `<` operator, it matches container matcher `m`. E.g. `WhenSorted(ElementsAre(1, 2, 3))` verifies that `argument` contains elements `1`, `2`, and `3`, ignoring order. | | `WhenSortedBy(comparator, m)` | The same as `WhenSorted(m)`, except that the given comparator instead of `<` is used to sort `argument`. E.g. `WhenSortedBy(std::greater<int>(), ElementsAre(3, 2, 1))`. | Notes: * These matchers can also match: 1. a native array passed by reference (e.g. in `Foo(const int (&a)[5])`), and - 1. an array passed as a pointer and a count (e.g. in `Bar(const T* buffer, int len)` -- see [Multi-argument Matchers](#Multiargument_Matchers.md)). + 1. an array passed as a pointer and a count (e.g. in `Bar(const T* buffer, int len)` -- see [Multi-argument Matchers](#multiargument-matchers)). * The array being matched may be multi-dimensional (i.e. its elements can be arrays). * `m` in `Pointwise(m, ...)` should be a matcher for `::testing::tuple<T, U>` where `T` and `U` are the element type of the actual container and the expected container, respectively. For example, to compare two `Foo` containers where `Foo` doesn't support `operator==` but has an `Equals()` method, one might write: -``` +```cpp using ::testing::get; MATCHER(FooEq, "") { return get<0>(arg).Equals(get<1>(arg)); @@ -271,21 +279,24 @@ EXPECT_THAT(actual_foos, Pointwise(FooEq(), expected_foos)); ## Member Matchers ## +| Matcher | Description | +|:--------|:------------| |`Field(&class::field, m)`|`argument.field` (or `argument->field` when `argument` is a plain pointer) matches matcher `m`, where `argument` is an object of type _class_.| -|:------------------------|:---------------------------------------------------------------------------------------------------------------------------------------------| -|`Key(e)` |`argument.first` matches `e`, which can be either a value or a matcher. E.g. `Contains(Key(Le(5)))` can verify that a `map` contains a key `<= 5`.| -|`Pair(m1, m2)` |`argument` is an `std::pair` whose `first` field matches `m1` and `second` field matches `m2`. | +|`Key(e)`|`argument.first` matches `e`, which can be either a value or a matcher. E.g. `Contains(Key(Le(5)))` can verify that a `map` contains a key `<= 5`.| +|`Pair(m1, m2)`|`argument` is an `std::pair` whose `first` field matches `m1` and `second` field matches `m2`.| |`Property(&class::property, m)`|`argument.property()` (or `argument->property()` when `argument` is a plain pointer) matches matcher `m`, where `argument` is an object of type _class_.| ## Matching the Result of a Function or Functor ## -|`ResultOf(f, m)`|`f(argument)` matches matcher `m`, where `f` is a function or functor.| +| Matcher | Description | |:---------------|:---------------------------------------------------------------------| +|`ResultOf(f, m)`|`f(argument)` matches matcher `m`, where `f` is a function or functor.| ## Pointer Matchers ## -|`Pointee(m)`|`argument` (either a smart pointer or a raw pointer) points to a value that matches matcher `m`.| -|:-----------|:-----------------------------------------------------------------------------------------------| +| Matcher | Description | +|:------------------------|:-----------------------------------------------------------------------------------------------| +|`Pointee(m)` |`argument` (either a smart pointer or a raw pointer) points to a value that matches matcher `m`.| |`WhenDynamicCastTo<T>(m)`| when `argument` is passed through `dynamic_cast<T>()`, it matches matcher `m`. | ## Multiargument Matchers ## @@ -294,8 +305,9 @@ Technically, all matchers match a _single_ value. A "multi-argument" matcher is just one that matches a _tuple_. The following matchers can be used to match a tuple `(x, y)`: +| Matcher | Description | +|:--------|:------------| |`Eq()`|`x == y`| -|:-----|:-------| |`Ge()`|`x >= y`| |`Gt()`|`x > y` | |`Le()`|`x <= y`| @@ -305,37 +317,42 @@ be used to match a tuple `(x, y)`: You can use the following selectors to pick a subset of the arguments (or reorder them) to participate in the matching: +| Matcher | Description | +|:--------|:------------| |`AllArgs(m)`|Equivalent to `m`. Useful as syntactic sugar in `.With(AllArgs(m))`.| -|:-----------|:-------------------------------------------------------------------| |`Args<N1, N2, ..., Nk>(m)`|The tuple of the `k` selected (using 0-based indices) arguments matches `m`, e.g. `Args<1, 2>(Eq())`.| ## Composite Matchers ## You can make a matcher from one or more other matchers: -|`AllOf(m1, m2, ..., mn)`|`argument` matches all of the matchers `m1` to `mn`.| -|:-----------------------|:---------------------------------------------------| +| Matcher | Description | +|:-----------------------|:------------------------------------------------------------| +|`AllOf(m1, m2, ..., mn)`|`argument` matches all of the matchers `m1` to `mn`. | |`AnyOf(m1, m2, ..., mn)`|`argument` matches at least one of the matchers `m1` to `mn`.| -|`Not(m)` |`argument` doesn't match matcher `m`. | +|`Not(m)` |`argument` doesn't match matcher `m`. | ## Adapters for Matchers ## +| Matcher | Description | +|:--------|:------------| |`MatcherCast<T>(m)`|casts matcher `m` to type `Matcher<T>`.| -|:------------------|:--------------------------------------| -|`SafeMatcherCast<T>(m)`| [safely casts](CookBook.md#casting-matchers) matcher `m` to type `Matcher<T>`. | -|`Truly(predicate)` |`predicate(argument)` returns something considered by C++ to be true, where `predicate` is a function or functor.| +|`SafeMatcherCast<T>(m)`| [safely casts](CookBook.md#casting-matchers) matcher `m` to type `Matcher<T>`.| +|`Truly(predicate)`|`predicate(argument)` returns something considered by C++ to be true, where `predicate` is a function or functor.| ## Matchers as Predicates ## +| Matcher | Description | +|:--------|:------------| |`Matches(m)(value)`|evaluates to `true` if `value` matches `m`. You can use `Matches(m)` alone as a unary functor.| -|:------------------|:---------------------------------------------------------------------------------------------| -|`ExplainMatchResult(m, value, result_listener)`|evaluates to `true` if `value` matches `m`, explaining the result to `result_listener`. | -|`Value(value, m)` |evaluates to `true` if `value` matches `m`. | +|`ExplainMatchResult(m, value, result_listener)`|evaluates to `true` if `value` matches `m`, explaining the result to `result_listener`.| +|`Value(value, m)`|evaluates to `true` if `value` matches `m`.| ## Defining Matchers ## +| Matcher | Description | +|:--------|:------------| | `MATCHER(IsEven, "") { return (arg % 2) == 0; }` | Defines a matcher `IsEven()` to match an even number. | -|:-------------------------------------------------|:------------------------------------------------------| | `MATCHER_P(IsDivisibleBy, n, "") { *result_listener << "where the remainder is " << (arg % n); return (arg % n) == 0; }` | Defines a macher `IsDivisibleBy(n)` to match a number divisible by `n`. | | `MATCHER_P2(IsBetween, a, b, std::string(negation ? "isn't" : "is") + " between " + PrintToString(a) + " and " + PrintToString(b)) { return a <= arg && arg <= b; }` | Defines a matcher `IsBetween(a, b)` to match a value in the range [`a`, `b`]. | @@ -347,9 +364,10 @@ You can make a matcher from one or more other matchers: ## Matchers as Test Assertions ## -|`ASSERT_THAT(expression, m)`|Generates a [fatal failure](../../googletest/docs/Primer.md#assertions) if the value of `expression` doesn't match matcher `m`.| -|:---------------------------|:----------------------------------------------------------------------------------------------------------------------------------------------| -|`EXPECT_THAT(expression, m)`|Generates a non-fatal failure if the value of `expression` doesn't match matcher `m`. | +| Matcher | Description | +|:--------|:------------| +|`ASSERT_THAT(expression, m)`|Generates a [fatal failure](../../googletest/docs/primer.md#assertions) if the value of `expression` doesn't match matcher `m`.| +|`EXPECT_THAT(expression, m)`|Generates a non-fatal failure if the value of `expression` doesn't match matcher `m`.| # Actions # @@ -357,77 +375,83 @@ You can make a matcher from one or more other matchers: ## Returning a Value ## +| Matcher | Description | +|:--------|:------------| |`Return()`|Return from a `void` mock function.| -|:---------|:----------------------------------| |`Return(value)`|Return `value`. If the type of `value` is different to the mock function's return type, `value` is converted to the latter type <i>at the time the expectation is set</i>, not when the action is executed.| |`ReturnArg<N>()`|Return the `N`-th (0-based) argument.| |`ReturnNew<T>(a1, ..., ak)`|Return `new T(a1, ..., ak)`; a different object is created each time.| -|`ReturnNull()`|Return a null pointer. | +|`ReturnNull()`|Return a null pointer.| |`ReturnPointee(ptr)`|Return the value pointed to by `ptr`.| -|`ReturnRef(variable)`|Return a reference to `variable`. | +|`ReturnRef(variable)`|Return a reference to `variable`.| |`ReturnRefOfCopy(value)`|Return a reference to a copy of `value`; the copy lives as long as the action.| ## Side Effects ## +| Matcher | Description | +|:--------|:------------| |`Assign(&variable, value)`|Assign `value` to variable.| -|:-------------------------|:--------------------------| -| `DeleteArg<N>()` | Delete the `N`-th (0-based) argument, which must be a pointer. | -| `SaveArg<N>(pointer)` | Save the `N`-th (0-based) argument to `*pointer`. | -| `SaveArgPointee<N>(pointer)` | Save the value pointed to by the `N`-th (0-based) argument to `*pointer`. | -| `SetArgReferee<N>(value)` | Assign value to the variable referenced by the `N`-th (0-based) argument. | +|`DeleteArg<N>()`| Delete the `N`-th (0-based) argument, which must be a pointer.| +|`SaveArg<N>(pointer)`| Save the `N`-th (0-based) argument to `*pointer`.| +|`SaveArgPointee<N>(pointer)`| Save the value pointed to by the `N`-th (0-based) argument to `*pointer`.| +|`SetArgReferee<N>(value)` | Assign value to the variable referenced by the `N`-th (0-based) argument. | |`SetArgPointee<N>(value)` |Assign `value` to the variable pointed by the `N`-th (0-based) argument.| |`SetArgumentPointee<N>(value)`|Same as `SetArgPointee<N>(value)`. Deprecated. Will be removed in v1.7.0.| |`SetArrayArgument<N>(first, last)`|Copies the elements in source range [`first`, `last`) to the array pointed to by the `N`-th (0-based) argument, which can be either a pointer or an iterator. The action does not take ownership of the elements in the source range.| |`SetErrnoAndReturn(error, value)`|Set `errno` to `error` and return `value`.| -|`Throw(exception)` |Throws the given exception, which can be any copyable value. Available since v1.1.0.| +|`Throw(exception)`|Throws the given exception, which can be any copyable value. Available since v1.1.0.| ## Using a Function or a Functor as an Action ## +| Matcher | Description | +|:--------|:------------| |`Invoke(f)`|Invoke `f` with the arguments passed to the mock function, where `f` can be a global/static function or a functor.| -|:----------|:-----------------------------------------------------------------------------------------------------------------| -|`Invoke(object_pointer, &class::method)`|Invoke the {method on the object with the arguments passed to the mock function. | -|`InvokeWithoutArgs(f)`|Invoke `f`, which can be a global/static function or a functor. `f` must take no arguments. | -|`InvokeWithoutArgs(object_pointer, &class::method)`|Invoke the method on the object, which takes no arguments. | +|`Invoke(object_pointer, &class::method)`|Invoke the {method on the object with the arguments passed to the mock function.| +|`InvokeWithoutArgs(f)`|Invoke `f`, which can be a global/static function or a functor. `f` must take no arguments.| +|`InvokeWithoutArgs(object_pointer, &class::method)`|Invoke the method on the object, which takes no arguments.| |`InvokeArgument<N>(arg1, arg2, ..., argk)`|Invoke the mock function's `N`-th (0-based) argument, which must be a function or a functor, with the `k` arguments.| The return value of the invoked function is used as the return value of the action. When defining a function or functor to be used with `Invoke*()`, you can declare any unused parameters as `Unused`: -``` +```cpp double Distance(Unused, double x, double y) { return sqrt(x*x + y*y); } ... EXPECT_CALL(mock, Foo("Hi", _, _)).WillOnce(Invoke(Distance)); ``` In `InvokeArgument<N>(...)`, if an argument needs to be passed by reference, wrap it inside `ByRef()`. For example, -``` +```cpp InvokeArgument<2>(5, string("Hi"), ByRef(foo)) ``` calls the mock function's #2 argument, passing to it `5` and `string("Hi")` by value, and `foo` by reference. ## Default Action ## +| Matcher | Description | +|:--------|:------------| |`DoDefault()`|Do the default action (specified by `ON_CALL()` or the built-in one).| -|:------------|:--------------------------------------------------------------------| **Note:** due to technical reasons, `DoDefault()` cannot be used inside a composite action - trying to do so will result in a run-time error. ## Composite Actions ## -|`DoAll(a1, a2, ..., an)`|Do all actions `a1` to `an` and return the result of `an` in each invocation. The first `n - 1` sub-actions must return void. | -|:-----------------------|:-----------------------------------------------------------------------------------------------------------------------------| -|`IgnoreResult(a)` |Perform action `a` and ignore its result. `a` must not return void. | -|`WithArg<N>(a)` |Pass the `N`-th (0-based) argument of the mock function to action `a` and perform it. | +| Matcher | Description | +|:-----------------------------|:-----------------------------------------------------------------------------------------------------------------------------| +|`DoAll(a1, a2, ..., an)` |Do all actions `a1` to `an` and return the result of `an` in each invocation. The first `n - 1` sub-actions must return void. | +|`IgnoreResult(a)` |Perform action `a` and ignore its result. `a` must not return void. | +|`WithArg<N>(a)` |Pass the `N`-th (0-based) argument of the mock function to action `a` and perform it. | |`WithArgs<N1, N2, ..., Nk>(a)`|Pass the selected (0-based) arguments of the mock function to action `a` and perform it. | -|`WithoutArgs(a)` |Perform action `a` without any arguments. | +|`WithoutArgs(a)` |Perform action `a` without any arguments. | ## Defining Actions ## -| `ACTION(Sum) { return arg0 + arg1; }` | Defines an action `Sum()` to return the sum of the mock function's argument #0 and #1. | -|:--------------------------------------|:---------------------------------------------------------------------------------------| -| `ACTION_P(Plus, n) { return arg0 + n; }` | Defines an action `Plus(n)` to return the sum of the mock function's argument #0 and `n`. | -| `ACTION_Pk(Foo, p1, ..., pk) { statements; }` | Defines a parameterized action `Foo(p1, ..., pk)` to execute the given `statements`. | +| Matcher | Description | +|:----------------------------------------------|:------------------------------------------------------------------------------------------| +| `ACTION(Sum) { return arg0 + arg1; }` | Defines an action `Sum()` to return the sum of the mock function's argument #0 and #1. | +| `ACTION_P(Plus, n) { return arg0 + n; }` | Defines an action `Plus(n)` to return the sum of the mock function's argument #0 and `n`. | +| `ACTION_Pk(Foo, p1, ..., pk) { statements; }` | Defines a parameterized action `Foo(p1, ..., pk)` to execute the given `statements`. | The `ACTION*` macros cannot be used inside a function or class. @@ -435,10 +459,11 @@ The `ACTION*` macros cannot be used inside a function or class. These are used in `Times()` to specify how many times a mock function will be called: +| Matcher | Description | +|:--------|:------------| |`AnyNumber()`|The function can be called any number of times.| -|:------------|:----------------------------------------------| -|`AtLeast(n)` |The call is expected at least `n` times. | -|`AtMost(n)` |The call is expected at most `n` times. | +|`AtLeast(n)`|The call is expected at least `n` times.| +|`AtMost(n)`|The call is expected at most `n` times.| |`Between(m, n)`|The call is expected between `m` and `n` (inclusive) times.| |`Exactly(n) or n`|The call is expected exactly `n` times. In particular, the call should never happen when `n` is 0.| @@ -451,7 +476,7 @@ together. ## The After Clause ## -``` +```cpp using ::testing::Expectation; ... Expectation init_x = EXPECT_CALL(foo, InitX()); @@ -465,7 +490,7 @@ says that `Bar()` can be called only after both `InitX()` and If you don't know how many pre-requisites an expectation has when you write it, you can use an `ExpectationSet` to collect them: -``` +```cpp using ::testing::ExpectationSet; ... ExpectationSet all_inits; @@ -490,7 +515,7 @@ each expectation in the chain a different name. <i>All expected<br> calls</i> in the same sequence must occur in the order they are specified. -``` +```cpp using ::testing::Sequence; Sequence s1, s2; ... @@ -508,7 +533,7 @@ says that `Reset()` must be called before _both_ `GetSize()` _and_ `Describe()`, and the latter two can occur in any order. To put many expectations in a sequence conveniently: -``` +```cpp using ::testing::InSequence; { InSequence dummy; @@ -525,7 +550,7 @@ strict order. The name `dummy` is irrelevant.) # Verifying and Resetting a Mock # Google Mock will verify the expectations on a mock object when it is destructed, or you can do it earlier: -``` +```cpp using ::testing::Mock; ... // Verifies and removes the expectations on mock_obj; @@ -540,14 +565,14 @@ Mock::VerifyAndClear(&mock_obj); You can also tell Google Mock that a mock object can be leaked and doesn't need to be verified: -``` +```cpp Mock::AllowLeak(&mock_obj); ``` # Mock Classes # Google Mock defines a convenient mock class template -``` +```cpp class MockFunction<R(A1, ..., An)> { public: MOCK_METHODn(Call, R(A1, ..., An)); @@ -557,6 +582,7 @@ See this [recipe](CookBook.md#using-check-points) for one application of it. # Flags # +| Flag | Description | +|:--------|:------------| | `--gmock_catch_leaked_mocks=0` | Don't report leaked mock objects as failures. | -|:-------------------------------|:----------------------------------------------| -| `--gmock_verbose=LEVEL` | Sets the default verbosity level (`info`, `warning`, or `error`) of Google Mock messages. | +| `--gmock_verbose=LEVEL` | Sets the default verbosity level (`info`, `warning`, or `error`) of Google Mock messages. | diff --git a/googlemock/docs/CookBook.md b/googlemock/docs/CookBook.md index 0460d35..5209110 100644 --- a/googlemock/docs/CookBook.md +++ b/googlemock/docs/CookBook.md @@ -18,10 +18,11 @@ You must always put a mock method definition (`MOCK_METHOD*`) in a `public:` section of the mock class, regardless of the method being mocked being `public`, `protected`, or `private` in the base class. This allows `ON_CALL` and `EXPECT_CALL` to reference the mock function -from outside of the mock class. (Yes, C++ allows a subclass to change -the access level of a virtual function in the base class.) Example: +from outside of the mock class. (Yes, C++ allows a subclass to specify +a different access level than the base class on a virtual function.) +Example: -``` +```cpp class Foo { public: ... @@ -50,7 +51,7 @@ class MockFoo : public Foo { You can mock overloaded functions as usual. No special attention is required: -``` +```cpp class Foo { ... @@ -80,7 +81,7 @@ class MockFoo : public Foo { compiler will give you a warning about some methods in the base class being hidden. To fix that, use `using` to bring them in scope: -``` +```cpp class MockFoo : public Foo { ... using Foo::Add; @@ -94,7 +95,7 @@ class MockFoo : public Foo { To mock a class template, append `_T` to the `MOCK_*` macros: -``` +```cpp template <typename Elem> class StackInterface { ... @@ -123,7 +124,7 @@ class, your mock class will be _unrelated_ to the real class, but contain methods with the same signatures. The syntax for mocking non-virtual methods is the _same_ as mocking virtual methods: -``` +```cpp // A simple packet stream class. None of its members is virtual. class ConcretePacketStream { public: @@ -147,7 +148,7 @@ Note that the mock class doesn't define `AppendPacket()`, unlike the real class. That's fine as long as the test doesn't need to call it. Next, you need a way to say that you want to use -`ConcretePacketStream` in production code, and use `MockPacketStream` +`ConcretePacketStream` in production code and to use `MockPacketStream` in tests. Since the functions are not virtual and the two classes are unrelated, you must specify your choice at _compile time_ (as opposed to run time). @@ -159,7 +160,7 @@ instantiate your template with `ConcretePacketStream` as the type argument. In tests, you will instantiate the same template with `MockPacketStream`. For example, you may write: -``` +```cpp template <class PacketStream> void CreateConnection(PacketStream* stream) { ... } @@ -175,7 +176,7 @@ Then you can use `CreateConnection<ConcretePacketStream>()` and `CreateConnection<MockPacketStream>()` and `PacketReader<MockPacketStream>` in tests. -``` +```cpp MockPacketStream mock_stream; EXPECT_CALL(mock_stream, ...)...; .. set more expectations on mock_stream ... @@ -193,7 +194,7 @@ Instead of calling a free function (say, `OpenFile`) directly, introduce an interface for it and have a concrete subclass that calls the free function: -``` +```cpp class FileInterface { public: ... @@ -226,7 +227,7 @@ If a mock method has no `EXPECT_CALL` spec but is called, Google Mock will print a warning about the "uninteresting call". The rationale is: * New methods may be added to an interface after a test is written. We shouldn't fail a test just because a method it doesn't know about is called. - * However, this may also mean there's a bug in the test, so Google Mock shouldn't be silent either. If the user believes these calls are harmless, he can add an `EXPECT_CALL()` to suppress the warning. + * However, this may also mean there's a bug in the test, so Google Mock shouldn't be silent either. If the user believes these calls are harmless, they can add an `EXPECT_CALL()` to suppress the warning. However, sometimes you may want to suppress all "uninteresting call" warnings, while sometimes you may want the opposite, i.e. to treat all @@ -235,7 +236,7 @@ per-mock-object basis. Suppose your test uses a mock class `MockFoo`: -``` +```cpp TEST(...) { MockFoo mock_foo; EXPECT_CALL(mock_foo, DoThis()); @@ -248,7 +249,7 @@ reported by Google Mock as a warning. However, if you rewrite your test to use `NiceMock<MockFoo>` instead, the warning will be gone, resulting in a cleaner test output: -``` +```cpp using ::testing::NiceMock; TEST(...) { @@ -264,7 +265,7 @@ wherever `MockFoo` is accepted. It also works if `MockFoo`'s constructor takes some arguments, as `NiceMock<MockFoo>` "inherits" `MockFoo`'s constructors: -``` +```cpp using ::testing::NiceMock; TEST(...) { @@ -277,7 +278,7 @@ TEST(...) { The usage of `StrictMock` is similar, except that it makes all uninteresting calls failures: -``` +```cpp using ::testing::StrictMock; TEST(...) { @@ -294,7 +295,7 @@ There are some caveats though (I don't like them just as much as the next guy, but sadly they are side effects of C++'s limitations): 1. `NiceMock<MockFoo>` and `StrictMock<MockFoo>` only work for mock methods defined using the `MOCK_METHOD*` family of macros **directly** in the `MockFoo` class. If a mock method is defined in a **base class** of `MockFoo`, the "nice" or "strict" modifier may not affect it, depending on the compiler. In particular, nesting `NiceMock` and `StrictMock` (e.g. `NiceMock<StrictMock<MockFoo> >`) is **not** supported. - 1. The constructors of the base mock (`MockFoo`) cannot have arguments passed by non-const reference, which happens to be banned by the [Google C++ style guide](http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml). + 1. The constructors of the base mock (`MockFoo`) cannot have arguments passed by non-const reference, which happens to be banned by the [Google C++ style guide](https://google.github.io/styleguide/cppguide.html). 1. During the constructor or destructor of `MockFoo`, the mock object is _not_ nice or strict. This may cause surprises if the constructor or destructor calls a mock method on `this` object. (This behavior, however, is consistent with C++'s general rule: if a constructor or destructor calls a virtual method of `this` object, that method is treated as non-virtual. In other words, to the base class's constructor or destructor, `this` object behaves like an instance of the base class, not the derived class. This rule is required for safety. Otherwise a base constructor may use members of a derived class before they are initialized, or a base destructor may use members of a derived class after they have been destroyed.) Finally, you should be **very cautious** about when to use naggy or strict mocks, as they tend to make tests more brittle and harder to maintain. When you refactor your code without changing its externally visible behavior, ideally you should't need to update any tests. If your code interacts with a naggy mock, however, you may start to get spammed with warnings as the result of your change. Worse, if your code interacts with a strict mock, your tests may start to fail and you'll be forced to fix them. Our general recommendation is to use nice mocks (not yet the default) most of the time, use naggy mocks (the current default) when developing or debugging tests, and use strict mocks only as the last resort. @@ -304,7 +305,7 @@ Finally, you should be **very cautious** about when to use naggy or strict mocks Sometimes a method has a long list of arguments that is mostly uninteresting. For example, -``` +```cpp class LogSink { public: ... @@ -323,7 +324,7 @@ it, which is often infeasible. The trick is to re-dispatch the method in the mock class: -``` +```cpp class ScopedMockLog : public LogSink { public: ... @@ -402,7 +403,7 @@ applicable in a wide variety of situations. :-) Some times you have a non-trivial fake implementation of an interface. For example: -``` +```cpp class Foo { public: virtual ~Foo() {} @@ -432,7 +433,7 @@ When you define the mock class using Google Mock, you can have it delegate its default action to a fake class you already have, using this pattern: -``` +```cpp using ::testing::_; using ::testing::Invoke; @@ -459,7 +460,7 @@ With that, you can use `MockFoo` in your tests as usual. Just remember that if you don't explicitly set an action in an `ON_CALL()` or `EXPECT_CALL()`, the fake will be called upon to do it: -``` +```cpp using ::testing::_; TEST(AbcTest, Xyz) { @@ -514,7 +515,7 @@ ability to validate calls. This technique is very similar to the delegating-to-fake technique, the difference being that we use a real object instead of a fake. Here's an example: -``` +```cpp using ::testing::_; using ::testing::AtLeast; using ::testing::Invoke; @@ -558,7 +559,7 @@ Ideally, you should code to interfaces, whose methods are all pure virtual. In reality, sometimes you do need to mock a virtual method that is not pure (i.e, it already has an implementation). For example: -``` +```cpp class Foo { public: virtual ~Foo(); @@ -585,7 +586,7 @@ whenever you don't need to mock one of its methods). The trick is to leave a back door in your mock class for accessing the real methods in the base class: -``` +```cpp class MockFoo : public Foo { public: // Mocking a pure method. @@ -600,7 +601,7 @@ class MockFoo : public Foo { Now, you can call `Foo::Concrete()` inside an action by: -``` +```cpp using ::testing::_; using ::testing::Invoke; ... @@ -610,7 +611,7 @@ using ::testing::Invoke; or tell the mock object that you don't want to mock `Concrete()`: -``` +```cpp using ::testing::Invoke; ... ON_CALL(foo, Concrete(_)) @@ -628,7 +629,7 @@ works.) You can specify exactly which arguments a mock method is expecting: -``` +```cpp using ::testing::Return; ... EXPECT_CALL(foo, DoThis(5)) @@ -640,7 +641,7 @@ using ::testing::Return; You can use matchers to match arguments that have a certain property: -``` +```cpp using ::testing::Ge; using ::testing::NotNull; using ::testing::Return; @@ -653,7 +654,7 @@ using ::testing::Return; A frequently used matcher is `_`, which matches anything: -``` +```cpp using ::testing::_; using ::testing::NotNull; ... @@ -665,7 +666,7 @@ using ::testing::NotNull; You can build complex matchers from existing ones using `AllOf()`, `AnyOf()`, and `Not()`: -``` +```cpp using ::testing::AllOf; using ::testing::Gt; using ::testing::HasSubstr; @@ -705,11 +706,11 @@ type `m` accepts): 1. When both `T` and `U` are built-in arithmetic types (`bool`, integers, and floating-point numbers), the conversion from `T` to `U` is not lossy (in other words, any value representable by `T` can also be represented by `U`); and 1. When `U` is a reference, `T` must also be a reference (as the underlying matcher may be interested in the address of the `U` value). -The code won't compile if any of these conditions isn't met. +The code won't compile if any of these conditions aren't met. Here's one example: -``` +```cpp using ::testing::SafeMatcherCast; // A base class and a child class. @@ -743,7 +744,7 @@ need some help on which overloaded version it is. To disambiguate functions overloaded on the const-ness of this object, use the `Const()` argument wrapper. -``` +```cpp using ::testing::ReturnRef; class MockFoo : public Foo { @@ -770,7 +771,7 @@ of a matcher, either by wrapping your matcher in `Matcher<type>()`, or using a matcher whose type is fixed (`TypedEq<type>`, `An<type>()`, etc): -``` +```cpp using ::testing::An; using ::testing::Lt; using ::testing::Matcher; @@ -802,7 +803,7 @@ still active will be selected (think "newer overrides older"). So, you can make a method do different things depending on its argument values like this: -``` +```cpp using ::testing::_; using ::testing::Lt; using ::testing::Return; @@ -826,7 +827,7 @@ example, we may want to say that the first argument must be less than the second argument. The `With()` clause allows us to match all arguments of a mock function as a whole. For example, -``` +```cpp using ::testing::_; using ::testing::Lt; using ::testing::Ne; @@ -849,7 +850,7 @@ than `.With(Lt())`. You can use `Args<k1, ..., kn>(m)` to match the `n` selected arguments (as a tuple) against `m`. For example, -``` +```cpp using ::testing::_; using ::testing::AllOf; using ::testing::Args; @@ -881,7 +882,7 @@ participate. Luckily, you can use a matcher where a unary predicate functor is expected by wrapping it inside the `Matches()` function. For example, -``` +```cpp #include <algorithm> #include <vector> @@ -897,7 +898,7 @@ predicates (doing the same using STL's `<functional>` header is just painful). For example, here's a predicate that's satisfied by any number that is >= 0, <= 100, and != 50: -``` +```cpp Matches(AllOf(Ge(0), Le(100), Ne(50))) ``` @@ -908,14 +909,14 @@ themselves, there is a way to take advantage of them in [Google Test](../../googletest/) assertions. It's called `ASSERT_THAT` and `EXPECT_THAT`: -``` +```cpp ASSERT_THAT(value, matcher); // Asserts that value matches matcher. EXPECT_THAT(value, matcher); // The non-fatal version. ``` For example, in a Google Test test you can write: -``` +```cpp #include "gmock/gmock.h" using ::testing::AllOf; @@ -959,7 +960,7 @@ as a matcher - as long as the predicate accepts a value of the type you want. You do this by wrapping the predicate inside the `Truly()` function, for example: -``` +```cpp using ::testing::Truly; int IsEven(int n) { return (n % 2) == 0 ? 1 : 0; } @@ -989,7 +990,7 @@ away from it if you can guarantee that `bar` won't be changed after the `EXPECT_CALL()` is executed. Just tell Google Mock that it should save a reference to `bar`, instead of a copy of it. Here's how: -``` +```cpp using ::testing::Eq; using ::testing::ByRef; using ::testing::Lt; @@ -1013,14 +1014,14 @@ you may need to validate a certain member variable or the result of a certain getter method of the object. You can do this with `Field()` and `Property()`. More specifically, -``` +```cpp Field(&Foo::bar, m) ``` is a matcher that matches a `Foo` object whose `bar` member variable satisfies matcher `m`. -``` +```cpp Property(&Foo::baz, m) ``` @@ -1029,9 +1030,10 @@ a value that satisfies matcher `m`. For example: -> | `Field(&Foo::number, Ge(3))` | Matches `x` where `x.number >= 3`. | +| Expression | Description | |:-----------------------------|:-----------------------------------| -> | `Property(&Foo::name, StartsWith("John "))` | Matches `x` where `x.name()` starts with `"John "`. | +| `Field(&Foo::number, Ge(3))` | Matches `x` where `x.number >= 3`. | +| `Property(&Foo::name, StartsWith("John "))` | Matches `x` where `x.name()` starts with `"John "`. | Note that in `Property(&Foo::baz, ...)`, method `baz()` must take no argument and be declared as `const`. @@ -1039,7 +1041,7 @@ argument and be declared as `const`. BTW, `Field()` and `Property()` can also match plain pointers to objects. For instance, -``` +```cpp Field(&Foo::number, Ge(3)) ``` @@ -1060,7 +1062,7 @@ Well, you can use the `Pointee(m)` matcher. `Pointee(m)` matches a pointer iff `m` matches the value the pointer points to. For example: -``` +```cpp using ::testing::Ge; using ::testing::Pointee; ... @@ -1073,7 +1075,7 @@ greater than or equal to 3. One nice thing about `Pointee()` is that it treats a `NULL` pointer as a match failure, so you can write `Pointee(m)` instead of -``` +```cpp AllOf(NotNull(), Pointee(m)) ``` @@ -1100,7 +1102,7 @@ which has an `int bar()` method and an `int baz()` method, and you want to constrain that the argument's `bar()` value plus its `baz()` value is a given number. Here's how you can define a matcher to do it: -``` +```cpp using ::testing::MatcherInterface; using ::testing::MatchResultListener; @@ -1151,7 +1153,7 @@ container out-of-line is a bit of a hassle. You can use the `ElementsAre()` or `UnorderedElementsAre()` matcher in such cases: -``` +```cpp using ::testing::_; using ::testing::ElementsAre; using ::testing::Gt; @@ -1168,7 +1170,7 @@ must be 1, greater than 0, anything, and 5 respectively. If you instead write: -``` +```cpp using ::testing::_; using ::testing::Gt; using ::testing::UnorderedElementsAre; @@ -1188,7 +1190,7 @@ to 10 arguments. If more are needed, you can place them in a C-style array and use `ElementsAreArray()` or `UnorderedElementsAreArray()` instead: -``` +```cpp using ::testing::ElementsAreArray; ... @@ -1205,7 +1207,7 @@ In case the array needs to be dynamically created (and therefore the array size cannot be inferred by the compiler), you can give `ElementsAreArray()` an additional argument to specify the array size: -``` +```cpp using ::testing::ElementsAreArray; ... int* const expected_vector3 = new int[count]; @@ -1229,10 +1231,10 @@ that references the implementation object dies, the implementation object will be deleted. Therefore, if you have some complex matcher that you want to use again -and again, there is no need to build it everytime. Just assign it to a +and again, there is no need to build it every time. Just assign it to a matcher variable and use that variable repeatedly! For example, -``` +```cpp Matcher<int> in_range = AllOf(Gt(5), Le(10)); ... use in_range as a matcher in multiple EXPECT_CALLs ... ``` @@ -1275,7 +1277,7 @@ any `EXPECT_CALL()` statement, it will be an error. If a mock method shouldn't be called at all, explicitly say so: -``` +```cpp using ::testing::_; ... EXPECT_CALL(foo, Bar(_)) @@ -1285,7 +1287,7 @@ using ::testing::_; If some calls to the method are allowed, but the rest are not, just list all the expected calls: -``` +```cpp using ::testing::AnyNumber; using ::testing::Gt; ... @@ -1317,7 +1319,7 @@ A **strict mock** turns uninteresting call warnings into errors. So making a moc Let's look at an example: -``` +```cpp TEST(...) { NiceMock<MockDomainRegistry> mock_registry; EXPECT_CALL(mock_registry, GetDomainOwner("google.com")) @@ -1332,7 +1334,7 @@ The sole `EXPECT_CALL` here says that all calls to `GetDomainOwner()` must have So how do we tell Google Mock that `GetDomainOwner()` can be called with some other arguments as well? The standard technique is to add a "catch all" `EXPECT_CALL`: -``` +```cpp EXPECT_CALL(mock_registry, GetDomainOwner(_)) .Times(AnyNumber()); // catches all other calls to this method. EXPECT_CALL(mock_registry, GetDomainOwner("google.com")) @@ -1358,7 +1360,7 @@ If you would rather have all calls occur in the order of the expectations, put the `EXPECT_CALL()` statements in a block where you define a variable of type `InSequence`: -``` +```cpp using ::testing::_; using ::testing::InSequence; @@ -1401,7 +1403,7 @@ edge from node A to node B wherever A must occur before B, we can get a DAG. We use the term "sequence" to mean a directed path in this DAG. Now, if we decompose the DAG into sequences, we just need to know which sequences each `EXPECT_CALL()` belongs to in order to be able to -reconstruct the orginal DAG. +reconstruct the original DAG. So, to specify the partial order on the expectations we need to do two things: first to define some `Sequence` objects, and then for each @@ -1409,7 +1411,7 @@ things: first to define some `Sequence` objects, and then for each of. Expectations in the same sequence must occur in the order they are written. For example, -``` +```cpp using ::testing::Sequence; Sequence s1, s2; @@ -1445,7 +1447,7 @@ that are still active. An expectation is active when created, and becomes inactive (aka _retires_) when a call that has to occur later has occurred. For example, in -``` +```cpp using ::testing::_; using ::testing::Sequence; @@ -1466,7 +1468,7 @@ as soon as either #2 or #3 is matched, #1 will retire. If a warning Note that an expectation doesn't retire automatically when it's saturated. For example, -``` +```cpp using ::testing::_; ... EXPECT_CALL(log, Log(WARNING, _, _)); // #1 @@ -1480,7 +1482,7 @@ match again and result in an upper-bound-violated error. If this is not what you want, you can ask an expectation to retire as soon as it becomes saturated: -``` +```cpp using ::testing::_; ... EXPECT_CALL(log, Log(WARNING, _, _)); // #1 @@ -1499,7 +1501,7 @@ will match #1 - there will be no error. If a mock function's return type is a reference, you need to use `ReturnRef()` instead of `Return()` to return a result: -``` +```cpp using ::testing::ReturnRef; class MockFoo : public Foo { @@ -1529,7 +1531,7 @@ as doing that usually indicates a user error. So, what shall you do? You may be tempted to try `ByRef()`: -``` +```cpp using testing::ByRef; using testing::Return; @@ -1566,7 +1568,7 @@ and `Return(ByRef(x))` will always return 0. specifically. It returns the value pointed to by `pointer` at the time the action is _executed_: -``` +```cpp using testing::ReturnPointee; ... int x = 0; @@ -1583,7 +1585,7 @@ Want to do more than one thing when a function is called? That's fine. `DoAll()` allow you to do sequence of actions every time. Only the return value of the last action in the sequence will be used. -``` +```cpp using ::testing::DoAll; class MockFoo : public Foo { @@ -1609,7 +1611,7 @@ define your own action by implementing `::testing::ActionInterface`. If all you need to do is to change an output argument, the built-in `SetArgPointee()` action is convenient: -``` +```cpp using ::testing::SetArgPointee; class MockMutator : public Mutator { @@ -1636,7 +1638,7 @@ constructor and assignment operator. If the mock method also needs to return a value as well, you can chain `SetArgPointee()` with `Return()` using `DoAll()`: -``` +```cpp using ::testing::_; using ::testing::Return; using ::testing::SetArgPointee; @@ -1659,7 +1661,7 @@ If the output argument is an array, use the elements in source range `[first, last)` to the array pointed to by the `N`-th (0-based) argument: -``` +```cpp using ::testing::NotNull; using ::testing::SetArrayArgument; @@ -1678,9 +1680,9 @@ class MockArrayMutator : public ArrayMutator { This also works when the argument is an output iterator: -``` +```cpp using ::testing::_; -using ::testing::SeArrayArgument; +using ::testing::SetArrayArgument; class MockRolodex : public Rolodex { public: @@ -1702,7 +1704,7 @@ class MockRolodex : public Rolodex { If you expect a call to change the behavior of a mock object, you can use `::testing::InSequence` to specify different behaviors before and after the call: -``` +```cpp using ::testing::InSequence; using ::testing::Return; @@ -1722,7 +1724,7 @@ This makes `my_mock.IsDirty()` return `true` before `my_mock.Flush()` is called If the behavior change is more complex, you can store the effects in a variable and make a mock method get its return value from that variable: -``` +```cpp using ::testing::_; using ::testing::SaveArg; using ::testing::Return; @@ -1752,7 +1754,7 @@ to specify a default value for types Google Mock doesn't know about. You can do this using the `::testing::DefaultValue` class template: -``` +```cpp class MockFoo : public Foo { public: MOCK_METHOD0(CalculateBar, Bar()); @@ -1788,7 +1790,7 @@ have two mock methods with the same return type and you want them to have different behaviors. The `ON_CALL()` macro allows you to customize your mock's behavior at the method level: -``` +```cpp using ::testing::_; using ::testing::AnyNumber; using ::testing::Gt; @@ -1821,7 +1823,7 @@ specialize the mock's behavior later. If the built-in actions don't suit you, you can easily use an existing function, method, or functor as an action: -``` +```cpp using ::testing::_; using ::testing::Invoke; @@ -1876,7 +1878,7 @@ tedious and obscures the intent of the test. that it doesn't pass the mock function's arguments to the callee. Here's an example: -``` +```cpp using ::testing::_; using ::testing::InvokeWithoutArgs; @@ -1900,7 +1902,7 @@ bool Job1() { ... } Sometimes a mock function will receive a function pointer or a functor (in other words, a "callable") as an argument, e.g. -``` +```cpp class MockFoo : public Foo { public: MOCK_METHOD2(DoThis, bool(int n, bool (*fp)(int))); @@ -1909,7 +1911,7 @@ class MockFoo : public Foo { and you may want to invoke this callable argument: -``` +```cpp using ::testing::_; ... MockFoo foo; @@ -1919,13 +1921,13 @@ using ::testing::_; // second argument DoThis() receives. ``` -Arghh, you need to refer to a mock function argument but C++ has no -lambda (yet), so you have to define your own action. :-( Or do you -really? +Arghh, you need to refer to a mock function argument but your version +of C++ has no lambdas, so you have to define your own action. :-( +Or do you really? Well, Google Mock has an action to solve _exactly_ this problem: -``` +```cpp InvokeArgument<N>(arg_1, arg_2, ..., arg_m) ``` @@ -1935,7 +1937,7 @@ a function pointer or a functor, Google Mock handles them both. With that, you could write: -``` +```cpp using ::testing::_; using ::testing::InvokeArgument; ... @@ -1948,7 +1950,7 @@ using ::testing::InvokeArgument; What if the callable takes an argument by reference? No problem - just wrap it inside `ByRef()`: -``` +```cpp ... MOCK_METHOD1(Bar, bool(bool (*fp)(int, const Helper&))); ... @@ -1972,7 +1974,7 @@ copy_ of the argument, and pass a _reference to the copy_, instead of a reference to the original value, to the callable. This is especially handy when the argument is a temporary value: -``` +```cpp ... MOCK_METHOD1(DoThat, bool(bool (*f)(const double& x, const string& s))); ... @@ -1999,7 +2001,7 @@ function that returns `void`, or perhaps it needs to be used in `DoAll()` and it's not the last in the list). `IgnoreResult()` lets you do that. For example: -``` +```cpp using ::testing::_; using ::testing::Invoke; using ::testing::Return; @@ -2036,7 +2038,7 @@ Say you have a mock function `Foo()` that takes seven arguments, and you have a custom action that you want to invoke when `Foo()` is called. Trouble is, the custom action only wants three arguments: -``` +```cpp using ::testing::_; using ::testing::Invoke; ... @@ -2058,7 +2060,7 @@ To please the compiler God, you can to define an "adaptor" that has the same signature as `Foo()` and calls the custom action with the right arguments: -``` +```cpp using ::testing::_; using ::testing::Invoke; @@ -2079,7 +2081,7 @@ Google Mock provides a generic _action adaptor_, so you can spend your time minding more important business than writing your own adaptors. Here's the syntax: -``` +```cpp WithArgs<N1, N2, ..., Nk>(action) ``` @@ -2087,7 +2089,7 @@ creates an action that passes the arguments of the mock function at the given indices (0-based) to the inner `action` and performs it. Using `WithArgs`, our original example can be written as: -``` +```cpp using ::testing::_; using ::testing::Invoke; using ::testing::WithArgs; @@ -2127,14 +2129,14 @@ case the types of the uninteresting arguments change. It could also increase the chance the action function can be reused. For example, given -``` +```cpp MOCK_METHOD3(Foo, double(const string& label, double x, double y)); MOCK_METHOD3(Bar, double(int index, double x, double y)); ``` instead of -``` +```cpp using ::testing::_; using ::testing::Invoke; @@ -2155,7 +2157,7 @@ double DistanceToOriginWithIndex(int index, double x, double y) { you could write -``` +```cpp using ::testing::_; using ::testing::Invoke; using ::testing::Unused; @@ -2180,12 +2182,12 @@ the implementation object dies, the implementation object will be deleted. If you have some complex action that you want to use again and again, -you may not have to build it from scratch everytime. If the action +you may not have to build it from scratch every time. If the action doesn't have an internal state (i.e. if it always does the same thing no matter how many times it has been called), you can assign it to an action variable and use that variable repeatedly. For example: -``` +```cpp Action<bool(int*)> set_flag = DoAll(SetArgPointee<0>(5), Return(true)); ... use set_flag in .WillOnce() and .WillRepeatedly() ... @@ -2198,7 +2200,7 @@ returns a counter whose initial value is `init`, using two actions created from the same expression and using a shared action will exihibit different behaviors. Example: -``` +```cpp EXPECT_CALL(foo, DoThis()) .WillRepeatedly(IncrementCounter(0)); EXPECT_CALL(foo, DoThat()) @@ -2211,7 +2213,7 @@ exihibit different behaviors. Example: versus -``` +```cpp Action<int()> increment = IncrementCounter(0); EXPECT_CALL(foo, DoThis()) @@ -2227,77 +2229,71 @@ versus ## Mocking Methods That Use Move-Only Types ## -C++11 introduced <em>move-only types</em>. A move-only-typed value can be moved from one object to another, but cannot be copied. `std::unique_ptr<T>` is probably the most commonly used move-only type. +C++11 introduced *move-only types*. A move-only-typed value can be moved from +one object to another, but cannot be copied. `std::unique_ptr<T>` is +probably the most commonly used move-only type. -Mocking a method that takes and/or returns move-only types presents some challenges, but nothing insurmountable. This recipe shows you how you can do it. +Mocking a method that takes and/or returns move-only types presents some +challenges, but nothing insurmountable. This recipe shows you how you can do it. +Note that the support for move-only method arguments was only introduced to +gMock in April 2017; in older code, you may find more complex +[workarounds](#legacy-workarounds-for-move-only-types) for lack of this feature. -Let’s say we are working on a fictional project that lets one post and share snippets called “buzzes”. Your code uses these types: +Let’s say we are working on a fictional project that lets one post and share +snippets called “buzzes”. Your code uses these types: -``` +```cpp enum class AccessLevel { kInternal, kPublic }; class Buzz { public: - explicit Buzz(AccessLevel access) { … } + explicit Buzz(AccessLevel access) { ... } ... }; class Buzzer { public: virtual ~Buzzer() {} - virtual std::unique_ptr<Buzz> MakeBuzz(const std::string& text) = 0; - virtual bool ShareBuzz(std::unique_ptr<Buzz> buzz, Time timestamp) = 0; + virtual std::unique_ptr<Buzz> MakeBuzz(StringPiece text) = 0; + virtual bool ShareBuzz(std::unique_ptr<Buzz> buzz, int64_t timestamp) = 0; ... }; ``` -A `Buzz` object represents a snippet being posted. A class that implements the `Buzzer` interface is capable of creating and sharing `Buzz`. Methods in `Buzzer` may return a `unique_ptr<Buzz>` or take a `unique_ptr<Buzz>`. Now we need to mock `Buzzer` in our tests. - -To mock a method that returns a move-only type, you just use the familiar `MOCK_METHOD` syntax as usual: - -``` -class MockBuzzer : public Buzzer { - public: - MOCK_METHOD1(MakeBuzz, std::unique_ptr<Buzz>(const std::string& text)); - … -}; -``` - -However, if you attempt to use the same `MOCK_METHOD` pattern to mock a method that takes a move-only parameter, you’ll get a compiler error currently: +A `Buzz` object represents a snippet being posted. A class that implements the +`Buzzer` interface is capable of creating and sharing `Buzz`es. Methods in +`Buzzer` may return a `unique_ptr<Buzz>` or take a +`unique_ptr<Buzz>`. Now we need to mock `Buzzer` in our tests. -``` - // Does NOT compile! - MOCK_METHOD2(ShareBuzz, bool(std::unique_ptr<Buzz> buzz, Time timestamp)); -``` +To mock a method that accepts or returns move-only types, you just use the +familiar `MOCK_METHOD` syntax as usual: -While it’s highly desirable to make this syntax just work, it’s not trivial and the work hasn’t been done yet. Fortunately, there is a trick you can apply today to get something that works nearly as well as this. - -The trick, is to delegate the `ShareBuzz()` method to a mock method (let’s call it `DoShareBuzz()`) that does not take move-only parameters: - -``` +```cpp class MockBuzzer : public Buzzer { public: - MOCK_METHOD1(MakeBuzz, std::unique_ptr<Buzz>(const std::string& text)); - MOCK_METHOD2(DoShareBuzz, bool(Buzz* buzz, Time timestamp)); - bool ShareBuzz(std::unique_ptr<Buzz> buzz, Time timestamp) { - return DoShareBuzz(buzz.get(), timestamp); - } + MOCK_METHOD1(MakeBuzz, std::unique_ptr<Buzz>(StringPiece text)); + MOCK_METHOD2(ShareBuzz, bool(std::unique_ptr<Buzz> buzz, int64_t timestamp)); }; ``` -Note that there's no need to define or declare `DoShareBuzz()` in a base class. You only need to define it as a `MOCK_METHOD` in the mock class. +Now that we have the mock class defined, we can use it in tests. In the +following code examples, we assume that we have defined a `MockBuzzer` object +named `mock_buzzer_`: -Now that we have the mock class defined, we can use it in tests. In the following code examples, we assume that we have defined a `MockBuzzer` object named `mock_buzzer_`: - -``` +```cpp MockBuzzer mock_buzzer_; ``` -First let’s see how we can set expectations on the `MakeBuzz()` method, which returns a `unique_ptr<Buzz>`. +First let’s see how we can set expectations on the `MakeBuzz()` method, which +returns a `unique_ptr<Buzz>`. -As usual, if you set an expectation without an action (i.e. the `.WillOnce()` or `.WillRepeated()` clause), when that expectation fires, the default action for that method will be taken. Since `unique_ptr<>` has a default constructor that returns a null `unique_ptr`, that’s what you’ll get if you don’t specify an action: +As usual, if you set an expectation without an action (i.e. the `.WillOnce()` or +`.WillRepeated()` clause), when that expectation fires, the default action for +that method will be taken. Since `unique_ptr<>` has a default constructor +that returns a null `unique_ptr`, that’s what you’ll get if you don’t specify an +action: -``` +```cpp // Use the default action. EXPECT_CALL(mock_buzzer_, MakeBuzz("hello")); @@ -2305,32 +2301,13 @@ As usual, if you set an expectation without an action (i.e. the `.WillOnce()` or EXPECT_EQ(nullptr, mock_buzzer_.MakeBuzz("hello")); ``` -If you are not happy with the default action, you can tweak it. Depending on what you need, you may either tweak the default action for a specific (mock object, mock method) combination using `ON_CALL()`, or you may tweak the default action for all mock methods that return a specific type. The usage of `ON_CALL()` is similar to `EXPECT_CALL()`, so we’ll skip it and just explain how to do the latter (tweaking the default action for a specific return type). You do this via the `DefaultValue<>::SetFactory()` and `DefaultValue<>::Clear()` API: +If you are not happy with the default action, you can tweak it as usual; see +[Setting Default Actions](#setting-the-default-actions-for-a-mock-method). -``` - // Sets the default action for return type std::unique_ptr<Buzz> to - // creating a new Buzz every time. - DefaultValue<std::unique_ptr<Buzz>>::SetFactory( - [] { return MakeUnique<Buzz>(AccessLevel::kInternal); }); - - // When this fires, the default action of MakeBuzz() will run, which - // will return a new Buzz object. - EXPECT_CALL(mock_buzzer_, MakeBuzz("hello")).Times(AnyNumber()); - - auto buzz1 = mock_buzzer_.MakeBuzz("hello"); - auto buzz2 = mock_buzzer_.MakeBuzz("hello"); - EXPECT_NE(nullptr, buzz1); - EXPECT_NE(nullptr, buzz2); - EXPECT_NE(buzz1, buzz2); - - // Resets the default action for return type std::unique_ptr<Buzz>, - // to avoid interfere with other tests. - DefaultValue<std::unique_ptr<Buzz>>::Clear(); -``` - -What if you want the method to do something other than the default action? If you just need to return a pre-defined move-only value, you can use the `Return(ByMove(...))` action: +If you just need to return a pre-defined move-only value, you can use the +`Return(ByMove(...))` action: -``` +```cpp // When this fires, the unique_ptr<> specified by ByMove(...) will // be returned. EXPECT_CALL(mock_buzzer_, MakeBuzz("world")) @@ -2341,81 +2318,87 @@ What if you want the method to do something other than the default action? If y Note that `ByMove()` is essential here - if you drop it, the code won’t compile. -Quiz time! What do you think will happen if a `Return(ByMove(...))` action is performed more than once (e.g. you write `….WillRepeatedly(Return(ByMove(...)));`)? Come think of it, after the first time the action runs, the source value will be consumed (since it’s a move-only value), so the next time around, there’s no value to move from -- you’ll get a run-time error that `Return(ByMove(...))` can only be run once. +Quiz time! What do you think will happen if a `Return(ByMove(...))` action is +performed more than once (e.g. you write +`.WillRepeatedly(Return(ByMove(...)));`)? Come think of it, after the first +time the action runs, the source value will be consumed (since it’s a move-only +value), so the next time around, there’s no value to move from -- you’ll get a +run-time error that `Return(ByMove(...))` can only be run once. -If you need your mock method to do more than just moving a pre-defined value, remember that you can always use `Invoke()` to call a lambda or a callable object, which can do pretty much anything you want: +If you need your mock method to do more than just moving a pre-defined value, +remember that you can always use a lambda or a callable object, which can do +pretty much anything you want: -``` +```cpp EXPECT_CALL(mock_buzzer_, MakeBuzz("x")) - .WillRepeatedly(Invoke([](const std::string& text) { - return std::make_unique<Buzz>(AccessLevel::kInternal); - })); + .WillRepeatedly([](StringPiece text) { + return MakeUnique<Buzz>(AccessLevel::kInternal); + }); EXPECT_NE(nullptr, mock_buzzer_.MakeBuzz("x")); EXPECT_NE(nullptr, mock_buzzer_.MakeBuzz("x")); ``` -Every time this `EXPECT_CALL` fires, a new `unique_ptr<Buzz>` will be created and returned. You cannot do this with `Return(ByMove(...))`. +Every time this `EXPECT_CALL` fires, a new `unique_ptr<Buzz>` will be +created and returned. You cannot do this with `Return(ByMove(...))`. -Now there’s one topic we haven’t covered: how do you set expectations on `ShareBuzz()`, which takes a move-only-typed parameter? The answer is you don’t. Instead, you set expectations on the `DoShareBuzz()` mock method (remember that we defined a `MOCK_METHOD` for `DoShareBuzz()`, not `ShareBuzz()`): +That covers returning move-only values; but how do we work with methods +accepting move-only arguments? The answer is that they work normally, although +some actions will not compile when any of method's arguments are move-only. You +can always use `Return`, or a [lambda or functor](#using-functionsmethodsfunctors-as-actions): -``` - EXPECT_CALL(mock_buzzer_, DoShareBuzz(NotNull(), _)); +```cpp + using ::testing::Unused; - // When one calls ShareBuzz() on the MockBuzzer like this, the call is - // forwarded to DoShareBuzz(), which is mocked. Therefore this statement - // will trigger the above EXPECT_CALL. - mock_buzzer_.ShareBuzz(MakeUnique<Buzz>(AccessLevel::kInternal), - ::base::Now()); + EXPECT_CALL(mock_buzzer_, ShareBuzz(NotNull(), _)) .WillOnce(Return(true)); + EXPECT_TRUE(mock_buzzer_.ShareBuzz(MakeUnique<Buzz>(AccessLevel::kInternal)), + 0); + + EXPECT_CALL(mock_buzzer_, ShareBuzz(_, _)) .WillOnce( + [](std::unique_ptr<Buzz> buzz, Unused) { return buzz != nullptr; }); + EXPECT_FALSE(mock_buzzer_.ShareBuzz(nullptr, 0)); ``` -Some of you may have spotted one problem with this approach: the `DoShareBuzz()` mock method differs from the real `ShareBuzz()` method in that it cannot take ownership of the buzz parameter - `ShareBuzz()` will always delete buzz after `DoShareBuzz()` returns. What if you need to save the buzz object somewhere for later use when `ShareBuzz()` is called? Indeed, you'd be stuck. +Many built-in actions (`WithArgs`, `WithoutArgs`,`DeleteArg`, `SaveArg`, ...) +could in principle support move-only arguments, but the support for this is not +implemented yet. If this is blocking you, please file a bug. -Another problem with the `DoShareBuzz()` we had is that it can surprise people reading or maintaining the test, as one would expect that `DoShareBuzz()` has (logically) the same contract as `ShareBuzz()`. +A few actions (e.g. `DoAll`) copy their arguments internally, so they can never +work with non-copyable objects; you'll have to use functors instead. -Fortunately, these problems can be fixed with a bit more code. Let's try to get it right this time: +##### Legacy workarounds for move-only types -``` +Support for move-only function arguments was only introduced to gMock in April +2017. In older code, you may encounter the following workaround for the lack of +this feature (it is no longer necessary - we're including it just for +reference): + +```cpp class MockBuzzer : public Buzzer { public: - MockBuzzer() { - // Since DoShareBuzz(buzz, time) is supposed to take ownership of - // buzz, define a default behavior for DoShareBuzz(buzz, time) to - // delete buzz. - ON_CALL(*this, DoShareBuzz(_, _)) - .WillByDefault(Invoke([](Buzz* buzz, Time timestamp) { - delete buzz; - return true; - })); - } - - MOCK_METHOD1(MakeBuzz, std::unique_ptr<Buzz>(const std::string& text)); - - // Takes ownership of buzz. MOCK_METHOD2(DoShareBuzz, bool(Buzz* buzz, Time timestamp)); - bool ShareBuzz(std::unique_ptr<Buzz> buzz, Time timestamp) { - return DoShareBuzz(buzz.release(), timestamp); + bool ShareBuzz(std::unique_ptr<Buzz> buzz, Time timestamp) override { + return DoShareBuzz(buzz.get(), timestamp); } }; ``` -Now, the mock `DoShareBuzz()` method is free to save the buzz argument for later use if this is what you want: +The trick is to delegate the `ShareBuzz()` method to a mock method (let’s call +it `DoShareBuzz()`) that does not take move-only parameters. Then, instead of +setting expectations on `ShareBuzz()`, you set them on the `DoShareBuzz()` mock +method: -``` - std::unique_ptr<Buzz> intercepted_buzz; - EXPECT_CALL(mock_buzzer_, DoShareBuzz(NotNull(), _)) - .WillOnce(Invoke([&intercepted_buzz](Buzz* buzz, Time timestamp) { - // Save buzz in intercepted_buzz for analysis later. - intercepted_buzz.reset(buzz); - return false; - })); +```cpp + MockBuzzer mock_buzzer_; + EXPECT_CALL(mock_buzzer_, DoShareBuzz(NotNull(), _)); - mock_buzzer_.ShareBuzz(std::make_unique<Buzz>(AccessLevel::kInternal), - Now()); - EXPECT_NE(nullptr, intercepted_buzz); + // When one calls ShareBuzz() on the MockBuzzer like this, the call is + // forwarded to DoShareBuzz(), which is mocked. Therefore this statement + // will trigger the above EXPECT_CALL. + mock_buzzer_.ShareBuzz(MakeUnique<Buzz>(AccessLevel::kInternal), 0); ``` -Using the tricks covered in this recipe, you are now able to mock methods that take and/or return move-only types. Put your newly-acquired power to good use - when you design a new API, you can now feel comfortable using `unique_ptrs` as appropriate, without fearing that doing so will compromise your tests. + ## Making the Compilation Faster ## @@ -2437,7 +2420,7 @@ and destructor once, resulting in a much faster compilation. Let's illustrate the idea using an example. Here's the definition of a mock class before applying this recipe: -``` +```cpp // File mock_foo.h. ... class MockFoo : public Foo { @@ -2454,7 +2437,7 @@ class MockFoo : public Foo { After the change, it would look like: -``` +```cpp // File mock_foo.h. ... class MockFoo : public Foo { @@ -2469,7 +2452,7 @@ class MockFoo : public Foo { }; ``` and -``` +```cpp // File mock_foo.cpp. #include "path/to/mock_foo.h" @@ -2482,12 +2465,12 @@ MockFoo::~MockFoo() {} ## Forcing a Verification ## -When it's being destoyed, your friendly mock object will automatically +When it's being destroyed, your friendly mock object will automatically verify that all expectations on it have been satisfied, and will generate [Google Test](../../googletest/) failures if not. This is convenient as it leaves you with one less thing to worry about. That is, unless you are not sure if your mock object will -be destoyed. +be destroyed. How could it be that your mock object won't eventually be destroyed? Well, it might be created on the heap and owned by the code you are @@ -2501,7 +2484,7 @@ to _force_ Google Mock to verify a mock object before it is (hopefully) destructed. You can do this with `Mock::VerifyAndClearExpectations(&mock_object)`: -``` +```cpp TEST(MyServerTest, ProcessesRequest) { using ::testing::Mock; @@ -2554,7 +2537,7 @@ function at specific places. Then you can verify that the mock function calls do happen at the right time. For example, if you are exercising code: -``` +```cpp Foo(1); Foo(2); Foo(3); @@ -2563,7 +2546,7 @@ Foo(3); and want to verify that `Foo(1)` and `Foo(3)` both invoke `mock.Bar("a")`, but `Foo(2)` doesn't invoke anything. You can write: -``` +```cpp using ::testing::MockFunction; TEST(FooTest, InvokesBarCorrectly) { @@ -2605,7 +2588,7 @@ This sounds simple, except for one problem: a destructor is a special function with special syntax and special semantics, and the `MOCK_METHOD0` macro doesn't work for it: -``` +```cpp MOCK_METHOD0(~MockFoo, void()); // Won't compile! ``` @@ -2613,7 +2596,7 @@ The good news is that you can use a simple pattern to achieve the same effect. First, add a mock function `Die()` to your mock class and call it in the destructor, like this: -``` +```cpp class MockFoo : public Foo { ... // Add the following two lines to the mock class. @@ -2626,7 +2609,7 @@ class MockFoo : public Foo { name.) Now, we have translated the problem of testing when a `MockFoo` object dies to testing when its `Die()` method is called: -``` +```cpp MockFoo* foo = new MockFoo; MockBar* bar = new MockBar; ... @@ -2681,7 +2664,7 @@ behavior. That's not fun, so don't do it. Google Mock guarantees that the action for a mock function is done in the same thread that called the mock function. For example, in -``` +```cpp EXPECT_CALL(mock, Foo(1)) .WillOnce(action1); EXPECT_CALL(mock, Foo(2)) @@ -2732,7 +2715,7 @@ with three possible values: Alternatively, you can adjust the value of that flag from within your tests like so: -``` +```cpp ::testing::FLAGS_gmock_verbose = "error"; ``` @@ -2754,7 +2737,7 @@ which `EXPECT_CALL` Google Mock thinks it matches? You can unlock this power by running your test with the `--gmock_verbose=info` flag. For example, given the test program: -``` +```cpp using testing::_; using testing::HasSubstr; using testing::Return; @@ -2838,7 +2821,7 @@ and you should see an `OUTPUT_DIR` directory being created with files These three files contain everything you need to use Google Mock (and Google Test). Just copy them to anywhere you want and you are ready to write tests and use mocks. You can use the -[scrpts/test/Makefile](../scripts/test/Makefile) file as an example on how to compile your tests +[make/Makefile](../make/Makefile) file as an example on how to compile your tests against them. # Extending Google Mock # @@ -2848,7 +2831,7 @@ against them. The `MATCHER*` family of macros can be used to define custom matchers easily. The syntax: -``` +```cpp MATCHER(name, description_string_expression) { statements; } ``` @@ -2869,16 +2852,16 @@ in which case Google Mock will use the sequence of words in the matcher name as the description. For example: -``` +```cpp MATCHER(IsDivisibleBy7, "") { return (arg % 7) == 0; } ``` allows you to write -``` +```cpp // Expects mock_foo.Bar(n) to be called where n is divisible by 7. EXPECT_CALL(mock_foo, Bar(IsDivisibleBy7())); ``` or, -``` +```cpp using ::testing::Not; ... EXPECT_THAT(some_expression, IsDivisibleBy7()); @@ -2901,7 +2884,7 @@ by 7)"` are automatically calculated from the matcher name As you may have noticed, the auto-generated descriptions (especially those for the negation) may not be so great. You can always override them with a string expression of your own: -``` +```cpp MATCHER(IsDivisibleBy7, std::string(negation ? "isn't" : "is") + " divisible by 7") { return (arg % 7) == 0; @@ -2911,7 +2894,7 @@ MATCHER(IsDivisibleBy7, std::string(negation ? "isn't" : "is") + Optionally, you can stream additional information to a hidden argument named `result_listener` to explain the match result. For example, a better definition of `IsDivisibleBy7` is: -``` +```cpp MATCHER(IsDivisibleBy7, "") { if ((arg % 7) == 0) return true; @@ -2944,18 +2927,18 @@ Google Mock already prints it for you. Sometimes you'll want to define a matcher that has parameters. For that you can use the macro: -``` +```cpp MATCHER_P(name, param_name, description_string) { statements; } ``` where the description string can be either `""` or a string expression that references `negation` and `param_name`. For example: -``` +```cpp MATCHER_P(HasAbsoluteValue, value, "") { return abs(arg) == value; } ``` will allow you to write: -``` +```cpp EXPECT_THAT(Blah("a"), HasAbsoluteValue(n)); ``` which may lead to this message (assuming `n` is 10): @@ -2975,7 +2958,7 @@ body of `MATCHER_P(HasAbsoluteValue, value)` above, you can write Google Mock also provides `MATCHER_P2`, `MATCHER_P3`, ..., up to `MATCHER_P10` to support multi-parameter matchers: -``` +```cpp MATCHER_Pk(name, param_1, ..., param_k, description_string) { statements; } ``` @@ -2987,7 +2970,7 @@ referencing the matcher parameters in the description string expression. For example, -``` +```cpp using ::testing::PrintToString; MATCHER_P2(InClosedRange, low, hi, std::string(negation ? "isn't" : "is") + " in range [" + @@ -3005,7 +2988,7 @@ would generate a failure that contains the message: If you specify `""` as the description, the failure message will contain the sequence of words in the matcher name followed by the parameter values printed as a tuple. For example, -``` +```cpp MATCHER_P2(InClosedRange, low, hi, "") { ... } ... EXPECT_THAT(3, InClosedRange(4, 6)); @@ -3016,11 +2999,11 @@ would generate a failure that contains the text: ``` For the purpose of typing, you can view -``` +```cpp MATCHER_Pk(Foo, p1, ..., pk, description_string) { ... } ``` as shorthand for -``` +```cpp template <typename p1_type, ..., typename pk_type> FooMatcherPk<p1_type, ..., pk_type> Foo(p1_type p1, ..., pk_type pk) { ... } @@ -3049,7 +3032,7 @@ matcher you will see the value of the referenced object but not its address. You can overload matchers with different numbers of parameters: -``` +```cpp MATCHER_P(Blah, a, description_string_1) { ... } MATCHER_P2(Blah, a, b, description_string_2) { ... } ``` @@ -3075,7 +3058,7 @@ error messages when expectations are violated. The interface looks like this: -``` +```cpp class MatchResultListener { public: ... @@ -3115,7 +3098,7 @@ strictly needed but it makes the syntax of using the matcher nicer. For example, you can define a matcher to test whether an `int` is divisible by 7 and then use it like this: -``` +```cpp using ::testing::MakeMatcher; using ::testing::Matcher; using ::testing::MatcherInterface; @@ -3147,7 +3130,7 @@ inline Matcher<int> DivisibleBy7() { You may improve the matcher message by streaming additional information to the `listener` argument in `MatchAndExplain()`: -``` +```cpp class DivisibleBy7Matcher : public MatcherInterface<int> { public: virtual bool MatchAndExplain(int n, @@ -3184,7 +3167,7 @@ Fortunately, most of the time you can define a polymorphic matcher easily with the help of `MakePolymorphicMatcher()`. Here's how you can define `NotNull()` as an example: -``` +```cpp using ::testing::MakePolymorphicMatcher; using ::testing::MatchResultListener; using ::testing::NotNull; @@ -3241,7 +3224,7 @@ If the built-in set of cardinalities doesn't suit you, you are free to define your own by implementing the following interface (in namespace `testing`): -``` +```cpp class CardinalityInterface { public: virtual ~CardinalityInterface(); @@ -3260,7 +3243,7 @@ class CardinalityInterface { For example, to specify that a call must occur even number of times, you can write -``` +```cpp using ::testing::Cardinality; using ::testing::CardinalityInterface; using ::testing::MakeCardinality; @@ -3297,7 +3280,7 @@ family to quickly define a new action that can be used in your code as if it's a built-in action. By writing -``` +```cpp ACTION(name) { statements; } ``` in a namespace scope (i.e. not inside a class or function), you will @@ -3305,11 +3288,11 @@ define an action with the given name that executes the statements. The value returned by `statements` will be used as the return value of the action. Inside the statements, you can refer to the K-th (0-based) argument of the mock function as `argK`. For example: -``` +```cpp ACTION(IncrementArg1) { return ++(*arg1); } ``` allows you to write -``` +```cpp ... WillOnce(IncrementArg1()); ``` @@ -3320,7 +3303,7 @@ operator, or if the type of `++(*arg1)` isn't compatible with the mock function's return type. Another example: -``` +```cpp ACTION(Foo) { (*arg2)(5); Blah(); @@ -3335,18 +3318,19 @@ with 5, calls function `Blah()`, sets the value pointed to by argument For more convenience and flexibility, you can also use the following pre-defined symbols in the body of `ACTION`: -| `argK_type` | The type of the K-th (0-based) argument of the mock function | -|:------------|:-------------------------------------------------------------| -| `args` | All arguments of the mock function as a tuple | -| `args_type` | The type of all arguments of the mock function as a tuple | -| `return_type` | The return type of the mock function | +| `argK_type` | The type of the K-th (0-based) argument of the mock function | +|:----------------|:-------------------------------------------------------------| +| `args` | All arguments of the mock function as a tuple | +| `args_type` | The type of all arguments of the mock function as a tuple | +| `return_type` | The return type of the mock function | | `function_type` | The type of the mock function | For example, when using an `ACTION` as a stub action for mock function: -``` +```cpp int DoSomething(bool flag, int* ptr); ``` we have: + | **Pre-defined Symbol** | **Is Bound To** | |:-----------------------|:----------------| | `arg0` | the value of `flag` | @@ -3362,16 +3346,16 @@ we have: Sometimes you'll want to parameterize an action you define. For that we have another macro -``` +```cpp ACTION_P(name, param) { statements; } ``` For example, -``` +```cpp ACTION_P(Add, n) { return arg0 + n; } ``` will allow you to write -``` +```cpp // Returns argument #0 + 5. ... WillOnce(Add(5)); ``` @@ -3388,7 +3372,7 @@ parameter as inferred by the compiler. For example, in the body of Google Mock also provides `ACTION_P2`, `ACTION_P3`, and etc to support multi-parameter actions. For example, -``` +```cpp ACTION_P2(ReturnDistanceTo, x, y) { double dx = arg0 - x; double dy = arg1 - y; @@ -3396,7 +3380,7 @@ ACTION_P2(ReturnDistanceTo, x, y) { } ``` lets you write -``` +```cpp ... WillOnce(ReturnDistanceTo(5.0, 26.5)); ``` @@ -3404,7 +3388,7 @@ You can view `ACTION` as a degenerated parameterized action where the number of parameters is 0. You can also easily define actions overloaded on the number of parameters: -``` +```cpp ACTION_P(Plus, a) { ... } ACTION_P2(Plus, a, b) { ... } ``` @@ -3417,7 +3401,7 @@ parameters. Instead, we let the compiler infer the types for us. Sometimes, however, we may want to be more explicit about the types. There are several tricks to do that. For example: -``` +```cpp ACTION(Foo) { // Makes sure arg0 can be converted to int. int n = arg0; @@ -3443,7 +3427,7 @@ supports that and can be viewed as an extension to `ACTION()` and `ACTION_P*()`. The syntax: -``` +```cpp ACTION_TEMPLATE(ActionName, HAS_m_TEMPLATE_PARAMS(kind1, name1, ..., kind_m, name_m), AND_n_VALUE_PARAMS(p1, ..., p_n)) { statements; } @@ -3457,7 +3441,7 @@ integral constant, or a template. `p_i` is the name of the i-th value parameter. Example: -``` +```cpp // DuplicateArg<k, T>(output) converts the k-th argument of the mock // function to type T and copies it to *output. ACTION_TEMPLATE(DuplicateArg, @@ -3469,13 +3453,13 @@ ACTION_TEMPLATE(DuplicateArg, ``` To create an instance of an action template, write: -``` +```cpp ActionName<t1, ..., t_m>(v1, ..., v_n) ``` where the `t`s are the template arguments and the `v`s are the value arguments. The value argument types are inferred by the compiler. For example: -``` +```cpp using ::testing::_; ... int n; @@ -3485,7 +3469,7 @@ using ::testing::_; If you want to explicitly specify the value argument types, you can provide additional template arguments: -``` +```cpp ActionName<t1, ..., t_m, u1, ..., u_k>(v1, ..., v_n) ``` where `u_i` is the desired type of `v_i`. @@ -3495,7 +3479,7 @@ number of value parameters, but not on the number of template parameters. Without the restriction, the meaning of the following is unclear: -``` +```cpp OverloadedAction<int, bool>(x); ``` @@ -3508,15 +3492,16 @@ is asked to infer the type of `x`? If you are writing a function that returns an `ACTION` object, you'll need to know its type. The type depends on the macro used to define the action and the parameter types. The rule is relatively simple: + | **Given Definition** | **Expression** | **Has Type** | |:---------------------|:---------------|:-------------| -| `ACTION(Foo)` | `Foo()` | `FooAction` | +| `ACTION(Foo)` | `Foo()` | `FooAction` | | `ACTION_TEMPLATE(Foo, HAS_m_TEMPLATE_PARAMS(...), AND_0_VALUE_PARAMS())` | `Foo<t1, ..., t_m>()` | `FooAction<t1, ..., t_m>` | | `ACTION_P(Bar, param)` | `Bar(int_value)` | `BarActionP<int>` | | `ACTION_TEMPLATE(Bar, HAS_m_TEMPLATE_PARAMS(...), AND_1_VALUE_PARAMS(p1))` | `Bar<t1, ..., t_m>(int_value)` | `FooActionP<t1, ..., t_m, int>` | | `ACTION_P2(Baz, p1, p2)` | `Baz(bool_value, int_value)` | `BazActionP2<bool, int>` | -| `ACTION_TEMPLATE(Baz, HAS_m_TEMPLATE_PARAMS(...), AND_2_VALUE_PARAMS(p1, p2))` | `Baz<t1, ..., t_m>(bool_value, int_value)` | `FooActionP2<t1, ..., t_m, bool, int>` | -| ... | ... | ... | +| `ACTION_TEMPLATE(Baz, HAS_m_TEMPLATE_PARAMS(...), AND_2_VALUE_PARAMS(p1, p2))`| `Baz<t1, ..., t_m>(bool_value, int_value)` | `FooActionP2<t1, ..., t_m, bool, int>` | +| ... | ... | ... | Note that we have to pick different suffixes (`Action`, `ActionP`, `ActionP2`, and etc) for actions with different numbers of value @@ -3537,7 +3522,7 @@ An alternative to the `ACTION*` macros is to implement `::testing::ActionInterface<F>`, where `F` is the type of the mock function in which the action will be used. For example: -``` +```cpp template <typename F>class ActionInterface { public: virtual ~ActionInterface(); @@ -3589,7 +3574,7 @@ If an action can be used in several types of mock functions, we say it's _polymorphic_. The `MakePolymorphicAction()` function template makes it easy to define such an action: -``` +```cpp namespace testing { template <typename Impl> @@ -3602,7 +3587,7 @@ As an example, let's define an action that returns the second argument in the mock function's argument list. The first step is to define an implementation class: -``` +```cpp class ReturnSecondArgumentAction { public: template <typename Result, typename ArgumentTuple> @@ -3626,7 +3611,7 @@ Next, we use `MakePolymorphicAction()` to turn an instance of the implementation class into the polymorphic action we need. It will be convenient to have a wrapper for this: -``` +```cpp using ::testing::MakePolymorphicAction; using ::testing::PolymorphicAction; @@ -3638,7 +3623,7 @@ PolymorphicAction<ReturnSecondArgumentAction> ReturnSecondArgument() { Now, you can use this polymorphic action the same way you use the built-in ones: -``` +```cpp using ::testing::_; class MockFoo : public Foo { @@ -3670,6 +3655,6 @@ This printer knows how to print built-in C++ types, native arrays, STL containers, and any type that supports the `<<` operator. For other types, it prints the raw bytes in the value and hopes that you the user can figure it out. -[Google Test's advanced guide](../../googletest/docs/AdvancedGuide.md#teaching-google-test-how-to-print-your-values) +[Google Test's advanced guide](../../googletest/docs/advanced.md#teaching-googletest-how-to-print-your-values) explains how to extend the printer to do a better job at printing your particular type than to dump the bytes. diff --git a/googlemock/docs/DesignDoc.md b/googlemock/docs/DesignDoc.md index 3f515c3..4cddc9d 100644 --- a/googlemock/docs/DesignDoc.md +++ b/googlemock/docs/DesignDoc.md @@ -11,7 +11,7 @@ non-trivial effort to define a custom action in Google Mock. For example, suppose you want to "increment the value pointed to by the second argument of the mock function and return it", you could write: -``` +```cpp int IncrementArg1(Unused, int* p, Unused) { return ++(*p); } @@ -28,7 +28,7 @@ There are several things unsatisfactory about this approach: The latter two problems can be overcome using `MakePolymorphicAction()`, but it requires much more boilerplate code: -``` +```cpp class IncrementArg1Action { public: template <typename Result, typename ArgumentTuple> @@ -50,7 +50,7 @@ boiler-plate C++ requires. ## Solution ## We propose to introduce a new macro: -``` +```cpp ACTION(name) { statements; } ``` @@ -58,11 +58,11 @@ Using this in a namespace scope will define an action with the given name that executes the statements. Inside the statements, you can refer to the K-th (0-based) argument of the mock function as `argK`. For example: -``` +```cpp ACTION(IncrementArg1) { return ++(*arg1); } ``` allows you to write -``` +```cpp ... WillOnce(IncrementArg1()); ``` @@ -73,7 +73,7 @@ your code is still type-safe though: you'll get a compiler error if `++(*arg1)` isn't compatible with the mock function's return type. Another example: -``` +```cpp ACTION(Foo) { (*arg2)(5); Blah(); @@ -88,18 +88,20 @@ with 5, calls function `Blah()`, sets the value pointed to by argument For more convenience and flexibility, you can also use the following pre-defined symbols in the body of `ACTION`: -| `argK_type` | The type of the K-th (0-based) argument of the mock function | -|:------------|:-------------------------------------------------------------| -| `args` | All arguments of the mock function as a tuple | -| `args_type` | The type of all arguments of the mock function as a tuple | -| `return_type` | The return type of the mock function | +| Argument | Description | +|:----------------|:-------------------------------------------------------------| +| `argK_type` | The type of the K-th (0-based) argument of the mock function | +| `args` | All arguments of the mock function as a tuple | +| `args_type` | The type of all arguments of the mock function as a tuple | +| `return_type` | The return type of the mock function | | `function_type` | The type of the mock function | For example, when using an `ACTION` as a stub action for mock function: -``` +```cpp int DoSomething(bool flag, int* ptr); ``` we have: + | **Pre-defined Symbol** | **Is Bound To** | |:-----------------------|:----------------| | `arg0` | the value of `flag` | @@ -115,16 +117,16 @@ we have: Sometimes you'll want to parameterize the action. For that we propose another macro -``` +```cpp ACTION_P(name, param) { statements; } ``` For example, -``` +```cpp ACTION_P(Add, n) { return arg0 + n; } ``` will allow you to write -``` +```cpp // Returns argument #0 + 5. ... WillOnce(Add(5)); ``` @@ -140,7 +142,7 @@ parameter as inferred by the compiler. We will also provide `ACTION_P2`, `ACTION_P3`, and etc to support multi-parameter actions. For example, -``` +```cpp ACTION_P2(ReturnDistanceTo, x, y) { double dx = arg0 - x; double dy = arg1 - y; @@ -148,7 +150,7 @@ ACTION_P2(ReturnDistanceTo, x, y) { } ``` lets you write -``` +```cpp ... WillOnce(ReturnDistanceTo(5.0, 26.5)); ``` @@ -160,7 +162,7 @@ number of parameters is 0. ### Overloading Actions ### You can easily define actions overloaded on the number of parameters: -``` +```cpp ACTION_P(Plus, a) { ... } ACTION_P2(Plus, a, b) { ... } ``` @@ -173,7 +175,7 @@ parameters. Instead, we let the compiler infer the types for us. Sometimes, however, we may want to be more explicit about the types. There are several tricks to do that. For example: -``` +```cpp ACTION(Foo) { // Makes sure arg0 can be converted to int. int n = arg0; @@ -196,12 +198,12 @@ Google Test (the name is chosen to match `static_assert` in C++0x). If you are writing a function that returns an `ACTION` object, you'll need to know its type. The type depends on the macro used to define the action and the parameter types. The rule is relatively simple: -| **Given Definition** | **Expression** | **Has Type** | -|:---------------------|:---------------|:-------------| -| `ACTION(Foo)` | `Foo()` | `FooAction` | -| `ACTION_P(Bar, param)` | `Bar(int_value)` | `BarActionP<int>` | +| **Given Definition** | **Expression** | **Has Type** | +|:-------------------------|:-----------------------------|:-------------------------| +| `ACTION(Foo)` | `Foo()` | `FooAction` | +| `ACTION_P(Bar, param)` | `Bar(int_value)` | `BarActionP<int>` | | `ACTION_P2(Baz, p1, p2)` | `Baz(bool_value, int_value)` | `BazActionP2<bool, int>` | -| ... | ... | ... | +| ... | ... | ... | Note that we have to pick different suffixes (`Action`, `ActionP`, `ActionP2`, and etc) for actions with different numbers of parameters, @@ -262,14 +264,14 @@ available, we may want to support using lambdas as actions. Once the macros for defining actions are implemented, we plan to do the same for matchers: -``` +```cpp MATCHER(name) { statements; } ``` where you can refer to the value being matched as `arg`. For example, given: -``` +```cpp MATCHER(IsPositive) { return arg > 0; } ``` @@ -277,4 +279,4 @@ you can use `IsPositive()` as a matcher that matches a value iff it is greater than 0. We will also add `MATCHER_P`, `MATCHER_P2`, and etc for parameterized -matchers.
\ No newline at end of file +matchers. diff --git a/googlemock/docs/DevGuide.md b/googlemock/docs/DevGuide.md deleted file mode 100644 index f4bab75..0000000 --- a/googlemock/docs/DevGuide.md +++ /dev/null @@ -1,132 +0,0 @@ - - -If you are interested in understanding the internals of Google Mock, -building from source, or contributing ideas or modifications to the -project, then this document is for you. - -# Introduction # - -First, let's give you some background of the project. - -## Licensing ## - -All Google Mock source and pre-built packages are provided under the [New BSD License](http://www.opensource.org/licenses/bsd-license.php). - -## The Google Mock Community ## - -The Google Mock community exists primarily through the [discussion group](http://groups.google.com/group/googlemock), the -[issue tracker](https://github.com/google/googletest/issues) and, to a lesser extent, the [source control repository](../). You are definitely encouraged to contribute to the -discussion and you can also help us to keep the effectiveness of the -group high by following and promoting the guidelines listed here. - -### Please Be Friendly ### - -Showing courtesy and respect to others is a vital part of the Google -culture, and we strongly encourage everyone participating in Google -Mock development to join us in accepting nothing less. Of course, -being courteous is not the same as failing to constructively disagree -with each other, but it does mean that we should be respectful of each -other when enumerating the 42 technical reasons that a particular -proposal may not be the best choice. There's never a reason to be -antagonistic or dismissive toward anyone who is sincerely trying to -contribute to a discussion. - -Sure, C++ testing is serious business and all that, but it's also -a lot of fun. Let's keep it that way. Let's strive to be one of the -friendliest communities in all of open source. - -### Where to Discuss Google Mock ### - -As always, discuss Google Mock in the official [Google C++ Mocking Framework discussion group](http://groups.google.com/group/googlemock). You don't have to actually submit -code in order to sign up. Your participation itself is a valuable -contribution. - -# Working with the Code # - -If you want to get your hands dirty with the code inside Google Mock, -this is the section for you. - -## Checking Out the Source from Subversion ## - -Checking out the Google Mock source is most useful if you plan to -tweak it yourself. You check out the source for Google Mock using a -[Subversion](http://subversion.tigris.org/) client as you would for any -other project hosted on Google Code. Please see the instruction on -the [source code access page](../) for how to do it. - -## Compiling from Source ## - -Once you check out the code, you can find instructions on how to -compile it in the [README](../README.md) file. - -## Testing ## - -A mocking framework is of no good if itself is not thoroughly tested. -Tests should be written for any new code, and changes should be -verified to not break existing tests before they are submitted for -review. To perform the tests, follow the instructions in [README](http://code.google.com/p/googlemock/source/browse/trunk/README) and -verify that there are no failures. - -# Contributing Code # - -We are excited that Google Mock is now open source, and hope to get -great patches from the community. Before you fire up your favorite IDE -and begin hammering away at that new feature, though, please take the -time to read this section and understand the process. While it seems -rigorous, we want to keep a high standard of quality in the code -base. - -## Contributor License Agreements ## - -You must sign a Contributor License Agreement (CLA) before we can -accept any code. The CLA protects you and us. - - * If you are an individual writing original source code and you're sure you own the intellectual property, then you'll need to sign an [individual CLA](http://code.google.com/legal/individual-cla-v1.0.html). - * If you work for a company that wants to allow you to contribute your work to Google Mock, then you'll need to sign a [corporate CLA](http://code.google.com/legal/corporate-cla-v1.0.html). - -Follow either of the two links above to access the appropriate CLA and -instructions for how to sign and return it. - -## Coding Style ## - -To keep the source consistent, readable, diffable and easy to merge, -we use a fairly rigid coding style, as defined by the [google-styleguide](https://github.com/google/styleguide) project. All patches will be expected -to conform to the style outlined [here](https://github.com/google/styleguide/blob/gh-pages/cppguide.xml). - -## Submitting Patches ## - -Please do submit code. Here's what you need to do: - - 1. Normally you should make your change against the SVN trunk instead of a branch or a tag, as the latter two are for release control and should be treated mostly as read-only. - 1. Decide which code you want to submit. A submission should be a set of changes that addresses one issue in the [Google Mock issue tracker](http://code.google.com/p/googlemock/issues/list). Please don't mix more than one logical change per submittal, because it makes the history hard to follow. If you want to make a change that doesn't have a corresponding issue in the issue tracker, please create one. - 1. Also, coordinate with team members that are listed on the issue in question. This ensures that work isn't being duplicated and communicating your plan early also generally leads to better patches. - 1. Ensure that your code adheres to the [Google Mock source code style](#Coding_Style.md). - 1. Ensure that there are unit tests for your code. - 1. Sign a Contributor License Agreement. - 1. Create a patch file using `svn diff`. - 1. We use [Rietveld](http://codereview.appspot.com/) to do web-based code reviews. You can read about the tool [here](https://github.com/rietveld-codereview/rietveld/wiki). When you are ready, upload your patch via Rietveld and notify `googlemock@googlegroups.com` to review it. There are several ways to upload the patch. We recommend using the [upload\_gmock.py](../scripts/upload_gmock.py) script, which you can find in the `scripts/` folder in the SVN trunk. - -## Google Mock Committers ## - -The current members of the Google Mock engineering team are the only -committers at present. In the great tradition of eating one's own -dogfood, we will be requiring each new Google Mock engineering team -member to earn the right to become a committer by following the -procedures in this document, writing consistently great code, and -demonstrating repeatedly that he or she truly gets the zen of Google -Mock. - -# Release Process # - -We follow the typical release process for Subversion-based projects: - - 1. A release branch named `release-X.Y` is created. - 1. Bugs are fixed and features are added in trunk; those individual patches are merged into the release branch until it's stable. - 1. An individual point release (the `Z` in `X.Y.Z`) is made by creating a tag from the branch. - 1. Repeat steps 2 and 3 throughout one release cycle (as determined by features or time). - 1. Go back to step 1 to create another release branch and so on. - - ---- - -This page is based on the [Making GWT Better](http://code.google.com/webtoolkit/makinggwtbetter.html) guide from the [Google Web Toolkit](http://code.google.com/webtoolkit/) project. Except as otherwise [noted](http://code.google.com/policies.html#restrictions), the content of this page is licensed under the [Creative Commons Attribution 2.5 License](http://creativecommons.org/licenses/by/2.5/). diff --git a/googlemock/docs/Documentation.md b/googlemock/docs/Documentation.md index 444151e..a42bd11 100644 --- a/googlemock/docs/Documentation.md +++ b/googlemock/docs/Documentation.md @@ -1,5 +1,8 @@ -This page lists all documentation wiki pages for Google Mock **(the SVN trunk version)** -- **if you use a released version of Google Mock, please read the documentation for that specific version instead.** +This page lists all documentation markdown files for Google Mock **(the +current git version)** +-- **if you use a former version of Google Mock, please read the +documentation for that specific version instead (e.g. by checking out +the respective git branch/tag).** * [ForDummies](ForDummies.md) -- start here if you are new to Google Mock. * [CheatSheet](CheatSheet.md) -- a quick reference. @@ -8,5 +11,5 @@ This page lists all documentation wiki pages for Google Mock **(the SVN trunk ve To contribute code to Google Mock, read: - * [DevGuide](DevGuide.md) -- read this _before_ writing your first patch. - * [Pump Manual](../googletest/docs/PumpManual.md) -- how we generate some of Google Mock's source files. + * [CONTRIBUTING](../../CONTRIBUTING.md) -- read this _before_ writing your first patch. + * [Pump Manual](../../googletest/docs/PumpManual.md) -- how we generate some of Google Mock's source files. diff --git a/googlemock/docs/ForDummies.md b/googlemock/docs/ForDummies.md index 0da4cbe..e2a430f 100644 --- a/googlemock/docs/ForDummies.md +++ b/googlemock/docs/ForDummies.md @@ -23,8 +23,8 @@ Using Google Mock involves three basic steps: # Why Google Mock? # While mock objects help you remove unnecessary dependencies in tests and make them fast and reliable, using mocks manually in C++ is _hard_: - * Someone has to implement the mocks. The job is usually tedious and error-prone. No wonder people go great distance to avoid it. - * The quality of those manually written mocks is a bit, uh, unpredictable. You may see some really polished ones, but you may also see some that were hacked up in a hurry and have all sorts of ad hoc restrictions. + * Someone has to implement the mocks. The job is usually tedious and error-prone. No wonder people go great distances to avoid it. + * The quality of those manually written mocks is a bit, uh, unpredictable. You may see some really polished ones, but you may also see some that were hacked up in a hurry and have all sorts of ad-hoc restrictions. * The knowledge you gained from using one mock doesn't transfer to the next. In contrast, Java and Python programmers have some fine mock frameworks, which automate the creation of mocks. As a result, mocking is a proven effective technique and widely adopted practice in those communities. Having the right tool absolutely makes the difference. @@ -49,7 +49,7 @@ Using Google Mock is easy! Inside your C++ source file, just `#include` `"gtest/ # A Case for Mock Turtles # Let's look at an example. Suppose you are developing a graphics program that relies on a LOGO-like API for drawing. How would you test that it does the right thing? Well, you can run it and compare the screen with a golden screen snapshot, but let's admit it: tests like this are expensive to run and fragile (What if you just upgraded to a shiny new graphics card that has better anti-aliasing? Suddenly you have to update all your golden images.). It would be too painful if all your tests are like this. Fortunately, you learned about Dependency Injection and know the right thing to do: instead of having your application talk to the drawing API directly, wrap the API in an interface (say, `Turtle`) and code to that interface: -``` +```cpp class Turtle { ... virtual ~Turtle() {} @@ -83,7 +83,7 @@ Using the `Turtle` interface as example, here are the simple steps you need to f After the process, you should have something like: -``` +```cpp #include "gmock/gmock.h" // Brings in Google Mock. class MockTurtle : public Turtle { public: @@ -125,7 +125,7 @@ Once you have a mock class, using it is easy. The typical work flow is: Here's an example: -``` +```cpp #include "path/to/mock-turtle.h" #include "gmock/gmock.h" #include "gtest/gtest.h" @@ -170,8 +170,8 @@ Admittedly, this test is contrived and doesn't do much. You can easily achieve t ## Using Google Mock with Any Testing Framework ## If you want to use something other than Google Test (e.g. [CppUnit](http://sourceforge.net/projects/cppunit/) or -[CxxTest](http://cxxtest.tigris.org/)) as your testing framework, just change the `main()` function in the previous section to: -``` +[CxxTest](https://cxxtest.com/)) as your testing framework, just change the `main()` function in the previous section to: +```cpp int main(int argc, char** argv) { // The following line causes Google Mock to throw an exception on failure, // which will be interpreted by your testing framework as a test failure. @@ -187,7 +187,7 @@ sometimes causes the test program to crash. You'll still be able to notice that the test has failed, but it's not a graceful failure. A better solution is to use Google Test's -[event listener API](../../googletest/docs/AdvancedGuide.md#extending-google-test-by-handling-test-events) +[event listener API](../../googletest/docs/advanced.md#extending-googletest-by-handling-test-events) to report a test failure to your testing framework properly. You'll need to implement the `OnTestPartResult()` method of the event listener interface, but it should be straightforward. @@ -203,7 +203,7 @@ The key to using a mock object successfully is to set the _right expectations_ o ## General Syntax ## In Google Mock we use the `EXPECT_CALL()` macro to set an expectation on a mock method. The general syntax is: -``` +```cpp EXPECT_CALL(mock_object, method(matchers)) .Times(cardinality) .WillOnce(action) @@ -216,8 +216,9 @@ The macro can be followed by some optional _clauses_ that provide more informati This syntax is designed to make an expectation read like English. For example, you can probably guess that -``` -using ::testing::Return;... +```cpp +using ::testing::Return; +... EXPECT_CALL(turtle, GetX()) .Times(5) .WillOnce(Return(100)) @@ -232,14 +233,14 @@ says that the `turtle` object's `GetX()` method will be called five times, it wi ## Matchers: What Arguments Do We Expect? ## When a mock function takes arguments, we must specify what arguments we are expecting; for example: -``` +```cpp // Expects the turtle to move forward by 100 units. EXPECT_CALL(turtle, Forward(100)); ``` Sometimes you may not want to be too specific (Remember that talk about tests being too rigid? Over specification leads to brittle tests and obscures the intent of tests. Therefore we encourage you to specify only what's necessary - no more, no less.). If you care to check that `Forward()` will be called but aren't interested in its actual argument, write `_` as the argument, which means "anything goes": -``` +```cpp using ::testing::_; ... // Expects the turtle to move forward. @@ -250,8 +251,9 @@ EXPECT_CALL(turtle, Forward(_)); A list of built-in matchers can be found in the [CheatSheet](CheatSheet.md). For example, here's the `Ge` (greater than or equal) matcher: -``` -using ::testing::Ge;... +```cpp +using ::testing::Ge; +... EXPECT_CALL(turtle, Forward(Ge(100))); ``` @@ -279,8 +281,9 @@ First, if the return type of a mock function is a built-in type or a pointer, th Second, if a mock function doesn't have a default action, or the default action doesn't suit you, you can specify the action to be taken each time the expectation matches using a series of `WillOnce()` clauses followed by an optional `WillRepeatedly()`. For example, -``` -using ::testing::Return;... +```cpp +using ::testing::Return; +... EXPECT_CALL(turtle, GetX()) .WillOnce(Return(100)) .WillOnce(Return(200)) @@ -289,8 +292,9 @@ EXPECT_CALL(turtle, GetX()) This says that `turtle.GetX()` will be called _exactly three times_ (Google Mock inferred this from how many `WillOnce()` clauses we've written, since we didn't explicitly write `Times()`), and will return 100, 200, and 300 respectively. -``` -using ::testing::Return;... +```cpp +using ::testing::Return; +... EXPECT_CALL(turtle, GetY()) .WillOnce(Return(100)) .WillOnce(Return(200)) @@ -305,7 +309,7 @@ What can we do inside `WillOnce()` besides `Return()`? You can return a referenc **Important note:** The `EXPECT_CALL()` statement evaluates the action clause only once, even though the action may be performed many times. Therefore you must be careful about side effects. The following may not do what you want: -``` +```cpp int n = 100; EXPECT_CALL(turtle, GetX()) .Times(4) @@ -316,8 +320,9 @@ Instead of returning 100, 101, 102, ..., consecutively, this mock function will Time for another quiz! What do you think the following means? -``` -using ::testing::Return;... +```cpp +using ::testing::Return; +... EXPECT_CALL(turtle, GetY()) .Times(4) .WillOnce(Return(100)); @@ -330,8 +335,9 @@ So far we've only shown examples where you have a single expectation. More reali By default, when a mock method is invoked, Google Mock will search the expectations in the **reverse order** they are defined, and stop when an active expectation that matches the arguments is found (you can think of it as "newer rules override older ones."). If the matching expectation cannot take any more calls, you will get an upper-bound-violated failure. Here's an example: -``` -using ::testing::_;... +```cpp +using ::testing::_; +... EXPECT_CALL(turtle, Forward(_)); // #1 EXPECT_CALL(turtle, Forward(10)) // #2 .Times(2); @@ -346,8 +352,9 @@ By default, an expectation can match a call even though an earlier expectation h Sometimes, you may want all the expected calls to occur in a strict order. To say this in Google Mock is easy: -``` -using ::testing::InSequence;... +```cpp +using ::testing::InSequence; +... TEST(FooTest, DrawsLineSegment) { ... { @@ -365,15 +372,16 @@ By creating an object of type `InSequence`, all expectations in its scope are pu In this example, we test that `Foo()` calls the three expected functions in the order as written. If a call is made out-of-order, it will be an error. -(What if you care about the relative order of some of the calls, but not all of them? Can you specify an arbitrary partial order? The answer is ... yes! If you are impatient, the details can be found in the [CookBook](CookBook#Expecting_Partially_Ordered_Calls.md).) +(What if you care about the relative order of some of the calls, but not all of them? Can you specify an arbitrary partial order? The answer is ... yes! If you are impatient, the details can be found in the [CookBook](CookBook.md#expecting-partially-ordered-calls).) ## All Expectations Are Sticky (Unless Said Otherwise) ## Now let's do a quick quiz to see how well you can use this mock stuff already. How would you test that the turtle is asked to go to the origin _exactly twice_ (you want to ignore any other instructions it receives)? After you've come up with your answer, take a look at ours and compare notes (solve it yourself first - don't cheat!): -``` -using ::testing::_;... +```cpp +using ::testing::_; +... EXPECT_CALL(turtle, GoTo(_, _)) // #1 .Times(AnyNumber()); EXPECT_CALL(turtle, GoTo(0, 0)) // #2 @@ -386,7 +394,7 @@ This example shows that **expectations in Google Mock are "sticky" by default**, Simple? Let's see if you've really understood it: what does the following code say? -``` +```cpp using ::testing::Return; ... for (int i = n; i > 0; i--) { @@ -399,7 +407,7 @@ If you think it says that `turtle.GetX()` will be called `n` times and will retu One correct way of saying that `turtle.GetX()` will return 10, 20, 30, ..., is to explicitly say that the expectations are _not_ sticky. In other words, they should _retire_ as soon as they are saturated: -``` +```cpp using ::testing::Return; ... for (int i = n; i > 0; i--) { @@ -411,7 +419,7 @@ for (int i = n; i > 0; i--) { And, there's a better way to do it: in this case, we expect the calls to occur in a specific order, and we line up the actions to match the order. Since the order is important here, we should make it explicit using a sequence: -``` +```cpp using ::testing::InSequence; using ::testing::Return; ... diff --git a/googlemock/docs/FrequentlyAskedQuestions.md b/googlemock/docs/FrequentlyAskedQuestions.md index 5eac83f..e91f038 100644 --- a/googlemock/docs/FrequentlyAskedQuestions.md +++ b/googlemock/docs/FrequentlyAskedQuestions.md @@ -3,7 +3,7 @@ Please send your questions to the [googlemock](http://groups.google.com/group/googlemock) discussion group. If you need help with compiler errors, make sure you have -tried [Google Mock Doctor](#How_am_I_supposed_to_make_sense_of_these_horrible_template_error.md) first. +tried [Google Mock Doctor](#how-am-i-supposed-to-make-sense-of-these-horrible-template-errors) first. ## When I call a method on my mock object, the method for the real object is invoked instead. What's the problem? ## @@ -27,7 +27,7 @@ later. Fortunately, it's usually not hard to migrate an existing matcher to the new API. Here's what you need to do: If you wrote your matcher like this: -``` +```cpp // Old matcher definition that doesn't work with the latest // Google Mock. using ::testing::MatcherInterface; @@ -44,7 +44,7 @@ class MyWonderfulMatcher : public MatcherInterface<MyType> { ``` you'll need to change it to: -``` +```cpp // New matcher definition that works with the latest Google Mock. using ::testing::MatcherInterface; using ::testing::MatchResultListener; @@ -65,7 +65,7 @@ argument of type `MatchResultListener*`.) If you were also using `ExplainMatchResultTo()` to improve the matcher message: -``` +```cpp // Old matcher definition that doesn't work with the lastest // Google Mock. using ::testing::MatcherInterface; @@ -91,7 +91,7 @@ class MyWonderfulMatcher : public MatcherInterface<MyType> { you should move the logic of `ExplainMatchResultTo()` into `MatchAndExplain()`, using the `MatchResultListener` argument where the `::std::ostream` was used: -``` +```cpp // New matcher definition that works with the latest Google Mock. using ::testing::MatcherInterface; using ::testing::MatchResultListener; @@ -110,7 +110,7 @@ class MyWonderfulMatcher : public MatcherInterface<MyType> { ``` If your matcher is defined using `MakePolymorphicMatcher()`: -``` +```cpp // Old matcher definition that doesn't work with the latest // Google Mock. using ::testing::MakePolymorphicMatcher; @@ -130,7 +130,7 @@ class MyGreatMatcher { you should rename the `Matches()` method to `MatchAndExplain()` and add a `MatchResultListener*` argument (the same as what you need to do for matchers defined by implementing `MatcherInterface`): -``` +```cpp // New matcher definition that works with the latest Google Mock. using ::testing::MakePolymorphicMatcher; using ::testing::MatchResultListener; @@ -150,7 +150,7 @@ class MyGreatMatcher { If your polymorphic matcher uses `ExplainMatchResultTo()` for better failure messages: -``` +```cpp // Old matcher definition that doesn't work with the latest // Google Mock. using ::testing::MakePolymorphicMatcher; @@ -176,7 +176,7 @@ void ExplainMatchResultTo(const MyGreatMatcher& matcher, you'll need to move the logic inside `ExplainMatchResultTo()` to `MatchAndExplain()`: -``` +```cpp // New matcher definition that works with the latest Google Mock. using ::testing::MakePolymorphicMatcher; using ::testing::MatchResultListener; @@ -240,7 +240,7 @@ You cannot mock a variadic function (i.e. a function taking ellipsis The problem is that in general, there is _no way_ for a mock object to know how many arguments are passed to the variadic method, and what the arguments' types are. Only the _author of the base class_ knows -the protocol, and we cannot look into his head. +the protocol, and we cannot look into their head. Therefore, to mock such a function, the _user_ must teach the mock object how to figure out the number of arguments and their types. One @@ -254,7 +254,7 @@ C++ as much as possible. ## MSVC gives me warning C4301 or C4373 when I define a mock method with a const parameter. Why? ## If you compile this using Microsoft Visual C++ 2005 SP1: -``` +```cpp class Foo { ... virtual void Bar(const int i) = 0; @@ -279,7 +279,7 @@ warning C4373: 'MockFoo::Bar': virtual function overrides 'Foo::Bar', previous v In C++, if you _declare_ a function with a `const` parameter, the `const` modifier is _ignored_. Therefore, the `Foo` base class above is equivalent to: -``` +```cpp class Foo { ... virtual void Bar(int i) = 0; // int or const int? Makes no difference. @@ -298,7 +298,7 @@ Note that we are talking about the _top-level_ `const` modifier here. If the function parameter is passed by pointer or reference, declaring the _pointee_ or _referee_ as `const` is still meaningful. For example, the following two declarations are _not_ equivalent: -``` +```cpp void Bar(int* p); // Neither p nor *p is const. void Bar(const int* p); // p is not const, but *p is. ``` @@ -318,7 +318,7 @@ you'll gain insights on why the expectations you set are not met. ## How can I assert that a function is NEVER called? ## -``` +```cpp EXPECT_CALL(foo, Bar(_)) .Times(0); ``` @@ -345,7 +345,7 @@ Whenever you derive from a base class, make sure its destructor is virtual. Otherwise Bad Things will happen. Consider the following code: -``` +```cpp class Base { public: // Not virtual, but should be. @@ -375,7 +375,7 @@ will be happy. When people complain about this, often they are referring to code like: -``` +```cpp // foo.Bar() should be called twice, return 1 the first time, and return // 2 the second time. However, I have to write the expectations in the // reverse order. This sucks big time!!! @@ -399,7 +399,7 @@ harder to do so. There are two better ways to write the test spec. You could either put the expectations in sequence: -``` +```cpp // foo.Bar() should be called twice, return 1 the first time, and return // 2 the second time. Using a sequence, we can write the expectations // in their natural order. @@ -416,7 +416,7 @@ put the expectations in sequence: or you can put the sequence of actions in the same expectation: -``` +```cpp // foo.Bar() should be called twice, return 1 the first time, and return // 2 the second time. EXPECT_CALL(foo, Bar()) @@ -450,14 +450,14 @@ may creep in unnoticed. If, however, you are sure that the calls are OK, you can write -``` +```cpp EXPECT_CALL(foo, Bar(_)) .WillRepeatedly(...); ``` instead of -``` +```cpp ON_CALL(foo, Bar(_)) .WillByDefault(...); ``` @@ -474,10 +474,10 @@ verbose level. If you find yourself needing to perform some action that's not supported by Google Mock directly, remember that you can define your own actions using -[MakeAction()](CookBook.md#writing-new-actions) or -[MakePolymorphicAction()](CookBook.md#writing_new_polymorphic_actions), +[MakeAction()](CookBook.md#writing-new-actions-quickly) or +[MakePolymorphicAction()](CookBook.md#writing-new-polymorphic-actions), or you can write a stub function and invoke it using -[Invoke()](CookBook.md#using-functions_methods_functors). +[Invoke()](CookBook.md#using-functionsmethodsfunctors-as-actions). ## MOCK\_METHODn()'s second argument looks funny. Why don't you use the MOCK\_METHODn(Method, return\_type, arg\_1, ..., arg\_n) syntax? ## @@ -488,12 +488,12 @@ extent, Google Mock's syntax was chosen for several practical advantages it has. Try to mock a function that takes a map as an argument: -``` +```cpp virtual int GetSize(const map<int, std::string>& m); ``` Using the proposed syntax, it would be: -``` +```cpp MOCK_METHOD1(GetSize, int, const map<int, std::string>& m); ``` @@ -503,7 +503,7 @@ around this you can use `typedef` to give the map type a name, but that gets in the way of your work. Google Mock's syntax avoids this problem as the function's argument types are protected inside a pair of parentheses: -``` +```cpp // This compiles fine. MOCK_METHOD1(GetSize, int(const map<int, std::string>& m)); ``` @@ -528,7 +528,7 @@ interface, which then can be easily mocked. It's a bit of work initially, but usually pays for itself quickly. This Google Testing Blog -[post](http://googletesting.blogspot.com/2008/06/defeat-static-cling.html) +[post](https://testing.googleblog.com/2008/06/defeat-static-cling.html) says it excellently. Check it out. ## My mock object needs to do complex stuff. It's a lot of pain to specify the actions. Google Mock sucks! ## @@ -599,7 +599,7 @@ when the mock method is called. `SetArgPointee()` says what the side effect is, but doesn't say what the return value should be. You need `DoAll()` to chain a `SetArgPointee()` with a `Return()`. -See this [recipe](CookBook.md#mocking_side_effects) for more details and an example. +See this [recipe](CookBook.md#mocking-side-effects) for more details and an example. ## My question is not in your FAQ! ## @@ -607,7 +607,6 @@ See this [recipe](CookBook.md#mocking_side_effects) for more details and an exam If you cannot find the answer to your question in this FAQ, there are some other resources you can use: - 1. read other [documentation](Documentation.md), 1. search the mailing list [archive](http://groups.google.com/group/googlemock/topics), 1. ask it on [googlemock@googlegroups.com](mailto:googlemock@googlegroups.com) and someone will answer it (to prevent spam, we require you to join the [discussion group](http://groups.google.com/group/googlemock) before you can post.). diff --git a/googlemock/docs/v1_5/CheatSheet.md b/googlemock/docs/v1_5/CheatSheet.md deleted file mode 100644 index 3c7bed4..0000000 --- a/googlemock/docs/v1_5/CheatSheet.md +++ /dev/null @@ -1,525 +0,0 @@ - - -# Defining a Mock Class # - -## Mocking a Normal Class ## - -Given -``` -class Foo { - ... - virtual ~Foo(); - virtual int GetSize() const = 0; - virtual string Describe(const char* name) = 0; - virtual string Describe(int type) = 0; - virtual bool Process(Bar elem, int count) = 0; -}; -``` -(note that `~Foo()` **must** be virtual) we can define its mock as -``` -#include <gmock/gmock.h> - -class MockFoo : public Foo { - MOCK_CONST_METHOD0(GetSize, int()); - MOCK_METHOD1(Describe, string(const char* name)); - MOCK_METHOD1(Describe, string(int type)); - MOCK_METHOD2(Process, bool(Bar elem, int count)); -}; -``` - -To create a "nice" mock object which ignores all uninteresting calls, -or a "strict" mock object, which treats them as failures: -``` -NiceMock<MockFoo> nice_foo; // The type is a subclass of MockFoo. -StrictMock<MockFoo> strict_foo; // The type is a subclass of MockFoo. -``` - -## Mocking a Class Template ## - -To mock -``` -template <typename Elem> -class StackInterface { - public: - ... - virtual ~StackInterface(); - virtual int GetSize() const = 0; - virtual void Push(const Elem& x) = 0; -}; -``` -(note that `~StackInterface()` **must** be virtual) just append `_T` to the `MOCK_*` macros: -``` -template <typename Elem> -class MockStack : public StackInterface<Elem> { - public: - ... - MOCK_CONST_METHOD0_T(GetSize, int()); - MOCK_METHOD1_T(Push, void(const Elem& x)); -}; -``` - -## Specifying Calling Conventions for Mock Functions ## - -If your mock function doesn't use the default calling convention, you -can specify it by appending `_WITH_CALLTYPE` to any of the macros -described in the previous two sections and supplying the calling -convention as the first argument to the macro. For example, -``` - MOCK_METHOD_1_WITH_CALLTYPE(STDMETHODCALLTYPE, Foo, bool(int n)); - MOCK_CONST_METHOD2_WITH_CALLTYPE(STDMETHODCALLTYPE, Bar, int(double x, double y)); -``` -where `STDMETHODCALLTYPE` is defined by `<objbase.h>` on Windows. - -# Using Mocks in Tests # - -The typical flow is: - 1. Import the Google Mock names you need to use. All Google Mock names are in the `testing` namespace unless they are macros or otherwise noted. - 1. Create the mock objects. - 1. Optionally, set the default actions of the mock objects. - 1. Set your expectations on the mock objects (How will they be called? What wil they do?). - 1. Exercise code that uses the mock objects; if necessary, check the result using [Google Test](http://code.google.com/p/googletest/) assertions. - 1. When a mock objects is destructed, Google Mock automatically verifies that all expectations on it have been satisfied. - -Here is an example: -``` -using ::testing::Return; // #1 - -TEST(BarTest, DoesThis) { - MockFoo foo; // #2 - - ON_CALL(foo, GetSize()) // #3 - .WillByDefault(Return(1)); - // ... other default actions ... - - EXPECT_CALL(foo, Describe(5)) // #4 - .Times(3) - .WillRepeatedly(Return("Category 5")); - // ... other expectations ... - - EXPECT_EQ("good", MyProductionFunction(&foo)); // #5 -} // #6 -``` - -# Setting Default Actions # - -Google Mock has a **built-in default action** for any function that -returns `void`, `bool`, a numeric value, or a pointer. - -To customize the default action for functions with return type `T` globally: -``` -using ::testing::DefaultValue; - -DefaultValue<T>::Set(value); // Sets the default value to be returned. -// ... use the mocks ... -DefaultValue<T>::Clear(); // Resets the default value. -``` - -To customize the default action for a particular method, use `ON_CALL()`: -``` -ON_CALL(mock_object, method(matchers)) - .With(multi_argument_matcher) ? - .WillByDefault(action); -``` - -# Setting Expectations # - -`EXPECT_CALL()` sets **expectations** on a mock method (How will it be -called? What will it do?): -``` -EXPECT_CALL(mock_object, method(matchers)) - .With(multi_argument_matcher) ? - .Times(cardinality) ? - .InSequence(sequences) * - .After(expectations) * - .WillOnce(action) * - .WillRepeatedly(action) ? - .RetiresOnSaturation(); ? -``` - -If `Times()` is omitted, the cardinality is assumed to be: - - * `Times(1)` when there is neither `WillOnce()` nor `WillRepeatedly()`; - * `Times(n)` when there are `n WillOnce()`s but no `WillRepeatedly()`, where `n` >= 1; or - * `Times(AtLeast(n))` when there are `n WillOnce()`s and a `WillRepeatedly()`, where `n` >= 0. - -A method with no `EXPECT_CALL()` is free to be invoked _any number of times_, and the default action will be taken each time. - -# Matchers # - -A **matcher** matches a _single_ argument. You can use it inside -`ON_CALL()` or `EXPECT_CALL()`, or use it to validate a value -directly: - -| `EXPECT_THAT(value, matcher)` | Asserts that `value` matches `matcher`. | -|:------------------------------|:----------------------------------------| -| `ASSERT_THAT(value, matcher)` | The same as `EXPECT_THAT(value, matcher)`, except that it generates a **fatal** failure. | - -Built-in matchers (where `argument` is the function argument) are -divided into several categories: - -## Wildcard ## -|`_`|`argument` can be any value of the correct type.| -|:--|:-----------------------------------------------| -|`A<type>()` or `An<type>()`|`argument` can be any value of type `type`. | - -## Generic Comparison ## - -|`Eq(value)` or `value`|`argument == value`| -|:---------------------|:------------------| -|`Ge(value)` |`argument >= value`| -|`Gt(value)` |`argument > value` | -|`Le(value)` |`argument <= value`| -|`Lt(value)` |`argument < value` | -|`Ne(value)` |`argument != value`| -|`IsNull()` |`argument` is a `NULL` pointer (raw or smart).| -|`NotNull()` |`argument` is a non-null pointer (raw or smart).| -|`Ref(variable)` |`argument` is a reference to `variable`.| -|`TypedEq<type>(value)`|`argument` has type `type` and is equal to `value`. You may need to use this instead of `Eq(value)` when the mock function is overloaded.| - -Except `Ref()`, these matchers make a _copy_ of `value` in case it's -modified or destructed later. If the compiler complains that `value` -doesn't have a public copy constructor, try wrap it in `ByRef()`, -e.g. `Eq(ByRef(non_copyable_value))`. If you do that, make sure -`non_copyable_value` is not changed afterwards, or the meaning of your -matcher will be changed. - -## Floating-Point Matchers ## - -|`DoubleEq(a_double)`|`argument` is a `double` value approximately equal to `a_double`, treating two NaNs as unequal.| -|:-------------------|:----------------------------------------------------------------------------------------------| -|`FloatEq(a_float)` |`argument` is a `float` value approximately equal to `a_float`, treating two NaNs as unequal. | -|`NanSensitiveDoubleEq(a_double)`|`argument` is a `double` value approximately equal to `a_double`, treating two NaNs as equal. | -|`NanSensitiveFloatEq(a_float)`|`argument` is a `float` value approximately equal to `a_float`, treating two NaNs as equal. | - -The above matchers use ULP-based comparison (the same as used in -[Google Test](http://code.google.com/p/googletest/)). They -automatically pick a reasonable error bound based on the absolute -value of the expected value. `DoubleEq()` and `FloatEq()` conform to -the IEEE standard, which requires comparing two NaNs for equality to -return false. The `NanSensitive*` version instead treats two NaNs as -equal, which is often what a user wants. - -## String Matchers ## - -The `argument` can be either a C string or a C++ string object: - -|`ContainsRegex(string)`|`argument` matches the given regular expression.| -|:----------------------|:-----------------------------------------------| -|`EndsWith(suffix)` |`argument` ends with string `suffix`. | -|`HasSubstr(string)` |`argument` contains `string` as a sub-string. | -|`MatchesRegex(string)` |`argument` matches the given regular expression with the match starting at the first character and ending at the last character.| -|`StartsWith(prefix)` |`argument` starts with string `prefix`. | -|`StrCaseEq(string)` |`argument` is equal to `string`, ignoring case. | -|`StrCaseNe(string)` |`argument` is not equal to `string`, ignoring case.| -|`StrEq(string)` |`argument` is equal to `string`. | -|`StrNe(string)` |`argument` is not equal to `string`. | - -`StrCaseEq()`, `StrCaseNe()`, `StrEq()`, and `StrNe()` work for wide -strings as well. - -## Container Matchers ## - -Most STL-style containers support `==`, so you can use -`Eq(expected_container)` or simply `expected_container` to match a -container exactly. If you want to write the elements in-line, -match them more flexibly, or get more informative messages, you can use: - -| `Contains(e)` | `argument` contains an element that matches `e`, which can be either a value or a matcher. | -|:--------------|:-------------------------------------------------------------------------------------------| -|`ElementsAre(e0, e1, ..., en)`|`argument` has `n + 1` elements, where the i-th element matches `ei`, which can be a value or a matcher. 0 to 10 arguments are allowed.| -|`ElementsAreArray(array)` or `ElementsAreArray(array, count)`|The same as `ElementsAre()` except that the expected element values/matchers come from a C-style array.| -| `ContainerEq(container)` | The same as `Eq(container)` except that the failure message also includes which elements are in one container but not the other. | - -These matchers can also match: - - 1. a native array passed by reference (e.g. in `Foo(const int (&a)[5])`), and - 1. an array passed as a pointer and a count (e.g. in `Bar(const T* buffer, int len)` -- see [Multi-argument Matchers](#Multiargument_Matchers.md)). - -where the array may be multi-dimensional (i.e. its elements can be arrays). - -## Member Matchers ## - -|`Field(&class::field, m)`|`argument.field` (or `argument->field` when `argument` is a plain pointer) matches matcher `m`, where `argument` is an object of type _class_.| -|:------------------------|:---------------------------------------------------------------------------------------------------------------------------------------------| -|`Key(e)` |`argument.first` matches `e`, which can be either a value or a matcher. E.g. `Contains(Key(Le(5)))` can verify that a `map` contains a key `<= 5`.| -|`Pair(m1, m2)` |`argument` is an `std::pair` whose `first` field matches `m1` and `second` field matches `m2`. | -|`Property(&class::property, m)`|`argument.property()` (or `argument->property()` when `argument` is a plain pointer) matches matcher `m`, where `argument` is an object of type _class_.| - -## Matching the Result of a Function or Functor ## - -|`ResultOf(f, m)`|`f(argument)` matches matcher `m`, where `f` is a function or functor.| -|:---------------|:---------------------------------------------------------------------| - -## Pointer Matchers ## - -|`Pointee(m)`|`argument` (either a smart pointer or a raw pointer) points to a value that matches matcher `m`.| -|:-----------|:-----------------------------------------------------------------------------------------------| - -## Multiargument Matchers ## - -These are matchers on tuple types. They can be used in -`.With()`. The following can be used on functions with <i>two<br> -arguments</i> `x` and `y`: - -|`Eq()`|`x == y`| -|:-----|:-------| -|`Ge()`|`x >= y`| -|`Gt()`|`x > y` | -|`Le()`|`x <= y`| -|`Lt()`|`x < y` | -|`Ne()`|`x != y`| - -You can use the following selectors to pick a subset of the arguments -(or reorder them) to participate in the matching: - -|`AllArgs(m)`|Equivalent to `m`. Useful as syntactic sugar in `.With(AllArgs(m))`.| -|:-----------|:-------------------------------------------------------------------| -|`Args<N1, N2, ..., Nk>(m)`|The `k` selected (using 0-based indices) arguments match `m`, e.g. `Args<1, 2>(Contains(5))`.| - -## Composite Matchers ## - -You can make a matcher from one or more other matchers: - -|`AllOf(m1, m2, ..., mn)`|`argument` matches all of the matchers `m1` to `mn`.| -|:-----------------------|:---------------------------------------------------| -|`AnyOf(m1, m2, ..., mn)`|`argument` matches at least one of the matchers `m1` to `mn`.| -|`Not(m)` |`argument` doesn't match matcher `m`. | - -## Adapters for Matchers ## - -|`MatcherCast<T>(m)`|casts matcher `m` to type `Matcher<T>`.| -|:------------------|:--------------------------------------| -|`SafeMatcherCast<T>(m)`| [safely casts](V1_5_CookBook#Casting_Matchers.md) matcher `m` to type `Matcher<T>`. | -|`Truly(predicate)` |`predicate(argument)` returns something considered by C++ to be true, where `predicate` is a function or functor.| - -## Matchers as Predicates ## - -|`Matches(m)`|a unary functor that returns `true` if the argument matches `m`.| -|:-----------|:---------------------------------------------------------------| -|`ExplainMatchResult(m, value, result_listener)`|returns `true` if `value` matches `m`, explaining the result to `result_listener`.| -|`Value(x, m)`|returns `true` if the value of `x` matches `m`. | - -## Defining Matchers ## - -| `MATCHER(IsEven, "") { return (arg % 2) == 0; }` | Defines a matcher `IsEven()` to match an even number. | -|:-------------------------------------------------|:------------------------------------------------------| -| `MATCHER_P(IsDivisibleBy, n, "") { *result_listener << "where the remainder is " << (arg % n); return (arg % n) == 0; }` | Defines a macher `IsDivisibleBy(n)` to match a number divisible by `n`. | -| `MATCHER_P2(IsBetween, a, b, "is between %(a)s and %(b)s") { return a <= arg && arg <= b; }` | Defines a matcher `IsBetween(a, b)` to match a value in the range [`a`, `b`]. | - -**Notes:** - - 1. The `MATCHER*` macros cannot be used inside a function or class. - 1. The matcher body must be _purely functional_ (i.e. it cannot have any side effect, and the result must not depend on anything other than the value being matched and the matcher parameters). - 1. You can use `PrintToString(x)` to convert a value `x` of any type to a string. - -## Matchers as Test Assertions ## - -|`ASSERT_THAT(expression, m)`|Generates a [fatal failure](http://code.google.com/p/googletest/wiki/GoogleTestPrimer#Assertions) if the value of `expression` doesn't match matcher `m`.| -|:---------------------------|:--------------------------------------------------------------------------------------------------------------------------------------------------------| -|`EXPECT_THAT(expression, m)`|Generates a non-fatal failure if the value of `expression` doesn't match matcher `m`. | - -# Actions # - -**Actions** specify what a mock function should do when invoked. - -## Returning a Value ## - -|`Return()`|Return from a `void` mock function.| -|:---------|:----------------------------------| -|`Return(value)`|Return `value`. | -|`ReturnArg<N>()`|Return the `N`-th (0-based) argument.| -|`ReturnNew<T>(a1, ..., ak)`|Return `new T(a1, ..., ak)`; a different object is created each time.| -|`ReturnNull()`|Return a null pointer. | -|`ReturnRef(variable)`|Return a reference to `variable`. | - -## Side Effects ## - -|`Assign(&variable, value)`|Assign `value` to variable.| -|:-------------------------|:--------------------------| -| `DeleteArg<N>()` | Delete the `N`-th (0-based) argument, which must be a pointer. | -| `SaveArg<N>(pointer)` | Save the `N`-th (0-based) argument to `*pointer`. | -| `SetArgReferee<N>(value)` | Assign value to the variable referenced by the `N`-th (0-based) argument. | -|`SetArgumentPointee<N>(value)`|Assign `value` to the variable pointed by the `N`-th (0-based) argument.| -|`SetArrayArgument<N>(first, last)`|Copies the elements in source range [`first`, `last`) to the array pointed to by the `N`-th (0-based) argument, which can be either a pointer or an iterator. The action does not take ownership of the elements in the source range.| -|`SetErrnoAndReturn(error, value)`|Set `errno` to `error` and return `value`.| -|`Throw(exception)` |Throws the given exception, which can be any copyable value. Available since v1.1.0.| - -## Using a Function or a Functor as an Action ## - -|`Invoke(f)`|Invoke `f` with the arguments passed to the mock function, where `f` can be a global/static function or a functor.| -|:----------|:-----------------------------------------------------------------------------------------------------------------| -|`Invoke(object_pointer, &class::method)`|Invoke the {method on the object with the arguments passed to the mock function. | -|`InvokeWithoutArgs(f)`|Invoke `f`, which can be a global/static function or a functor. `f` must take no arguments. | -|`InvokeWithoutArgs(object_pointer, &class::method)`|Invoke the method on the object, which takes no arguments. | -|`InvokeArgument<N>(arg1, arg2, ..., argk)`|Invoke the mock function's `N`-th (0-based) argument, which must be a function or a functor, with the `k` arguments.| - -The return value of the invoked function is used as the return value -of the action. - -When defining a function or functor to be used with `Invoke*()`, you can declare any unused parameters as `Unused`: -``` - double Distance(Unused, double x, double y) { return sqrt(x*x + y*y); } - ... - EXPECT_CALL(mock, Foo("Hi", _, _)).WillOnce(Invoke(Distance)); -``` - -In `InvokeArgument<N>(...)`, if an argument needs to be passed by reference, wrap it inside `ByRef()`. For example, -``` - InvokeArgument<2>(5, string("Hi"), ByRef(foo)) -``` -calls the mock function's #2 argument, passing to it `5` and `string("Hi")` by value, and `foo` by reference. - -## Default Action ## - -|`DoDefault()`|Do the default action (specified by `ON_CALL()` or the built-in one).| -|:------------|:--------------------------------------------------------------------| - -**Note:** due to technical reasons, `DoDefault()` cannot be used inside a composite action - trying to do so will result in a run-time error. - -## Composite Actions ## - -|`DoAll(a1, a2, ..., an)`|Do all actions `a1` to `an` and return the result of `an` in each invocation. The first `n - 1` sub-actions must return void. | -|:-----------------------|:-----------------------------------------------------------------------------------------------------------------------------| -|`IgnoreResult(a)` |Perform action `a` and ignore its result. `a` must not return void. | -|`WithArg<N>(a)` |Pass the `N`-th (0-based) argument of the mock function to action `a` and perform it. | -|`WithArgs<N1, N2, ..., Nk>(a)`|Pass the selected (0-based) arguments of the mock function to action `a` and perform it. | -|`WithoutArgs(a)` |Perform action `a` without any arguments. | - -## Defining Actions ## - -| `ACTION(Sum) { return arg0 + arg1; }` | Defines an action `Sum()` to return the sum of the mock function's argument #0 and #1. | -|:--------------------------------------|:---------------------------------------------------------------------------------------| -| `ACTION_P(Plus, n) { return arg0 + n; }` | Defines an action `Plus(n)` to return the sum of the mock function's argument #0 and `n`. | -| `ACTION_Pk(Foo, p1, ..., pk) { statements; }` | Defines a parameterized action `Foo(p1, ..., pk)` to execute the given `statements`. | - -The `ACTION*` macros cannot be used inside a function or class. - -# Cardinalities # - -These are used in `Times()` to specify how many times a mock function will be called: - -|`AnyNumber()`|The function can be called any number of times.| -|:------------|:----------------------------------------------| -|`AtLeast(n)` |The call is expected at least `n` times. | -|`AtMost(n)` |The call is expected at most `n` times. | -|`Between(m, n)`|The call is expected between `m` and `n` (inclusive) times.| -|`Exactly(n) or n`|The call is expected exactly `n` times. In particular, the call should never happen when `n` is 0.| - -# Expectation Order # - -By default, the expectations can be matched in _any_ order. If some -or all expectations must be matched in a given order, there are two -ways to specify it. They can be used either independently or -together. - -## The After Clause ## - -``` -using ::testing::Expectation; -... -Expectation init_x = EXPECT_CALL(foo, InitX()); -Expectation init_y = EXPECT_CALL(foo, InitY()); -EXPECT_CALL(foo, Bar()) - .After(init_x, init_y); -``` -says that `Bar()` can be called only after both `InitX()` and -`InitY()` have been called. - -If you don't know how many pre-requisites an expectation has when you -write it, you can use an `ExpectationSet` to collect them: - -``` -using ::testing::ExpectationSet; -... -ExpectationSet all_inits; -for (int i = 0; i < element_count; i++) { - all_inits += EXPECT_CALL(foo, InitElement(i)); -} -EXPECT_CALL(foo, Bar()) - .After(all_inits); -``` -says that `Bar()` can be called only after all elements have been -initialized (but we don't care about which elements get initialized -before the others). - -Modifying an `ExpectationSet` after using it in an `.After()` doesn't -affect the meaning of the `.After()`. - -## Sequences ## - -When you have a long chain of sequential expectations, it's easier to -specify the order using **sequences**, which don't require you to given -each expectation in the chain a different name. <i>All expected<br> -calls</i> in the same sequence must occur in the order they are -specified. - -``` -using ::testing::Sequence; -Sequence s1, s2; -... -EXPECT_CALL(foo, Reset()) - .InSequence(s1, s2) - .WillOnce(Return(true)); -EXPECT_CALL(foo, GetSize()) - .InSequence(s1) - .WillOnce(Return(1)); -EXPECT_CALL(foo, Describe(A<const char*>())) - .InSequence(s2) - .WillOnce(Return("dummy")); -``` -says that `Reset()` must be called before _both_ `GetSize()` _and_ -`Describe()`, and the latter two can occur in any order. - -To put many expectations in a sequence conveniently: -``` -using ::testing::InSequence; -{ - InSequence dummy; - - EXPECT_CALL(...)...; - EXPECT_CALL(...)...; - ... - EXPECT_CALL(...)...; -} -``` -says that all expected calls in the scope of `dummy` must occur in -strict order. The name `dummy` is irrelevant.) - -# Verifying and Resetting a Mock # - -Google Mock will verify the expectations on a mock object when it is destructed, or you can do it earlier: -``` -using ::testing::Mock; -... -// Verifies and removes the expectations on mock_obj; -// returns true iff successful. -Mock::VerifyAndClearExpectations(&mock_obj); -... -// Verifies and removes the expectations on mock_obj; -// also removes the default actions set by ON_CALL(); -// returns true iff successful. -Mock::VerifyAndClear(&mock_obj); -``` - -You can also tell Google Mock that a mock object can be leaked and doesn't -need to be verified: -``` -Mock::AllowLeak(&mock_obj); -``` - -# Mock Classes # - -Google Mock defines a convenient mock class template -``` -class MockFunction<R(A1, ..., An)> { - public: - MOCK_METHODn(Call, R(A1, ..., An)); -}; -``` -See this [recipe](V1_5_CookBook#Using_Check_Points.md) for one application of it. - -# Flags # - -| `--gmock_catch_leaked_mocks=0` | Don't report leaked mock objects as failures. | -|:-------------------------------|:----------------------------------------------| -| `--gmock_verbose=LEVEL` | Sets the default verbosity level (`info`, `warning`, or `error`) of Google Mock messages. |
\ No newline at end of file diff --git a/googlemock/docs/v1_5/CookBook.md b/googlemock/docs/v1_5/CookBook.md deleted file mode 100644 index 26e153c..0000000 --- a/googlemock/docs/v1_5/CookBook.md +++ /dev/null @@ -1,3250 +0,0 @@ - - -You can find recipes for using Google Mock here. If you haven't yet, -please read the [ForDummies](V1_5_ForDummies.md) document first to make sure you understand -the basics. - -**Note:** Google Mock lives in the `testing` name space. For -readability, it is recommended to write `using ::testing::Foo;` once in -your file before using the name `Foo` defined by Google Mock. We omit -such `using` statements in this page for brevity, but you should do it -in your own code. - -# Creating Mock Classes # - -## Mocking Private or Protected Methods ## - -You must always put a mock method definition (`MOCK_METHOD*`) in a -`public:` section of the mock class, regardless of the method being -mocked being `public`, `protected`, or `private` in the base class. -This allows `ON_CALL` and `EXPECT_CALL` to reference the mock function -from outside of the mock class. (Yes, C++ allows a subclass to change -the access level of a virtual function in the base class.) Example: - -``` -class Foo { - public: - ... - virtual bool Transform(Gadget* g) = 0; - - protected: - virtual void Resume(); - - private: - virtual int GetTimeOut(); -}; - -class MockFoo : public Foo { - public: - ... - MOCK_METHOD1(Transform, bool(Gadget* g)); - - // The following must be in the public section, even though the - // methods are protected or private in the base class. - MOCK_METHOD0(Resume, void()); - MOCK_METHOD0(GetTimeOut, int()); -}; -``` - -## Mocking Overloaded Methods ## - -You can mock overloaded functions as usual. No special attention is required: - -``` -class Foo { - ... - - // Must be virtual as we'll inherit from Foo. - virtual ~Foo(); - - // Overloaded on the types and/or numbers of arguments. - virtual int Add(Element x); - virtual int Add(int times, Element x); - - // Overloaded on the const-ness of this object. - virtual Bar& GetBar(); - virtual const Bar& GetBar() const; -}; - -class MockFoo : public Foo { - ... - MOCK_METHOD1(Add, int(Element x)); - MOCK_METHOD2(Add, int(int times, Element x); - - MOCK_METHOD0(GetBar, Bar&()); - MOCK_CONST_METHOD0(GetBar, const Bar&()); -}; -``` - -**Note:** if you don't mock all versions of the overloaded method, the -compiler will give you a warning about some methods in the base class -being hidden. To fix that, use `using` to bring them in scope: - -``` -class MockFoo : public Foo { - ... - using Foo::Add; - MOCK_METHOD1(Add, int(Element x)); - // We don't want to mock int Add(int times, Element x); - ... -}; -``` - -## Mocking Class Templates ## - -To mock a class template, append `_T` to the `MOCK_*` macros: - -``` -template <typename Elem> -class StackInterface { - ... - // Must be virtual as we'll inherit from StackInterface. - virtual ~StackInterface(); - - virtual int GetSize() const = 0; - virtual void Push(const Elem& x) = 0; -}; - -template <typename Elem> -class MockStack : public StackInterface<Elem> { - ... - MOCK_CONST_METHOD0_T(GetSize, int()); - MOCK_METHOD1_T(Push, void(const Elem& x)); -}; -``` - -## Mocking Nonvirtual Methods ## - -Google Mock can mock non-virtual functions to be used in what we call _hi-perf -dependency injection_. - -In this case, instead of sharing a common base class with the real -class, your mock class will be _unrelated_ to the real class, but -contain methods with the same signatures. The syntax for mocking -non-virtual methods is the _same_ as mocking virtual methods: - -``` -// A simple packet stream class. None of its members is virtual. -class ConcretePacketStream { - public: - void AppendPacket(Packet* new_packet); - const Packet* GetPacket(size_t packet_number) const; - size_t NumberOfPackets() const; - ... -}; - -// A mock packet stream class. It inherits from no other, but defines -// GetPacket() and NumberOfPackets(). -class MockPacketStream { - public: - MOCK_CONST_METHOD1(GetPacket, const Packet*(size_t packet_number)); - MOCK_CONST_METHOD0(NumberOfPackets, size_t()); - ... -}; -``` - -Note that the mock class doesn't define `AppendPacket()`, unlike the -real class. That's fine as long as the test doesn't need to call it. - -Next, you need a way to say that you want to use -`ConcretePacketStream` in production code, and use `MockPacketStream` -in tests. Since the functions are not virtual and the two classes are -unrelated, you must specify your choice at _compile time_ (as opposed -to run time). - -One way to do it is to templatize your code that needs to use a packet -stream. More specifically, you will give your code a template type -argument for the type of the packet stream. In production, you will -instantiate your template with `ConcretePacketStream` as the type -argument. In tests, you will instantiate the same template with -`MockPacketStream`. For example, you may write: - -``` -template <class PacketStream> -void CreateConnection(PacketStream* stream) { ... } - -template <class PacketStream> -class PacketReader { - public: - void ReadPackets(PacketStream* stream, size_t packet_num); -}; -``` - -Then you can use `CreateConnection<ConcretePacketStream>()` and -`PacketReader<ConcretePacketStream>` in production code, and use -`CreateConnection<MockPacketStream>()` and -`PacketReader<MockPacketStream>` in tests. - -``` - MockPacketStream mock_stream; - EXPECT_CALL(mock_stream, ...)...; - .. set more expectations on mock_stream ... - PacketReader<MockPacketStream> reader(&mock_stream); - ... exercise reader ... -``` - -## Mocking Free Functions ## - -It's possible to use Google Mock to mock a free function (i.e. a -C-style function or a static method). You just need to rewrite your -code to use an interface (abstract class). - -Instead of calling a free function (say, `OpenFile`) directly, -introduce an interface for it and have a concrete subclass that calls -the free function: - -``` -class FileInterface { - public: - ... - virtual bool Open(const char* path, const char* mode) = 0; -}; - -class File : public FileInterface { - public: - ... - virtual bool Open(const char* path, const char* mode) { - return OpenFile(path, mode); - } -}; -``` - -Your code should talk to `FileInterface` to open a file. Now it's -easy to mock out the function. - -This may seem much hassle, but in practice you often have multiple -related functions that you can put in the same interface, so the -per-function syntactic overhead will be much lower. - -If you are concerned about the performance overhead incurred by -virtual functions, and profiling confirms your concern, you can -combine this with the recipe for [mocking non-virtual methods](#Mocking_Nonvirtual_Methods.md). - -## Nice Mocks and Strict Mocks ## - -If a mock method has no `EXPECT_CALL` spec but is called, Google Mock -will print a warning about the "uninteresting call". The rationale is: - - * New methods may be added to an interface after a test is written. We shouldn't fail a test just because a method it doesn't know about is called. - * However, this may also mean there's a bug in the test, so Google Mock shouldn't be silent either. If the user believes these calls are harmless, he can add an `EXPECT_CALL()` to suppress the warning. - -However, sometimes you may want to suppress all "uninteresting call" -warnings, while sometimes you may want the opposite, i.e. to treat all -of them as errors. Google Mock lets you make the decision on a -per-mock-object basis. - -Suppose your test uses a mock class `MockFoo`: - -``` -TEST(...) { - MockFoo mock_foo; - EXPECT_CALL(mock_foo, DoThis()); - ... code that uses mock_foo ... -} -``` - -If a method of `mock_foo` other than `DoThis()` is called, it will be -reported by Google Mock as a warning. However, if you rewrite your -test to use `NiceMock<MockFoo>` instead, the warning will be gone, -resulting in a cleaner test output: - -``` -using ::testing::NiceMock; - -TEST(...) { - NiceMock<MockFoo> mock_foo; - EXPECT_CALL(mock_foo, DoThis()); - ... code that uses mock_foo ... -} -``` - -`NiceMock<MockFoo>` is a subclass of `MockFoo`, so it can be used -wherever `MockFoo` is accepted. - -It also works if `MockFoo`'s constructor takes some arguments, as -`NiceMock<MockFoo>` "inherits" `MockFoo`'s constructors: - -``` -using ::testing::NiceMock; - -TEST(...) { - NiceMock<MockFoo> mock_foo(5, "hi"); // Calls MockFoo(5, "hi"). - EXPECT_CALL(mock_foo, DoThis()); - ... code that uses mock_foo ... -} -``` - -The usage of `StrictMock` is similar, except that it makes all -uninteresting calls failures: - -``` -using ::testing::StrictMock; - -TEST(...) { - StrictMock<MockFoo> mock_foo; - EXPECT_CALL(mock_foo, DoThis()); - ... code that uses mock_foo ... - - // The test will fail if a method of mock_foo other than DoThis() - // is called. -} -``` - -There are some caveats though (I don't like them just as much as the -next guy, but sadly they are side effects of C++'s limitations): - - 1. `NiceMock<MockFoo>` and `StrictMock<MockFoo>` only work for mock methods defined using the `MOCK_METHOD*` family of macros **directly** in the `MockFoo` class. If a mock method is defined in a **base class** of `MockFoo`, the "nice" or "strict" modifier may not affect it, depending on the compiler. In particular, nesting `NiceMock` and `StrictMock` (e.g. `NiceMock<StrictMock<MockFoo> >`) is **not** supported. - 1. The constructors of the base mock (`MockFoo`) cannot have arguments passed by non-const reference, which happens to be banned by the [Google C++ style guide](http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml). - 1. During the constructor or destructor of `MockFoo`, the mock object is _not_ nice or strict. This may cause surprises if the constructor or destructor calls a mock method on `this` object. (This behavior, however, is consistent with C++'s general rule: if a constructor or destructor calls a virtual method of `this` object, that method is treated as non-virtual. In other words, to the base class's constructor or destructor, `this` object behaves like an instance of the base class, not the derived class. This rule is required for safety. Otherwise a base constructor may use members of a derived class before they are initialized, or a base destructor may use members of a derived class after they have been destroyed.) - -Finally, you should be **very cautious** when using this feature, as the -decision you make applies to **all** future changes to the mock -class. If an important change is made in the interface you are mocking -(and thus in the mock class), it could break your tests (if you use -`StrictMock`) or let bugs pass through without a warning (if you use -`NiceMock`). Therefore, try to specify the mock's behavior using -explicit `EXPECT_CALL` first, and only turn to `NiceMock` or -`StrictMock` as the last resort. - -## Simplifying the Interface without Breaking Existing Code ## - -Sometimes a method has a long list of arguments that is mostly -uninteresting. For example, - -``` -class LogSink { - public: - ... - virtual void send(LogSeverity severity, const char* full_filename, - const char* base_filename, int line, - const struct tm* tm_time, - const char* message, size_t message_len) = 0; -}; -``` - -This method's argument list is lengthy and hard to work with (let's -say that the `message` argument is not even 0-terminated). If we mock -it as is, using the mock will be awkward. If, however, we try to -simplify this interface, we'll need to fix all clients depending on -it, which is often infeasible. - -The trick is to re-dispatch the method in the mock class: - -``` -class ScopedMockLog : public LogSink { - public: - ... - virtual void send(LogSeverity severity, const char* full_filename, - const char* base_filename, int line, const tm* tm_time, - const char* message, size_t message_len) { - // We are only interested in the log severity, full file name, and - // log message. - Log(severity, full_filename, std::string(message, message_len)); - } - - // Implements the mock method: - // - // void Log(LogSeverity severity, - // const string& file_path, - // const string& message); - MOCK_METHOD3(Log, void(LogSeverity severity, const string& file_path, - const string& message)); -}; -``` - -By defining a new mock method with a trimmed argument list, we make -the mock class much more user-friendly. - -## Alternative to Mocking Concrete Classes ## - -Often you may find yourself using classes that don't implement -interfaces. In order to test your code that uses such a class (let's -call it `Concrete`), you may be tempted to make the methods of -`Concrete` virtual and then mock it. - -Try not to do that. - -Making a non-virtual function virtual is a big decision. It creates an -extension point where subclasses can tweak your class' behavior. This -weakens your control on the class because now it's harder to maintain -the class' invariants. You should make a function virtual only when -there is a valid reason for a subclass to override it. - -Mocking concrete classes directly is problematic as it creates a tight -coupling between the class and the tests - any small change in the -class may invalidate your tests and make test maintenance a pain. - -To avoid such problems, many programmers have been practicing "coding -to interfaces": instead of talking to the `Concrete` class, your code -would define an interface and talk to it. Then you implement that -interface as an adaptor on top of `Concrete`. In tests, you can easily -mock that interface to observe how your code is doing. - -This technique incurs some overhead: - - * You pay the cost of virtual function calls (usually not a problem). - * There is more abstraction for the programmers to learn. - -However, it can also bring significant benefits in addition to better -testability: - - * `Concrete`'s API may not fit your problem domain very well, as you may not be the only client it tries to serve. By designing your own interface, you have a chance to tailor it to your need - you may add higher-level functionalities, rename stuff, etc instead of just trimming the class. This allows you to write your code (user of the interface) in a more natural way, which means it will be more readable, more maintainable, and you'll be more productive. - * If `Concrete`'s implementation ever has to change, you don't have to rewrite everywhere it is used. Instead, you can absorb the change in your implementation of the interface, and your other code and tests will be insulated from this change. - -Some people worry that if everyone is practicing this technique, they -will end up writing lots of redundant code. This concern is totally -understandable. However, there are two reasons why it may not be the -case: - - * Different projects may need to use `Concrete` in different ways, so the best interfaces for them will be different. Therefore, each of them will have its own domain-specific interface on top of `Concrete`, and they will not be the same code. - * If enough projects want to use the same interface, they can always share it, just like they have been sharing `Concrete`. You can check in the interface and the adaptor somewhere near `Concrete` (perhaps in a `contrib` sub-directory) and let many projects use it. - -You need to weigh the pros and cons carefully for your particular -problem, but I'd like to assure you that the Java community has been -practicing this for a long time and it's a proven effective technique -applicable in a wide variety of situations. :-) - -## Delegating Calls to a Fake ## - -Some times you have a non-trivial fake implementation of an -interface. For example: - -``` -class Foo { - public: - virtual ~Foo() {} - virtual char DoThis(int n) = 0; - virtual void DoThat(const char* s, int* p) = 0; -}; - -class FakeFoo : public Foo { - public: - virtual char DoThis(int n) { - return (n > 0) ? '+' : - (n < 0) ? '-' : '0'; - } - - virtual void DoThat(const char* s, int* p) { - *p = strlen(s); - } -}; -``` - -Now you want to mock this interface such that you can set expectations -on it. However, you also want to use `FakeFoo` for the default -behavior, as duplicating it in the mock object is, well, a lot of -work. - -When you define the mock class using Google Mock, you can have it -delegate its default action to a fake class you already have, using -this pattern: - -``` -using ::testing::_; -using ::testing::Invoke; - -class MockFoo : public Foo { - public: - // Normal mock method definitions using Google Mock. - MOCK_METHOD1(DoThis, char(int n)); - MOCK_METHOD2(DoThat, void(const char* s, int* p)); - - // Delegates the default actions of the methods to a FakeFoo object. - // This must be called *before* the custom ON_CALL() statements. - void DelegateToFake() { - ON_CALL(*this, DoThis(_)) - .WillByDefault(Invoke(&fake_, &FakeFoo::DoThis)); - ON_CALL(*this, DoThat(_, _)) - .WillByDefault(Invoke(&fake_, &FakeFoo::DoThat)); - } - private: - FakeFoo fake_; // Keeps an instance of the fake in the mock. -}; -``` - -With that, you can use `MockFoo` in your tests as usual. Just remember -that if you don't explicitly set an action in an `ON_CALL()` or -`EXPECT_CALL()`, the fake will be called upon to do it: - -``` -using ::testing::_; - -TEST(AbcTest, Xyz) { - MockFoo foo; - foo.DelegateToFake(); // Enables the fake for delegation. - - // Put your ON_CALL(foo, ...)s here, if any. - - // No action specified, meaning to use the default action. - EXPECT_CALL(foo, DoThis(5)); - EXPECT_CALL(foo, DoThat(_, _)); - - int n = 0; - EXPECT_EQ('+', foo.DoThis(5)); // FakeFoo::DoThis() is invoked. - foo.DoThat("Hi", &n); // FakeFoo::DoThat() is invoked. - EXPECT_EQ(2, n); -} -``` - -**Some tips:** - - * If you want, you can still override the default action by providing your own `ON_CALL()` or using `.WillOnce()` / `.WillRepeatedly()` in `EXPECT_CALL()`. - * In `DelegateToFake()`, you only need to delegate the methods whose fake implementation you intend to use. - * The general technique discussed here works for overloaded methods, but you'll need to tell the compiler which version you mean. To disambiguate a mock function (the one you specify inside the parentheses of `ON_CALL()`), see the "Selecting Between Overloaded Functions" section on this page; to disambiguate a fake function (the one you place inside `Invoke()`), use a `static_cast` to specify the function's type. - * Having to mix a mock and a fake is often a sign of something gone wrong. Perhaps you haven't got used to the interaction-based way of testing yet. Or perhaps your interface is taking on too many roles and should be split up. Therefore, **don't abuse this**. We would only recommend to do it as an intermediate step when you are refactoring your code. - -Regarding the tip on mixing a mock and a fake, here's an example on -why it may be a bad sign: Suppose you have a class `System` for -low-level system operations. In particular, it does file and I/O -operations. And suppose you want to test how your code uses `System` -to do I/O, and you just want the file operations to work normally. If -you mock out the entire `System` class, you'll have to provide a fake -implementation for the file operation part, which suggests that -`System` is taking on too many roles. - -Instead, you can define a `FileOps` interface and an `IOOps` interface -and split `System`'s functionalities into the two. Then you can mock -`IOOps` without mocking `FileOps`. - -## Delegating Calls to a Real Object ## - -When using testing doubles (mocks, fakes, stubs, and etc), sometimes -their behaviors will differ from those of the real objects. This -difference could be either intentional (as in simulating an error such -that you can test the error handling code) or unintentional. If your -mocks have different behaviors than the real objects by mistake, you -could end up with code that passes the tests but fails in production. - -You can use the _delegating-to-real_ technique to ensure that your -mock has the same behavior as the real object while retaining the -ability to validate calls. This technique is very similar to the -delegating-to-fake technique, the difference being that we use a real -object instead of a fake. Here's an example: - -``` -using ::testing::_; -using ::testing::AtLeast; -using ::testing::Invoke; - -class MockFoo : public Foo { - public: - MockFoo() { - // By default, all calls are delegated to the real object. - ON_CALL(*this, DoThis()) - .WillByDefault(Invoke(&real_, &Foo::DoThis)); - ON_CALL(*this, DoThat(_)) - .WillByDefault(Invoke(&real_, &Foo::DoThat)); - ... - } - MOCK_METHOD0(DoThis, ...); - MOCK_METHOD1(DoThat, ...); - ... - private: - Foo real_; -}; -... - - MockFoo mock; - - EXPECT_CALL(mock, DoThis()) - .Times(3); - EXPECT_CALL(mock, DoThat("Hi")) - .Times(AtLeast(1)); - ... use mock in test ... -``` - -With this, Google Mock will verify that your code made the right calls -(with the right arguments, in the right order, called the right number -of times, etc), and a real object will answer the calls (so the -behavior will be the same as in production). This gives you the best -of both worlds. - -## Delegating Calls to a Parent Class ## - -Ideally, you should code to interfaces, whose methods are all pure -virtual. In reality, sometimes you do need to mock a virtual method -that is not pure (i.e, it already has an implementation). For example: - -``` -class Foo { - public: - virtual ~Foo(); - - virtual void Pure(int n) = 0; - virtual int Concrete(const char* str) { ... } -}; - -class MockFoo : public Foo { - public: - // Mocking a pure method. - MOCK_METHOD1(Pure, void(int n)); - // Mocking a concrete method. Foo::Concrete() is shadowed. - MOCK_METHOD1(Concrete, int(const char* str)); -}; -``` - -Sometimes you may want to call `Foo::Concrete()` instead of -`MockFoo::Concrete()`. Perhaps you want to do it as part of a stub -action, or perhaps your test doesn't need to mock `Concrete()` at all -(but it would be oh-so painful to have to define a new mock class -whenever you don't need to mock one of its methods). - -The trick is to leave a back door in your mock class for accessing the -real methods in the base class: - -``` -class MockFoo : public Foo { - public: - // Mocking a pure method. - MOCK_METHOD1(Pure, void(int n)); - // Mocking a concrete method. Foo::Concrete() is shadowed. - MOCK_METHOD1(Concrete, int(const char* str)); - - // Use this to call Concrete() defined in Foo. - int FooConcrete(const char* str) { return Foo::Concrete(str); } -}; -``` - -Now, you can call `Foo::Concrete()` inside an action by: - -``` -using ::testing::_; -using ::testing::Invoke; -... - EXPECT_CALL(foo, Concrete(_)) - .WillOnce(Invoke(&foo, &MockFoo::FooConcrete)); -``` - -or tell the mock object that you don't want to mock `Concrete()`: - -``` -using ::testing::Invoke; -... - ON_CALL(foo, Concrete(_)) - .WillByDefault(Invoke(&foo, &MockFoo::FooConcrete)); -``` - -(Why don't we just write `Invoke(&foo, &Foo::Concrete)`? If you do -that, `MockFoo::Concrete()` will be called (and cause an infinite -recursion) since `Foo::Concrete()` is virtual. That's just how C++ -works.) - -# Using Matchers # - -## Matching Argument Values Exactly ## - -You can specify exactly which arguments a mock method is expecting: - -``` -using ::testing::Return; -... - EXPECT_CALL(foo, DoThis(5)) - .WillOnce(Return('a')); - EXPECT_CALL(foo, DoThat("Hello", bar)); -``` - -## Using Simple Matchers ## - -You can use matchers to match arguments that have a certain property: - -``` -using ::testing::Ge; -using ::testing::NotNull; -using ::testing::Return; -... - EXPECT_CALL(foo, DoThis(Ge(5))) // The argument must be >= 5. - .WillOnce(Return('a')); - EXPECT_CALL(foo, DoThat("Hello", NotNull())); - // The second argument must not be NULL. -``` - -A frequently used matcher is `_`, which matches anything: - -``` -using ::testing::_; -using ::testing::NotNull; -... - EXPECT_CALL(foo, DoThat(_, NotNull())); -``` - -## Combining Matchers ## - -You can build complex matchers from existing ones using `AllOf()`, -`AnyOf()`, and `Not()`: - -``` -using ::testing::AllOf; -using ::testing::Gt; -using ::testing::HasSubstr; -using ::testing::Ne; -using ::testing::Not; -... - // The argument must be > 5 and != 10. - EXPECT_CALL(foo, DoThis(AllOf(Gt(5), - Ne(10)))); - - // The first argument must not contain sub-string "blah". - EXPECT_CALL(foo, DoThat(Not(HasSubstr("blah")), - NULL)); -``` - -## Casting Matchers ## - -Google Mock matchers are statically typed, meaning that the compiler -can catch your mistake if you use a matcher of the wrong type (for -example, if you use `Eq(5)` to match a `string` argument). Good for -you! - -Sometimes, however, you know what you're doing and want the compiler -to give you some slack. One example is that you have a matcher for -`long` and the argument you want to match is `int`. While the two -types aren't exactly the same, there is nothing really wrong with -using a `Matcher<long>` to match an `int` - after all, we can first -convert the `int` argument to a `long` before giving it to the -matcher. - -To support this need, Google Mock gives you the -`SafeMatcherCast<T>(m)` function. It casts a matcher `m` to type -`Matcher<T>`. To ensure safety, Google Mock checks that (let `U` be the -type `m` accepts): - - 1. Type `T` can be implicitly cast to type `U`; - 1. When both `T` and `U` are built-in arithmetic types (`bool`, integers, and floating-point numbers), the conversion from `T` to `U` is not lossy (in other words, any value representable by `T` can also be represented by `U`); and - 1. When `U` is a reference, `T` must also be a reference (as the underlying matcher may be interested in the address of the `U` value). - -The code won't compile if any of these conditions isn't met. - -Here's one example: - -``` -using ::testing::SafeMatcherCast; - -// A base class and a child class. -class Base { ... }; -class Derived : public Base { ... }; - -class MockFoo : public Foo { - public: - MOCK_METHOD1(DoThis, void(Derived* derived)); -}; -... - - MockFoo foo; - // m is a Matcher<Base*> we got from somewhere. - EXPECT_CALL(foo, DoThis(SafeMatcherCast<Derived*>(m))); -``` - -If you find `SafeMatcherCast<T>(m)` too limiting, you can use a similar -function `MatcherCast<T>(m)`. The difference is that `MatcherCast` works -as long as you can `static_cast` type `T` to type `U`. - -`MatcherCast` essentially lets you bypass C++'s type system -(`static_cast` isn't always safe as it could throw away information, -for example), so be careful not to misuse/abuse it. - -## Selecting Between Overloaded Functions ## - -If you expect an overloaded function to be called, the compiler may -need some help on which overloaded version it is. - -To disambiguate functions overloaded on the const-ness of this object, -use the `Const()` argument wrapper. - -``` -using ::testing::ReturnRef; - -class MockFoo : public Foo { - ... - MOCK_METHOD0(GetBar, Bar&()); - MOCK_CONST_METHOD0(GetBar, const Bar&()); -}; -... - - MockFoo foo; - Bar bar1, bar2; - EXPECT_CALL(foo, GetBar()) // The non-const GetBar(). - .WillOnce(ReturnRef(bar1)); - EXPECT_CALL(Const(foo), GetBar()) // The const GetBar(). - .WillOnce(ReturnRef(bar2)); -``` - -(`Const()` is defined by Google Mock and returns a `const` reference -to its argument.) - -To disambiguate overloaded functions with the same number of arguments -but different argument types, you may need to specify the exact type -of a matcher, either by wrapping your matcher in `Matcher<type>()`, or -using a matcher whose type is fixed (`TypedEq<type>`, `An<type>()`, -etc): - -``` -using ::testing::An; -using ::testing::Lt; -using ::testing::Matcher; -using ::testing::TypedEq; - -class MockPrinter : public Printer { - public: - MOCK_METHOD1(Print, void(int n)); - MOCK_METHOD1(Print, void(char c)); -}; - -TEST(PrinterTest, Print) { - MockPrinter printer; - - EXPECT_CALL(printer, Print(An<int>())); // void Print(int); - EXPECT_CALL(printer, Print(Matcher<int>(Lt(5)))); // void Print(int); - EXPECT_CALL(printer, Print(TypedEq<char>('a'))); // void Print(char); - - printer.Print(3); - printer.Print(6); - printer.Print('a'); -} -``` - -## Performing Different Actions Based on the Arguments ## - -When a mock method is called, the _last_ matching expectation that's -still active will be selected (think "newer overrides older"). So, you -can make a method do different things depending on its argument values -like this: - -``` -using ::testing::_; -using ::testing::Lt; -using ::testing::Return; -... - // The default case. - EXPECT_CALL(foo, DoThis(_)) - .WillRepeatedly(Return('b')); - - // The more specific case. - EXPECT_CALL(foo, DoThis(Lt(5))) - .WillRepeatedly(Return('a')); -``` - -Now, if `foo.DoThis()` is called with a value less than 5, `'a'` will -be returned; otherwise `'b'` will be returned. - -## Matching Multiple Arguments as a Whole ## - -Sometimes it's not enough to match the arguments individually. For -example, we may want to say that the first argument must be less than -the second argument. The `With()` clause allows us to match -all arguments of a mock function as a whole. For example, - -``` -using ::testing::_; -using ::testing::Lt; -using ::testing::Ne; -... - EXPECT_CALL(foo, InRange(Ne(0), _)) - .With(Lt()); -``` - -says that the first argument of `InRange()` must not be 0, and must be -less than the second argument. - -The expression inside `With()` must be a matcher of type -`Matcher<tr1::tuple<A1, ..., An> >`, where `A1`, ..., `An` are the -types of the function arguments. - -You can also write `AllArgs(m)` instead of `m` inside `.With()`. The -two forms are equivalent, but `.With(AllArgs(Lt()))` is more readable -than `.With(Lt())`. - -You can use `Args<k1, ..., kn>(m)` to match the `n` selected arguments -against `m`. For example, - -``` -using ::testing::_; -using ::testing::AllOf; -using ::testing::Args; -using ::testing::Lt; -... - EXPECT_CALL(foo, Blah(_, _, _)) - .With(AllOf(Args<0, 1>(Lt()), Args<1, 2>(Lt()))); -``` - -says that `Blah()` will be called with arguments `x`, `y`, and `z` where -`x < y < z`. - -As a convenience and example, Google Mock provides some matchers for -2-tuples, including the `Lt()` matcher above. See the [CheatSheet](V1_5_CheatSheet.md) for -the complete list. - -## Using Matchers as Predicates ## - -Have you noticed that a matcher is just a fancy predicate that also -knows how to describe itself? Many existing algorithms take predicates -as arguments (e.g. those defined in STL's `<algorithm>` header), and -it would be a shame if Google Mock matchers are not allowed to -participate. - -Luckily, you can use a matcher where a unary predicate functor is -expected by wrapping it inside the `Matches()` function. For example, - -``` -#include <algorithm> -#include <vector> - -std::vector<int> v; -... -// How many elements in v are >= 10? -const int count = count_if(v.begin(), v.end(), Matches(Ge(10))); -``` - -Since you can build complex matchers from simpler ones easily using -Google Mock, this gives you a way to conveniently construct composite -predicates (doing the same using STL's `<functional>` header is just -painful). For example, here's a predicate that's satisfied by any -number that is >= 0, <= 100, and != 50: - -``` -Matches(AllOf(Ge(0), Le(100), Ne(50))) -``` - -## Using Matchers in Google Test Assertions ## - -Since matchers are basically predicates that also know how to describe -themselves, there is a way to take advantage of them in -[Google Test](http://code.google.com/p/googletest/) assertions. It's -called `ASSERT_THAT` and `EXPECT_THAT`: - -``` - ASSERT_THAT(value, matcher); // Asserts that value matches matcher. - EXPECT_THAT(value, matcher); // The non-fatal version. -``` - -For example, in a Google Test test you can write: - -``` -#include <gmock/gmock.h> - -using ::testing::AllOf; -using ::testing::Ge; -using ::testing::Le; -using ::testing::MatchesRegex; -using ::testing::StartsWith; -... - - EXPECT_THAT(Foo(), StartsWith("Hello")); - EXPECT_THAT(Bar(), MatchesRegex("Line \\d+")); - ASSERT_THAT(Baz(), AllOf(Ge(5), Le(10))); -``` - -which (as you can probably guess) executes `Foo()`, `Bar()`, and -`Baz()`, and verifies that: - - * `Foo()` returns a string that starts with `"Hello"`. - * `Bar()` returns a string that matches regular expression `"Line \\d+"`. - * `Baz()` returns a number in the range [5, 10]. - -The nice thing about these macros is that _they read like -English_. They generate informative messages too. For example, if the -first `EXPECT_THAT()` above fails, the message will be something like: - -``` -Value of: Foo() - Actual: "Hi, world!" -Expected: starts with "Hello" -``` - -**Credit:** The idea of `(ASSERT|EXPECT)_THAT` was stolen from the -[Hamcrest](http://code.google.com/p/hamcrest/) project, which adds -`assertThat()` to JUnit. - -## Using Predicates as Matchers ## - -Google Mock provides a built-in set of matchers. In case you find them -lacking, you can use an arbitray unary predicate function or functor -as a matcher - as long as the predicate accepts a value of the type -you want. You do this by wrapping the predicate inside the `Truly()` -function, for example: - -``` -using ::testing::Truly; - -int IsEven(int n) { return (n % 2) == 0 ? 1 : 0; } -... - - // Bar() must be called with an even number. - EXPECT_CALL(foo, Bar(Truly(IsEven))); -``` - -Note that the predicate function / functor doesn't have to return -`bool`. It works as long as the return value can be used as the -condition in statement `if (condition) ...`. - -## Matching Arguments that Are Not Copyable ## - -When you do an `EXPECT_CALL(mock_obj, Foo(bar))`, Google Mock saves -away a copy of `bar`. When `Foo()` is called later, Google Mock -compares the argument to `Foo()` with the saved copy of `bar`. This -way, you don't need to worry about `bar` being modified or destroyed -after the `EXPECT_CALL()` is executed. The same is true when you use -matchers like `Eq(bar)`, `Le(bar)`, and so on. - -But what if `bar` cannot be copied (i.e. has no copy constructor)? You -could define your own matcher function and use it with `Truly()`, as -the previous couple of recipes have shown. Or, you may be able to get -away from it if you can guarantee that `bar` won't be changed after -the `EXPECT_CALL()` is executed. Just tell Google Mock that it should -save a reference to `bar`, instead of a copy of it. Here's how: - -``` -using ::testing::Eq; -using ::testing::ByRef; -using ::testing::Lt; -... - // Expects that Foo()'s argument == bar. - EXPECT_CALL(mock_obj, Foo(Eq(ByRef(bar)))); - - // Expects that Foo()'s argument < bar. - EXPECT_CALL(mock_obj, Foo(Lt(ByRef(bar)))); -``` - -Remember: if you do this, don't change `bar` after the -`EXPECT_CALL()`, or the result is undefined. - -## Validating a Member of an Object ## - -Often a mock function takes a reference to object as an argument. When -matching the argument, you may not want to compare the entire object -against a fixed object, as that may be over-specification. Instead, -you may need to validate a certain member variable or the result of a -certain getter method of the object. You can do this with `Field()` -and `Property()`. More specifically, - -``` -Field(&Foo::bar, m) -``` - -is a matcher that matches a `Foo` object whose `bar` member variable -satisfies matcher `m`. - -``` -Property(&Foo::baz, m) -``` - -is a matcher that matches a `Foo` object whose `baz()` method returns -a value that satisfies matcher `m`. - -For example: - -> | `Field(&Foo::number, Ge(3))` | Matches `x` where `x.number >= 3`. | -|:-----------------------------|:-----------------------------------| -> | `Property(&Foo::name, StartsWith("John "))` | Matches `x` where `x.name()` starts with `"John "`. | - -Note that in `Property(&Foo::baz, ...)`, method `baz()` must take no -argument and be declared as `const`. - -BTW, `Field()` and `Property()` can also match plain pointers to -objects. For instance, - -``` -Field(&Foo::number, Ge(3)) -``` - -matches a plain pointer `p` where `p->number >= 3`. If `p` is `NULL`, -the match will always fail regardless of the inner matcher. - -What if you want to validate more than one members at the same time? -Remember that there is `AllOf()`. - -## Validating the Value Pointed to by a Pointer Argument ## - -C++ functions often take pointers as arguments. You can use matchers -like `NULL`, `NotNull()`, and other comparison matchers to match a -pointer, but what if you want to make sure the value _pointed to_ by -the pointer, instead of the pointer itself, has a certain property? -Well, you can use the `Pointee(m)` matcher. - -`Pointee(m)` matches a pointer iff `m` matches the value the pointer -points to. For example: - -``` -using ::testing::Ge; -using ::testing::Pointee; -... - EXPECT_CALL(foo, Bar(Pointee(Ge(3)))); -``` - -expects `foo.Bar()` to be called with a pointer that points to a value -greater than or equal to 3. - -One nice thing about `Pointee()` is that it treats a `NULL` pointer as -a match failure, so you can write `Pointee(m)` instead of - -``` - AllOf(NotNull(), Pointee(m)) -``` - -without worrying that a `NULL` pointer will crash your test. - -Also, did we tell you that `Pointee()` works with both raw pointers -**and** smart pointers (`linked_ptr`, `shared_ptr`, `scoped_ptr`, and -etc)? - -What if you have a pointer to pointer? You guessed it - you can use -nested `Pointee()` to probe deeper inside the value. For example, -`Pointee(Pointee(Lt(3)))` matches a pointer that points to a pointer -that points to a number less than 3 (what a mouthful...). - -## Testing a Certain Property of an Object ## - -Sometimes you want to specify that an object argument has a certain -property, but there is no existing matcher that does this. If you want -good error messages, you should define a matcher. If you want to do it -quick and dirty, you could get away with writing an ordinary function. - -Let's say you have a mock function that takes an object of type `Foo`, -which has an `int bar()` method and an `int baz()` method, and you -want to constrain that the argument's `bar()` value plus its `baz()` -value is a given number. Here's how you can define a matcher to do it: - -``` -using ::testing::MatcherInterface; -using ::testing::MatchResultListener; - -class BarPlusBazEqMatcher : public MatcherInterface<const Foo&> { - public: - explicit BarPlusBazEqMatcher(int expected_sum) - : expected_sum_(expected_sum) {} - - virtual bool MatchAndExplain(const Foo& foo, - MatchResultListener* listener) const { - return (foo.bar() + foo.baz()) == expected_sum_; - } - - virtual void DescribeTo(::std::ostream* os) const { - *os << "bar() + baz() equals " << expected_sum_; - } - - virtual void DescribeNegationTo(::std::ostream* os) const { - *os << "bar() + baz() does not equal " << expected_sum_; - } - private: - const int expected_sum_; -}; - -inline Matcher<const Foo&> BarPlusBazEq(int expected_sum) { - return MakeMatcher(new BarPlusBazEqMatcher(expected_sum)); -} - -... - - EXPECT_CALL(..., DoThis(BarPlusBazEq(5)))...; -``` - -## Matching Containers ## - -Sometimes an STL container (e.g. list, vector, map, ...) is passed to -a mock function and you may want to validate it. Since most STL -containers support the `==` operator, you can write -`Eq(expected_container)` or simply `expected_container` to match a -container exactly. - -Sometimes, though, you may want to be more flexible (for example, the -first element must be an exact match, but the second element can be -any positive number, and so on). Also, containers used in tests often -have a small number of elements, and having to define the expected -container out-of-line is a bit of a hassle. - -You can use the `ElementsAre()` matcher in such cases: - -``` -using ::testing::_; -using ::testing::ElementsAre; -using ::testing::Gt; -... - - MOCK_METHOD1(Foo, void(const vector<int>& numbers)); -... - - EXPECT_CALL(mock, Foo(ElementsAre(1, Gt(0), _, 5))); -``` - -The above matcher says that the container must have 4 elements, which -must be 1, greater than 0, anything, and 5 respectively. - -`ElementsAre()` is overloaded to take 0 to 10 arguments. If more are -needed, you can place them in a C-style array and use -`ElementsAreArray()` instead: - -``` -using ::testing::ElementsAreArray; -... - - // ElementsAreArray accepts an array of element values. - const int expected_vector1[] = { 1, 5, 2, 4, ... }; - EXPECT_CALL(mock, Foo(ElementsAreArray(expected_vector1))); - - // Or, an array of element matchers. - Matcher<int> expected_vector2 = { 1, Gt(2), _, 3, ... }; - EXPECT_CALL(mock, Foo(ElementsAreArray(expected_vector2))); -``` - -In case the array needs to be dynamically created (and therefore the -array size cannot be inferred by the compiler), you can give -`ElementsAreArray()` an additional argument to specify the array size: - -``` -using ::testing::ElementsAreArray; -... - int* const expected_vector3 = new int[count]; - ... fill expected_vector3 with values ... - EXPECT_CALL(mock, Foo(ElementsAreArray(expected_vector3, count))); -``` - -**Tips:** - - * `ElementAre*()` works with _any_ container that implements the STL iterator concept (i.e. it has a `const_iterator` type and supports `begin()/end()`) and supports `size()`, not just the ones defined in STL. It will even work with container types yet to be written - as long as they follows the above pattern. - * You can use nested `ElementAre*()` to match nested (multi-dimensional) containers. - * If the container is passed by pointer instead of by reference, just write `Pointee(ElementsAre*(...))`. - * The order of elements _matters_ for `ElementsAre*()`. Therefore don't use it with containers whose element order is undefined (e.g. `hash_map`). - -## Sharing Matchers ## - -Under the hood, a Google Mock matcher object consists of a pointer to -a ref-counted implementation object. Copying matchers is allowed and -very efficient, as only the pointer is copied. When the last matcher -that references the implementation object dies, the implementation -object will be deleted. - -Therefore, if you have some complex matcher that you want to use again -and again, there is no need to build it everytime. Just assign it to a -matcher variable and use that variable repeatedly! For example, - -``` - Matcher<int> in_range = AllOf(Gt(5), Le(10)); - ... use in_range as a matcher in multiple EXPECT_CALLs ... -``` - -# Setting Expectations # - -## Ignoring Uninteresting Calls ## - -If you are not interested in how a mock method is called, just don't -say anything about it. In this case, if the method is ever called, -Google Mock will perform its default action to allow the test program -to continue. If you are not happy with the default action taken by -Google Mock, you can override it using `DefaultValue<T>::Set()` -(described later in this document) or `ON_CALL()`. - -Please note that once you expressed interest in a particular mock -method (via `EXPECT_CALL()`), all invocations to it must match some -expectation. If this function is called but the arguments don't match -any `EXPECT_CALL()` statement, it will be an error. - -## Disallowing Unexpected Calls ## - -If a mock method shouldn't be called at all, explicitly say so: - -``` -using ::testing::_; -... - EXPECT_CALL(foo, Bar(_)) - .Times(0); -``` - -If some calls to the method are allowed, but the rest are not, just -list all the expected calls: - -``` -using ::testing::AnyNumber; -using ::testing::Gt; -... - EXPECT_CALL(foo, Bar(5)); - EXPECT_CALL(foo, Bar(Gt(10))) - .Times(AnyNumber()); -``` - -A call to `foo.Bar()` that doesn't match any of the `EXPECT_CALL()` -statements will be an error. - -## Expecting Ordered Calls ## - -Although an `EXPECT_CALL()` statement defined earlier takes precedence -when Google Mock tries to match a function call with an expectation, -by default calls don't have to happen in the order `EXPECT_CALL()` -statements are written. For example, if the arguments match the -matchers in the third `EXPECT_CALL()`, but not those in the first two, -then the third expectation will be used. - -If you would rather have all calls occur in the order of the -expectations, put the `EXPECT_CALL()` statements in a block where you -define a variable of type `InSequence`: - -``` - using ::testing::_; - using ::testing::InSequence; - - { - InSequence s; - - EXPECT_CALL(foo, DoThis(5)); - EXPECT_CALL(bar, DoThat(_)) - .Times(2); - EXPECT_CALL(foo, DoThis(6)); - } -``` - -In this example, we expect a call to `foo.DoThis(5)`, followed by two -calls to `bar.DoThat()` where the argument can be anything, which are -in turn followed by a call to `foo.DoThis(6)`. If a call occurred -out-of-order, Google Mock will report an error. - -## Expecting Partially Ordered Calls ## - -Sometimes requiring everything to occur in a predetermined order can -lead to brittle tests. For example, we may care about `A` occurring -before both `B` and `C`, but aren't interested in the relative order -of `B` and `C`. In this case, the test should reflect our real intent, -instead of being overly constraining. - -Google Mock allows you to impose an arbitrary DAG (directed acyclic -graph) on the calls. One way to express the DAG is to use the -[After](V1_5_CheatSheet#The_After_Clause.md) clause of `EXPECT_CALL`. - -Another way is via the `InSequence()` clause (not the same as the -`InSequence` class), which we borrowed from jMock 2. It's less -flexible than `After()`, but more convenient when you have long chains -of sequential calls, as it doesn't require you to come up with -different names for the expectations in the chains. Here's how it -works: - -If we view `EXPECT_CALL()` statements as nodes in a graph, and add an -edge from node A to node B wherever A must occur before B, we can get -a DAG. We use the term "sequence" to mean a directed path in this -DAG. Now, if we decompose the DAG into sequences, we just need to know -which sequences each `EXPECT_CALL()` belongs to in order to be able to -reconstruct the orginal DAG. - -So, to specify the partial order on the expectations we need to do two -things: first to define some `Sequence` objects, and then for each -`EXPECT_CALL()` say which `Sequence` objects it is part -of. Expectations in the same sequence must occur in the order they are -written. For example, - -``` - using ::testing::Sequence; - - Sequence s1, s2; - - EXPECT_CALL(foo, A()) - .InSequence(s1, s2); - EXPECT_CALL(bar, B()) - .InSequence(s1); - EXPECT_CALL(bar, C()) - .InSequence(s2); - EXPECT_CALL(foo, D()) - .InSequence(s2); -``` - -specifies the following DAG (where `s1` is `A -> B`, and `s2` is `A -> -C -> D`): - -``` - +---> B - | - A ---| - | - +---> C ---> D -``` - -This means that A must occur before B and C, and C must occur before -D. There's no restriction about the order other than these. - -## Controlling When an Expectation Retires ## - -When a mock method is called, Google Mock only consider expectations -that are still active. An expectation is active when created, and -becomes inactive (aka _retires_) when a call that has to occur later -has occurred. For example, in - -``` - using ::testing::_; - using ::testing::Sequence; - - Sequence s1, s2; - - EXPECT_CALL(log, Log(WARNING, _, "File too large.")) // #1 - .Times(AnyNumber()) - .InSequence(s1, s2); - EXPECT_CALL(log, Log(WARNING, _, "Data set is empty.")) // #2 - .InSequence(s1); - EXPECT_CALL(log, Log(WARNING, _, "User not found.")) // #3 - .InSequence(s2); -``` - -as soon as either #2 or #3 is matched, #1 will retire. If a warning -`"File too large."` is logged after this, it will be an error. - -Note that an expectation doesn't retire automatically when it's -saturated. For example, - -``` -using ::testing::_; -... - EXPECT_CALL(log, Log(WARNING, _, _)); // #1 - EXPECT_CALL(log, Log(WARNING, _, "File too large.")); // #2 -``` - -says that there will be exactly one warning with the message `"File -too large."`. If the second warning contains this message too, #2 will -match again and result in an upper-bound-violated error. - -If this is not what you want, you can ask an expectation to retire as -soon as it becomes saturated: - -``` -using ::testing::_; -... - EXPECT_CALL(log, Log(WARNING, _, _)); // #1 - EXPECT_CALL(log, Log(WARNING, _, "File too large.")) // #2 - .RetiresOnSaturation(); -``` - -Here #2 can be used only once, so if you have two warnings with the -message `"File too large."`, the first will match #2 and the second -will match #1 - there will be no error. - -# Using Actions # - -## Returning References from Mock Methods ## - -If a mock function's return type is a reference, you need to use -`ReturnRef()` instead of `Return()` to return a result: - -``` -using ::testing::ReturnRef; - -class MockFoo : public Foo { - public: - MOCK_METHOD0(GetBar, Bar&()); -}; -... - - MockFoo foo; - Bar bar; - EXPECT_CALL(foo, GetBar()) - .WillOnce(ReturnRef(bar)); -``` - -## Combining Actions ## - -Want to do more than one thing when a function is called? That's -fine. `DoAll()` allow you to do sequence of actions every time. Only -the return value of the last action in the sequence will be used. - -``` -using ::testing::DoAll; - -class MockFoo : public Foo { - public: - MOCK_METHOD1(Bar, bool(int n)); -}; -... - - EXPECT_CALL(foo, Bar(_)) - .WillOnce(DoAll(action_1, - action_2, - ... - action_n)); -``` - -## Mocking Side Effects ## - -Sometimes a method exhibits its effect not via returning a value but -via side effects. For example, it may change some global state or -modify an output argument. To mock side effects, in general you can -define your own action by implementing `::testing::ActionInterface`. - -If all you need to do is to change an output argument, the built-in -`SetArgumentPointee()` action is convenient: - -``` -using ::testing::SetArgumentPointee; - -class MockMutator : public Mutator { - public: - MOCK_METHOD2(Mutate, void(bool mutate, int* value)); - ... -}; -... - - MockMutator mutator; - EXPECT_CALL(mutator, Mutate(true, _)) - .WillOnce(SetArgumentPointee<1>(5)); -``` - -In this example, when `mutator.Mutate()` is called, we will assign 5 -to the `int` variable pointed to by argument #1 -(0-based). - -`SetArgumentPointee()` conveniently makes an internal copy of the -value you pass to it, removing the need to keep the value in scope and -alive. The implication however is that the value must have a copy -constructor and assignment operator. - -If the mock method also needs to return a value as well, you can chain -`SetArgumentPointee()` with `Return()` using `DoAll()`: - -``` -using ::testing::_; -using ::testing::Return; -using ::testing::SetArgumentPointee; - -class MockMutator : public Mutator { - public: - ... - MOCK_METHOD1(MutateInt, bool(int* value)); -}; -... - - MockMutator mutator; - EXPECT_CALL(mutator, MutateInt(_)) - .WillOnce(DoAll(SetArgumentPointee<0>(5), - Return(true))); -``` - -If the output argument is an array, use the -`SetArrayArgument<N>(first, last)` action instead. It copies the -elements in source range `[first, last)` to the array pointed to by -the `N`-th (0-based) argument: - -``` -using ::testing::NotNull; -using ::testing::SetArrayArgument; - -class MockArrayMutator : public ArrayMutator { - public: - MOCK_METHOD2(Mutate, void(int* values, int num_values)); - ... -}; -... - - MockArrayMutator mutator; - int values[5] = { 1, 2, 3, 4, 5 }; - EXPECT_CALL(mutator, Mutate(NotNull(), 5)) - .WillOnce(SetArrayArgument<0>(values, values + 5)); -``` - -This also works when the argument is an output iterator: - -``` -using ::testing::_; -using ::testing::SeArrayArgument; - -class MockRolodex : public Rolodex { - public: - MOCK_METHOD1(GetNames, void(std::back_insert_iterator<vector<string> >)); - ... -}; -... - - MockRolodex rolodex; - vector<string> names; - names.push_back("George"); - names.push_back("John"); - names.push_back("Thomas"); - EXPECT_CALL(rolodex, GetNames(_)) - .WillOnce(SetArrayArgument<0>(names.begin(), names.end())); -``` - -## Changing a Mock Object's Behavior Based on the State ## - -If you expect a call to change the behavior of a mock object, you can use `::testing::InSequence` to specify different behaviors before and after the call: - -``` -using ::testing::InSequence; -using ::testing::Return; - -... - { - InSequence seq; - EXPECT_CALL(my_mock, IsDirty()) - .WillRepeatedly(Return(true)); - EXPECT_CALL(my_mock, Flush()); - EXPECT_CALL(my_mock, IsDirty()) - .WillRepeatedly(Return(false)); - } - my_mock.FlushIfDirty(); -``` - -This makes `my_mock.IsDirty()` return `true` before `my_mock.Flush()` is called and return `false` afterwards. - -If the behavior change is more complex, you can store the effects in a variable and make a mock method get its return value from that variable: - -``` -using ::testing::_; -using ::testing::SaveArg; -using ::testing::Return; - -ACTION_P(ReturnPointee, p) { return *p; } -... - int previous_value = 0; - EXPECT_CALL(my_mock, GetPrevValue()) - .WillRepeatedly(ReturnPointee(&previous_value)); - EXPECT_CALL(my_mock, UpdateValue(_)) - .WillRepeatedly(SaveArg<0>(&previous_value)); - my_mock.DoSomethingToUpdateValue(); -``` - -Here `my_mock.GetPrevValue()` will always return the argument of the last `UpdateValue()` call. - -## Setting the Default Value for a Return Type ## - -If a mock method's return type is a built-in C++ type or pointer, by -default it will return 0 when invoked. You only need to specify an -action if this default value doesn't work for you. - -Sometimes, you may want to change this default value, or you may want -to specify a default value for types Google Mock doesn't know -about. You can do this using the `::testing::DefaultValue` class -template: - -``` -class MockFoo : public Foo { - public: - MOCK_METHOD0(CalculateBar, Bar()); -}; -... - - Bar default_bar; - // Sets the default return value for type Bar. - DefaultValue<Bar>::Set(default_bar); - - MockFoo foo; - - // We don't need to specify an action here, as the default - // return value works for us. - EXPECT_CALL(foo, CalculateBar()); - - foo.CalculateBar(); // This should return default_bar. - - // Unsets the default return value. - DefaultValue<Bar>::Clear(); -``` - -Please note that changing the default value for a type can make you -tests hard to understand. We recommend you to use this feature -judiciously. For example, you may want to make sure the `Set()` and -`Clear()` calls are right next to the code that uses your mock. - -## Setting the Default Actions for a Mock Method ## - -You've learned how to change the default value of a given -type. However, this may be too coarse for your purpose: perhaps you -have two mock methods with the same return type and you want them to -have different behaviors. The `ON_CALL()` macro allows you to -customize your mock's behavior at the method level: - -``` -using ::testing::_; -using ::testing::AnyNumber; -using ::testing::Gt; -using ::testing::Return; -... - ON_CALL(foo, Sign(_)) - .WillByDefault(Return(-1)); - ON_CALL(foo, Sign(0)) - .WillByDefault(Return(0)); - ON_CALL(foo, Sign(Gt(0))) - .WillByDefault(Return(1)); - - EXPECT_CALL(foo, Sign(_)) - .Times(AnyNumber()); - - foo.Sign(5); // This should return 1. - foo.Sign(-9); // This should return -1. - foo.Sign(0); // This should return 0. -``` - -As you may have guessed, when there are more than one `ON_CALL()` -statements, the news order take precedence over the older ones. In -other words, the **last** one that matches the function arguments will -be used. This matching order allows you to set up the common behavior -in a mock object's constructor or the test fixture's set-up phase and -specialize the mock's behavior later. - -## Using Functions/Methods/Functors as Actions ## - -If the built-in actions don't suit you, you can easily use an existing -function, method, or functor as an action: - -``` -using ::testing::_; -using ::testing::Invoke; - -class MockFoo : public Foo { - public: - MOCK_METHOD2(Sum, int(int x, int y)); - MOCK_METHOD1(ComplexJob, bool(int x)); -}; - -int CalculateSum(int x, int y) { return x + y; } - -class Helper { - public: - bool ComplexJob(int x); -}; -... - - MockFoo foo; - Helper helper; - EXPECT_CALL(foo, Sum(_, _)) - .WillOnce(Invoke(CalculateSum)); - EXPECT_CALL(foo, ComplexJob(_)) - .WillOnce(Invoke(&helper, &Helper::ComplexJob)); - - foo.Sum(5, 6); // Invokes CalculateSum(5, 6). - foo.ComplexJob(10); // Invokes helper.ComplexJob(10); -``` - -The only requirement is that the type of the function, etc must be -_compatible_ with the signature of the mock function, meaning that the -latter's arguments can be implicitly converted to the corresponding -arguments of the former, and the former's return type can be -implicitly converted to that of the latter. So, you can invoke -something whose type is _not_ exactly the same as the mock function, -as long as it's safe to do so - nice, huh? - -## Invoking a Function/Method/Functor Without Arguments ## - -`Invoke()` is very useful for doing actions that are more complex. It -passes the mock function's arguments to the function or functor being -invoked such that the callee has the full context of the call to work -with. If the invoked function is not interested in some or all of the -arguments, it can simply ignore them. - -Yet, a common pattern is that a test author wants to invoke a function -without the arguments of the mock function. `Invoke()` allows her to -do that using a wrapper function that throws away the arguments before -invoking an underlining nullary function. Needless to say, this can be -tedious and obscures the intent of the test. - -`InvokeWithoutArgs()` solves this problem. It's like `Invoke()` except -that it doesn't pass the mock function's arguments to the -callee. Here's an example: - -``` -using ::testing::_; -using ::testing::InvokeWithoutArgs; - -class MockFoo : public Foo { - public: - MOCK_METHOD1(ComplexJob, bool(int n)); -}; - -bool Job1() { ... } -... - - MockFoo foo; - EXPECT_CALL(foo, ComplexJob(_)) - .WillOnce(InvokeWithoutArgs(Job1)); - - foo.ComplexJob(10); // Invokes Job1(). -``` - -## Invoking an Argument of the Mock Function ## - -Sometimes a mock function will receive a function pointer or a functor -(in other words, a "callable") as an argument, e.g. - -``` -class MockFoo : public Foo { - public: - MOCK_METHOD2(DoThis, bool(int n, bool (*fp)(int))); -}; -``` - -and you may want to invoke this callable argument: - -``` -using ::testing::_; -... - MockFoo foo; - EXPECT_CALL(foo, DoThis(_, _)) - .WillOnce(...); - // Will execute (*fp)(5), where fp is the - // second argument DoThis() receives. -``` - -Arghh, you need to refer to a mock function argument but C++ has no -lambda (yet), so you have to define your own action. :-( Or do you -really? - -Well, Google Mock has an action to solve _exactly_ this problem: - -``` - InvokeArgument<N>(arg_1, arg_2, ..., arg_m) -``` - -will invoke the `N`-th (0-based) argument the mock function receives, -with `arg_1`, `arg_2`, ..., and `arg_m`. No matter if the argument is -a function pointer or a functor, Google Mock handles them both. - -With that, you could write: - -``` -using ::testing::_; -using ::testing::InvokeArgument; -... - EXPECT_CALL(foo, DoThis(_, _)) - .WillOnce(InvokeArgument<1>(5)); - // Will execute (*fp)(5), where fp is the - // second argument DoThis() receives. -``` - -What if the callable takes an argument by reference? No problem - just -wrap it inside `ByRef()`: - -``` -... - MOCK_METHOD1(Bar, bool(bool (*fp)(int, const Helper&))); -... -using ::testing::_; -using ::testing::ByRef; -using ::testing::InvokeArgument; -... - - MockFoo foo; - Helper helper; - ... - EXPECT_CALL(foo, Bar(_)) - .WillOnce(InvokeArgument<0>(5, ByRef(helper))); - // ByRef(helper) guarantees that a reference to helper, not a copy of it, - // will be passed to the callable. -``` - -What if the callable takes an argument by reference and we do **not** -wrap the argument in `ByRef()`? Then `InvokeArgument()` will _make a -copy_ of the argument, and pass a _reference to the copy_, instead of -a reference to the original value, to the callable. This is especially -handy when the argument is a temporary value: - -``` -... - MOCK_METHOD1(DoThat, bool(bool (*f)(const double& x, const string& s))); -... -using ::testing::_; -using ::testing::InvokeArgument; -... - - MockFoo foo; - ... - EXPECT_CALL(foo, DoThat(_)) - .WillOnce(InvokeArgument<0>(5.0, string("Hi"))); - // Will execute (*f)(5.0, string("Hi")), where f is the function pointer - // DoThat() receives. Note that the values 5.0 and string("Hi") are - // temporary and dead once the EXPECT_CALL() statement finishes. Yet - // it's fine to perform this action later, since a copy of the values - // are kept inside the InvokeArgument action. -``` - -## Ignoring an Action's Result ## - -Sometimes you have an action that returns _something_, but you need an -action that returns `void` (perhaps you want to use it in a mock -function that returns `void`, or perhaps it needs to be used in -`DoAll()` and it's not the last in the list). `IgnoreResult()` lets -you do that. For example: - -``` -using ::testing::_; -using ::testing::Invoke; -using ::testing::Return; - -int Process(const MyData& data); -string DoSomething(); - -class MockFoo : public Foo { - public: - MOCK_METHOD1(Abc, void(const MyData& data)); - MOCK_METHOD0(Xyz, bool()); -}; -... - - MockFoo foo; - EXPECT_CALL(foo, Abc(_)) - // .WillOnce(Invoke(Process)); - // The above line won't compile as Process() returns int but Abc() needs - // to return void. - .WillOnce(IgnoreResult(Invoke(Process))); - - EXPECT_CALL(foo, Xyz()) - .WillOnce(DoAll(IgnoreResult(Invoke(DoSomething)), - // Ignores the string DoSomething() returns. - Return(true))); -``` - -Note that you **cannot** use `IgnoreResult()` on an action that already -returns `void`. Doing so will lead to ugly compiler errors. - -## Selecting an Action's Arguments ## - -Say you have a mock function `Foo()` that takes seven arguments, and -you have a custom action that you want to invoke when `Foo()` is -called. Trouble is, the custom action only wants three arguments: - -``` -using ::testing::_; -using ::testing::Invoke; -... - MOCK_METHOD7(Foo, bool(bool visible, const string& name, int x, int y, - const map<pair<int, int>, double>& weight, - double min_weight, double max_wight)); -... - -bool IsVisibleInQuadrant1(bool visible, int x, int y) { - return visible && x >= 0 && y >= 0; -} -... - - EXPECT_CALL(mock, Foo(_, _, _, _, _, _, _)) - .WillOnce(Invoke(IsVisibleInQuadrant1)); // Uh, won't compile. :-( -``` - -To please the compiler God, you can to define an "adaptor" that has -the same signature as `Foo()` and calls the custom action with the -right arguments: - -``` -using ::testing::_; -using ::testing::Invoke; - -bool MyIsVisibleInQuadrant1(bool visible, const string& name, int x, int y, - const map<pair<int, int>, double>& weight, - double min_weight, double max_wight) { - return IsVisibleInQuadrant1(visible, x, y); -} -... - - EXPECT_CALL(mock, Foo(_, _, _, _, _, _, _)) - .WillOnce(Invoke(MyIsVisibleInQuadrant1)); // Now it works. -``` - -But isn't this awkward? - -Google Mock provides a generic _action adaptor_, so you can spend your -time minding more important business than writing your own -adaptors. Here's the syntax: - -``` - WithArgs<N1, N2, ..., Nk>(action) -``` - -creates an action that passes the arguments of the mock function at -the given indices (0-based) to the inner `action` and performs -it. Using `WithArgs`, our original example can be written as: - -``` -using ::testing::_; -using ::testing::Invoke; -using ::testing::WithArgs; -... - EXPECT_CALL(mock, Foo(_, _, _, _, _, _, _)) - .WillOnce(WithArgs<0, 2, 3>(Invoke(IsVisibleInQuadrant1))); - // No need to define your own adaptor. -``` - -For better readability, Google Mock also gives you: - - * `WithoutArgs(action)` when the inner `action` takes _no_ argument, and - * `WithArg<N>(action)` (no `s` after `Arg`) when the inner `action` takes _one_ argument. - -As you may have realized, `InvokeWithoutArgs(...)` is just syntactic -sugar for `WithoutArgs(Inovke(...))`. - -Here are more tips: - - * The inner action used in `WithArgs` and friends does not have to be `Invoke()` -- it can be anything. - * You can repeat an argument in the argument list if necessary, e.g. `WithArgs<2, 3, 3, 5>(...)`. - * You can change the order of the arguments, e.g. `WithArgs<3, 2, 1>(...)`. - * The types of the selected arguments do _not_ have to match the signature of the inner action exactly. It works as long as they can be implicitly converted to the corresponding arguments of the inner action. For example, if the 4-th argument of the mock function is an `int` and `my_action` takes a `double`, `WithArg<4>(my_action)` will work. - -## Ignoring Arguments in Action Functions ## - -The selecting-an-action's-arguments recipe showed us one way to make a -mock function and an action with incompatible argument lists fit -together. The downside is that wrapping the action in -`WithArgs<...>()` can get tedious for people writing the tests. - -If you are defining a function, method, or functor to be used with -`Invoke*()`, and you are not interested in some of its arguments, an -alternative to `WithArgs` is to declare the uninteresting arguments as -`Unused`. This makes the definition less cluttered and less fragile in -case the types of the uninteresting arguments change. It could also -increase the chance the action function can be reused. For example, -given - -``` - MOCK_METHOD3(Foo, double(const string& label, double x, double y)); - MOCK_METHOD3(Bar, double(int index, double x, double y)); -``` - -instead of - -``` -using ::testing::_; -using ::testing::Invoke; - -double DistanceToOriginWithLabel(const string& label, double x, double y) { - return sqrt(x*x + y*y); -} - -double DistanceToOriginWithIndex(int index, double x, double y) { - return sqrt(x*x + y*y); -} -... - - EXEPCT_CALL(mock, Foo("abc", _, _)) - .WillOnce(Invoke(DistanceToOriginWithLabel)); - EXEPCT_CALL(mock, Bar(5, _, _)) - .WillOnce(Invoke(DistanceToOriginWithIndex)); -``` - -you could write - -``` -using ::testing::_; -using ::testing::Invoke; -using ::testing::Unused; - -double DistanceToOrigin(Unused, double x, double y) { - return sqrt(x*x + y*y); -} -... - - EXEPCT_CALL(mock, Foo("abc", _, _)) - .WillOnce(Invoke(DistanceToOrigin)); - EXEPCT_CALL(mock, Bar(5, _, _)) - .WillOnce(Invoke(DistanceToOrigin)); -``` - -## Sharing Actions ## - -Just like matchers, a Google Mock action object consists of a pointer -to a ref-counted implementation object. Therefore copying actions is -also allowed and very efficient. When the last action that references -the implementation object dies, the implementation object will be -deleted. - -If you have some complex action that you want to use again and again, -you may not have to build it from scratch everytime. If the action -doesn't have an internal state (i.e. if it always does the same thing -no matter how many times it has been called), you can assign it to an -action variable and use that variable repeatedly. For example: - -``` - Action<bool(int*)> set_flag = DoAll(SetArgumentPointee<0>(5), - Return(true)); - ... use set_flag in .WillOnce() and .WillRepeatedly() ... -``` - -However, if the action has its own state, you may be surprised if you -share the action object. Suppose you have an action factory -`IncrementCounter(init)` which creates an action that increments and -returns a counter whose initial value is `init`, using two actions -created from the same expression and using a shared action will -exihibit different behaviors. Example: - -``` - EXPECT_CALL(foo, DoThis()) - .WillRepeatedly(IncrementCounter(0)); - EXPECT_CALL(foo, DoThat()) - .WillRepeatedly(IncrementCounter(0)); - foo.DoThis(); // Returns 1. - foo.DoThis(); // Returns 2. - foo.DoThat(); // Returns 1 - Blah() uses a different - // counter than Bar()'s. -``` - -versus - -``` - Action<int()> increment = IncrementCounter(0); - - EXPECT_CALL(foo, DoThis()) - .WillRepeatedly(increment); - EXPECT_CALL(foo, DoThat()) - .WillRepeatedly(increment); - foo.DoThis(); // Returns 1. - foo.DoThis(); // Returns 2. - foo.DoThat(); // Returns 3 - the counter is shared. -``` - -# Misc Recipes on Using Google Mock # - -## Forcing a Verification ## - -When it's being destoyed, your friendly mock object will automatically -verify that all expectations on it have been satisfied, and will -generate [Google Test](http://code.google.com/p/googletest/) failures -if not. This is convenient as it leaves you with one less thing to -worry about. That is, unless you are not sure if your mock object will -be destoyed. - -How could it be that your mock object won't eventually be destroyed? -Well, it might be created on the heap and owned by the code you are -testing. Suppose there's a bug in that code and it doesn't delete the -mock object properly - you could end up with a passing test when -there's actually a bug. - -Using a heap checker is a good idea and can alleviate the concern, but -its implementation may not be 100% reliable. So, sometimes you do want -to _force_ Google Mock to verify a mock object before it is -(hopefully) destructed. You can do this with -`Mock::VerifyAndClearExpectations(&mock_object)`: - -``` -TEST(MyServerTest, ProcessesRequest) { - using ::testing::Mock; - - MockFoo* const foo = new MockFoo; - EXPECT_CALL(*foo, ...)...; - // ... other expectations ... - - // server now owns foo. - MyServer server(foo); - server.ProcessRequest(...); - - // In case that server's destructor will forget to delete foo, - // this will verify the expectations anyway. - Mock::VerifyAndClearExpectations(foo); -} // server is destroyed when it goes out of scope here. -``` - -**Tip:** The `Mock::VerifyAndClearExpectations()` function returns a -`bool` to indicate whether the verification was successful (`true` for -yes), so you can wrap that function call inside a `ASSERT_TRUE()` if -there is no point going further when the verification has failed. - -## Using Check Points ## - -Sometimes you may want to "reset" a mock object at various check -points in your test: at each check point, you verify that all existing -expectations on the mock object have been satisfied, and then you set -some new expectations on it as if it's newly created. This allows you -to work with a mock object in "phases" whose sizes are each -manageable. - -One such scenario is that in your test's `SetUp()` function, you may -want to put the object you are testing into a certain state, with the -help from a mock object. Once in the desired state, you want to clear -all expectations on the mock, such that in the `TEST_F` body you can -set fresh expectations on it. - -As you may have figured out, the `Mock::VerifyAndClearExpectations()` -function we saw in the previous recipe can help you here. Or, if you -are using `ON_CALL()` to set default actions on the mock object and -want to clear the default actions as well, use -`Mock::VerifyAndClear(&mock_object)` instead. This function does what -`Mock::VerifyAndClearExpectations(&mock_object)` does and returns the -same `bool`, **plus** it clears the `ON_CALL()` statements on -`mock_object` too. - -Another trick you can use to achieve the same effect is to put the -expectations in sequences and insert calls to a dummy "check-point" -function at specific places. Then you can verify that the mock -function calls do happen at the right time. For example, if you are -exercising code: - -``` -Foo(1); -Foo(2); -Foo(3); -``` - -and want to verify that `Foo(1)` and `Foo(3)` both invoke -`mock.Bar("a")`, but `Foo(2)` doesn't invoke anything. You can write: - -``` -using ::testing::MockFunction; - -TEST(FooTest, InvokesBarCorrectly) { - MyMock mock; - // Class MockFunction<F> has exactly one mock method. It is named - // Call() and has type F. - MockFunction<void(string check_point_name)> check; - { - InSequence s; - - EXPECT_CALL(mock, Bar("a")); - EXPECT_CALL(check, Call("1")); - EXPECT_CALL(check, Call("2")); - EXPECT_CALL(mock, Bar("a")); - } - Foo(1); - check.Call("1"); - Foo(2); - check.Call("2"); - Foo(3); -} -``` - -The expectation spec says that the first `Bar("a")` must happen before -check point "1", the second `Bar("a")` must happen after check point "2", -and nothing should happen between the two check points. The explicit -check points make it easy to tell which `Bar("a")` is called by which -call to `Foo()`. - -## Mocking Destructors ## - -Sometimes you want to make sure a mock object is destructed at the -right time, e.g. after `bar->A()` is called but before `bar->B()` is -called. We already know that you can specify constraints on the order -of mock function calls, so all we need to do is to mock the destructor -of the mock function. - -This sounds simple, except for one problem: a destructor is a special -function with special syntax and special semantics, and the -`MOCK_METHOD0` macro doesn't work for it: - -``` - MOCK_METHOD0(~MockFoo, void()); // Won't compile! -``` - -The good news is that you can use a simple pattern to achieve the same -effect. First, add a mock function `Die()` to your mock class and call -it in the destructor, like this: - -``` -class MockFoo : public Foo { - ... - // Add the following two lines to the mock class. - MOCK_METHOD0(Die, void()); - virtual ~MockFoo() { Die(); } -}; -``` - -(If the name `Die()` clashes with an existing symbol, choose another -name.) Now, we have translated the problem of testing when a `MockFoo` -object dies to testing when its `Die()` method is called: - -``` - MockFoo* foo = new MockFoo; - MockBar* bar = new MockBar; - ... - { - InSequence s; - - // Expects *foo to die after bar->A() and before bar->B(). - EXPECT_CALL(*bar, A()); - EXPECT_CALL(*foo, Die()); - EXPECT_CALL(*bar, B()); - } -``` - -And that's that. - -## Using Google Mock and Threads ## - -**IMPORTANT NOTE:** What we describe in this recipe is **NOT** true yet, -as Google Mock is not currently thread-safe. However, all we need to -make it thread-safe is to implement some synchronization operations in -`<gtest/internal/gtest-port.h>` - and then the information below will -become true. - -In a **unit** test, it's best if you could isolate and test a piece of -code in a single-threaded context. That avoids race conditions and -dead locks, and makes debugging your test much easier. - -Yet many programs are multi-threaded, and sometimes to test something -we need to pound on it from more than one thread. Google Mock works -for this purpose too. - -Remember the steps for using a mock: - - 1. Create a mock object `foo`. - 1. Set its default actions and expectations using `ON_CALL()` and `EXPECT_CALL()`. - 1. The code under test calls methods of `foo`. - 1. Optionally, verify and reset the mock. - 1. Destroy the mock yourself, or let the code under test destroy it. The destructor will automatically verify it. - -If you follow the following simple rules, your mocks and threads can -live happily togeter: - - * Execute your _test code_ (as opposed to the code being tested) in _one_ thread. This makes your test easy to follow. - * Obviously, you can do step #1 without locking. - * When doing step #2 and #5, make sure no other thread is accessing `foo`. Obvious too, huh? - * #3 and #4 can be done either in one thread or in multiple threads - anyway you want. Google Mock takes care of the locking, so you don't have to do any - unless required by your test logic. - -If you violate the rules (for example, if you set expectations on a -mock while another thread is calling its methods), you get undefined -behavior. That's not fun, so don't do it. - -Google Mock guarantees that the action for a mock function is done in -the same thread that called the mock function. For example, in - -``` - EXPECT_CALL(mock, Foo(1)) - .WillOnce(action1); - EXPECT_CALL(mock, Foo(2)) - .WillOnce(action2); -``` - -if `Foo(1)` is called in thread 1 and `Foo(2)` is called in thread 2, -Google Mock will execute `action1` in thread 1 and `action2` in thread -2. - -Google Mock does _not_ impose a sequence on actions performed in -different threads (doing so may create deadlocks as the actions may -need to cooperate). This means that the execution of `action1` and -`action2` in the above example _may_ interleave. If this is a problem, -you should add proper synchronization logic to `action1` and `action2` -to make the test thread-safe. - - -Also, remember that `DefaultValue<T>` is a global resource that -potentially affects _all_ living mock objects in your -program. Naturally, you won't want to mess with it from multiple -threads or when there still are mocks in action. - -## Controlling How Much Information Google Mock Prints ## - -When Google Mock sees something that has the potential of being an -error (e.g. a mock function with no expectation is called, a.k.a. an -uninteresting call, which is allowed but perhaps you forgot to -explicitly ban the call), it prints some warning messages, including -the arguments of the function and the return value. Hopefully this -will remind you to take a look and see if there is indeed a problem. - -Sometimes you are confident that your tests are correct and may not -appreciate such friendly messages. Some other times, you are debugging -your tests or learning about the behavior of the code you are testing, -and wish you could observe every mock call that happens (including -argument values and the return value). Clearly, one size doesn't fit -all. - -You can control how much Google Mock tells you using the -`--gmock_verbose=LEVEL` command-line flag, where `LEVEL` is a string -with three possible values: - - * `info`: Google Mock will print all informational messages, warnings, and errors (most verbose). At this setting, Google Mock will also log any calls to the `ON_CALL/EXPECT_CALL` macros. - * `warning`: Google Mock will print both warnings and errors (less verbose). This is the default. - * `error`: Google Mock will print errors only (least verbose). - -Alternatively, you can adjust the value of that flag from within your -tests like so: - -``` - ::testing::FLAGS_gmock_verbose = "error"; -``` - -Now, judiciously use the right flag to enable Google Mock serve you better! - -## Running Tests in Emacs ## - -If you build and run your tests in Emacs, the source file locations of -Google Mock and [Google Test](http://code.google.com/p/googletest/) -errors will be highlighted. Just press `<Enter>` on one of them and -you'll be taken to the offending line. Or, you can just type `C-x `` -to jump to the next error. - -To make it even easier, you can add the following lines to your -`~/.emacs` file: - -``` -(global-set-key "\M-m" 'compile) ; m is for make -(global-set-key [M-down] 'next-error) -(global-set-key [M-up] '(lambda () (interactive) (next-error -1))) -``` - -Then you can type `M-m` to start a build, or `M-up`/`M-down` to move -back and forth between errors. - -## Fusing Google Mock Source Files ## - -Google Mock's implementation consists of dozens of files (excluding -its own tests). Sometimes you may want them to be packaged up in -fewer files instead, such that you can easily copy them to a new -machine and start hacking there. For this we provide an experimental -Python script `fuse_gmock_files.py` in the `scripts/` directory -(starting with release 1.2.0). Assuming you have Python 2.4 or above -installed on your machine, just go to that directory and run -``` -python fuse_gmock_files.py OUTPUT_DIR -``` - -and you should see an `OUTPUT_DIR` directory being created with files -`gtest/gtest.h`, `gmock/gmock.h`, and `gmock-gtest-all.cc` in it. -These three files contain everything you need to use Google Mock (and -Google Test). Just copy them to anywhere you want and you are ready -to write tests and use mocks. You can use the -[scrpts/test/Makefile](http://code.google.com/p/googlemock/source/browse/trunk/scripts/test/Makefile) file as an example on how to compile your tests -against them. - -# Extending Google Mock # - -## Writing New Matchers Quickly ## - -The `MATCHER*` family of macros can be used to define custom matchers -easily. The syntax: - -``` -MATCHER(name, "description string") { statements; } -``` - -will define a matcher with the given name that executes the -statements, which must return a `bool` to indicate if the match -succeeds. Inside the statements, you can refer to the value being -matched by `arg`, and refer to its type by `arg_type`. - -The description string documents what the matcher does, and is used to -generate the failure message when the match fails. Since a -`MATCHER()` is usually defined in a header file shared by multiple C++ -source files, we require the description to be a C-string _literal_ to -avoid possible side effects. It can be empty (`""`), in which case -Google Mock will use the sequence of words in the matcher name as the -description. - -For example: -``` -MATCHER(IsDivisibleBy7, "") { return (arg % 7) == 0; } -``` -allows you to write -``` - // Expects mock_foo.Bar(n) to be called where n is divisible by 7. - EXPECT_CALL(mock_foo, Bar(IsDivisibleBy7())); -``` -or, -``` - // Verifies that the value of some_expression is divisible by 7. - EXPECT_THAT(some_expression, IsDivisibleBy7()); -``` -If the above assertion fails, it will print something like: -``` - Value of: some_expression - Expected: is divisible by 7 - Actual: 27 -``` -where the description `"is divisible by 7"` is automatically calculated from the -matcher name `IsDivisibleBy7`. - -Optionally, you can stream additional information to a hidden argument -named `result_listener` to explain the match result. For example, a -better definition of `IsDivisibleBy7` is: -``` -MATCHER(IsDivisibleBy7, "") { - if ((arg % 7) == 0) - return true; - - *result_listener << "the remainder is " << (arg % 7); - return false; -} -``` - -With this definition, the above assertion will give a better message: -``` - Value of: some_expression - Expected: is divisible by 7 - Actual: 27 (the remainder is 6) -``` - -You should let `MatchAndExplain()` print _any additional information_ -that can help a user understand the match result. Note that it should -explain why the match succeeds in case of a success (unless it's -obvious) - this is useful when the matcher is used inside -`Not()`. There is no need to print the argument value itself, as -Google Mock already prints it for you. - -**Notes:** - - 1. The type of the value being matched (`arg_type`) is determined by the context in which you use the matcher and is supplied to you by the compiler, so you don't need to worry about declaring it (nor can you). This allows the matcher to be polymorphic. For example, `IsDivisibleBy7()` can be used to match any type where the value of `(arg % 7) == 0` can be implicitly converted to a `bool`. In the `Bar(IsDivisibleBy7())` example above, if method `Bar()` takes an `int`, `arg_type` will be `int`; if it takes an `unsigned long`, `arg_type` will be `unsigned long`; and so on. - 1. Google Mock doesn't guarantee when or how many times a matcher will be invoked. Therefore the matcher logic must be _purely functional_ (i.e. it cannot have any side effect, and the result must not depend on anything other than the value being matched and the matcher parameters). This requirement must be satisfied no matter how you define the matcher (e.g. using one of the methods described in the following recipes). In particular, a matcher can never call a mock function, as that will affect the state of the mock object and Google Mock. - -## Writing New Parameterized Matchers Quickly ## - -Sometimes you'll want to define a matcher that has parameters. For that you -can use the macro: -``` -MATCHER_P(name, param_name, "description string") { statements; } -``` - -For example: -``` -MATCHER_P(HasAbsoluteValue, value, "") { return abs(arg) == value; } -``` -will allow you to write: -``` - EXPECT_THAT(Blah("a"), HasAbsoluteValue(n)); -``` -which may lead to this message (assuming `n` is 10): -``` - Value of: Blah("a") - Expected: has absolute value 10 - Actual: -9 -``` - -Note that both the matcher description and its parameter are -printed, making the message human-friendly. - -In the matcher definition body, you can write `foo_type` to -reference the type of a parameter named `foo`. For example, in the -body of `MATCHER_P(HasAbsoluteValue, value)` above, you can write -`value_type` to refer to the type of `value`. - -Google Mock also provides `MATCHER_P2`, `MATCHER_P3`, ..., up to -`MATCHER_P10` to support multi-parameter matchers: -``` -MATCHER_Pk(name, param_1, ..., param_k, "description string") { statements; } -``` - -Please note that the custom description string is for a particular -**instance** of the matcher, where the parameters have been bound to -actual values. Therefore usually you'll want the parameter values to -be part of the description. Google Mock lets you do that using -Python-style interpolations. The following syntaxes are supported -currently: - -| `%%` | a single `%` character | -|:-----|:-----------------------| -| `%(*)s` | all parameters of the matcher printed as a tuple | -| `%(foo)s` | value of the matcher parameter named `foo` | - -For example, -``` - MATCHER_P2(InClosedRange, low, hi, "is in range [%(low)s, %(hi)s]") { - return low <= arg && arg <= hi; - } - ... - EXPECT_THAT(3, InClosedRange(4, 6)); -``` -would generate a failure that contains the message: -``` - Expected: is in range [4, 6] -``` - -If you specify `""` as the description, the failure message will -contain the sequence of words in the matcher name followed by the -parameter values printed as a tuple. For example, -``` - MATCHER_P2(InClosedRange, low, hi, "") { ... } - ... - EXPECT_THAT(3, InClosedRange(4, 6)); -``` -would generate a failure that contains the text: -``` - Expected: in closed range (4, 6) -``` - -For the purpose of typing, you can view -``` -MATCHER_Pk(Foo, p1, ..., pk, "description string") { ... } -``` -as shorthand for -``` -template <typename p1_type, ..., typename pk_type> -FooMatcherPk<p1_type, ..., pk_type> -Foo(p1_type p1, ..., pk_type pk) { ... } -``` - -When you write `Foo(v1, ..., vk)`, the compiler infers the types of -the parameters `v1`, ..., and `vk` for you. If you are not happy with -the result of the type inference, you can specify the types by -explicitly instantiating the template, as in `Foo<long, bool>(5, false)`. -As said earlier, you don't get to (or need to) specify -`arg_type` as that's determined by the context in which the matcher -is used. - -You can assign the result of expression `Foo(p1, ..., pk)` to a -variable of type `FooMatcherPk<p1_type, ..., pk_type>`. This can be -useful when composing matchers. Matchers that don't have a parameter -or have only one parameter have special types: you can assign `Foo()` -to a `FooMatcher`-typed variable, and assign `Foo(p)` to a -`FooMatcherP<p_type>`-typed variable. - -While you can instantiate a matcher template with reference types, -passing the parameters by pointer usually makes your code more -readable. If, however, you still want to pass a parameter by -reference, be aware that in the failure message generated by the -matcher you will see the value of the referenced object but not its -address. - -You can overload matchers with different numbers of parameters: -``` -MATCHER_P(Blah, a, "description string 1") { ... } -MATCHER_P2(Blah, a, b, "description string 2") { ... } -``` - -While it's tempting to always use the `MATCHER*` macros when defining -a new matcher, you should also consider implementing -`MatcherInterface` or using `MakePolymorphicMatcher()` instead (see -the recipes that follow), especially if you need to use the matcher a -lot. While these approaches require more work, they give you more -control on the types of the value being matched and the matcher -parameters, which in general leads to better compiler error messages -that pay off in the long run. They also allow overloading matchers -based on parameter types (as opposed to just based on the number of -parameters). - -## Writing New Monomorphic Matchers ## - -A matcher of argument type `T` implements -`::testing::MatcherInterface<T>` and does two things: it tests whether a -value of type `T` matches the matcher, and can describe what kind of -values it matches. The latter ability is used for generating readable -error messages when expectations are violated. - -The interface looks like this: - -``` -class MatchResultListener { - public: - ... - // Streams x to the underlying ostream; does nothing if the ostream - // is NULL. - template <typename T> - MatchResultListener& operator<<(const T& x); - - // Returns the underlying ostream. - ::std::ostream* stream(); -}; - -template <typename T> -class MatcherInterface { - public: - virtual ~MatcherInterface(); - - // Returns true iff the matcher matches x; also explains the match - // result to 'listener'. - virtual bool MatchAndExplain(T x, MatchResultListener* listener) const = 0; - - // Describes this matcher to an ostream. - virtual void DescribeTo(::std::ostream* os) const = 0; - - // Describes the negation of this matcher to an ostream. - virtual void DescribeNegationTo(::std::ostream* os) const; -}; -``` - -If you need a custom matcher but `Truly()` is not a good option (for -example, you may not be happy with the way `Truly(predicate)` -describes itself, or you may want your matcher to be polymorphic as -`Eq(value)` is), you can define a matcher to do whatever you want in -two steps: first implement the matcher interface, and then define a -factory function to create a matcher instance. The second step is not -strictly needed but it makes the syntax of using the matcher nicer. - -For example, you can define a matcher to test whether an `int` is -divisible by 7 and then use it like this: -``` -using ::testing::MakeMatcher; -using ::testing::Matcher; -using ::testing::MatcherInterface; -using ::testing::MatchResultListener; - -class DivisibleBy7Matcher : public MatcherInterface<int> { - public: - virtual bool MatchAndExplain(int n, MatchResultListener* listener) const { - return (n % 7) == 0; - } - - virtual void DescribeTo(::std::ostream* os) const { - *os << "is divisible by 7"; - } - - virtual void DescribeNegationTo(::std::ostream* os) const { - *os << "is not divisible by 7"; - } -}; - -inline Matcher<int> DivisibleBy7() { - return MakeMatcher(new DivisibleBy7Matcher); -} -... - - EXPECT_CALL(foo, Bar(DivisibleBy7())); -``` - -You may improve the matcher message by streaming additional -information to the `listener` argument in `MatchAndExplain()`: - -``` -class DivisibleBy7Matcher : public MatcherInterface<int> { - public: - virtual bool MatchAndExplain(int n, - MatchResultListener* listener) const { - const int remainder = n % 7; - if (remainder != 0) { - *listener << "the remainder is " << remainder; - } - return remainder == 0; - } - ... -}; -``` - -Then, `EXPECT_THAT(x, DivisibleBy7());` may general a message like this: -``` -Value of: x -Expected: is divisible by 7 - Actual: 23 (the remainder is 2) -``` - -## Writing New Polymorphic Matchers ## - -You've learned how to write your own matchers in the previous -recipe. Just one problem: a matcher created using `MakeMatcher()` only -works for one particular type of arguments. If you want a -_polymorphic_ matcher that works with arguments of several types (for -instance, `Eq(x)` can be used to match a `value` as long as `value` == -`x` compiles -- `value` and `x` don't have to share the same type), -you can learn the trick from `<gmock/gmock-matchers.h>` but it's a bit -involved. - -Fortunately, most of the time you can define a polymorphic matcher -easily with the help of `MakePolymorphicMatcher()`. Here's how you can -define `NotNull()` as an example: - -``` -using ::testing::MakePolymorphicMatcher; -using ::testing::MatchResultListener; -using ::testing::NotNull; -using ::testing::PolymorphicMatcher; - -class NotNullMatcher { - public: - // To implement a polymorphic matcher, first define a COPYABLE class - // that has three members MatchAndExplain(), DescribeTo(), and - // DescribeNegationTo(), like the following. - - // In this example, we want to use NotNull() with any pointer, so - // MatchAndExplain() accepts a pointer of any type as its first argument. - // In general, you can define MatchAndExplain() as an ordinary method or - // a method template, or even overload it. - template <typename T> - bool MatchAndExplain(T* p, - MatchResultListener* /* listener */) const { - return p != NULL; - } - - // Describes the property of a value matching this matcher. - void DescribeTo(::std::ostream* os) const { *os << "is not NULL"; } - - // Describes the property of a value NOT matching this matcher. - void DescribeNegationTo(::std::ostream* os) const { *os << "is NULL"; } -}; - -// To construct a polymorphic matcher, pass an instance of the class -// to MakePolymorphicMatcher(). Note the return type. -inline PolymorphicMatcher<NotNullMatcher> NotNull() { - return MakePolymorphicMatcher(NotNullMatcher()); -} -... - - EXPECT_CALL(foo, Bar(NotNull())); // The argument must be a non-NULL pointer. -``` - -**Note:** Your polymorphic matcher class does **not** need to inherit from -`MatcherInterface` or any other class, and its methods do **not** need -to be virtual. - -Like in a monomorphic matcher, you may explain the match result by -streaming additional information to the `listener` argument in -`MatchAndExplain()`. - -## Writing New Cardinalities ## - -A cardinality is used in `Times()` to tell Google Mock how many times -you expect a call to occur. It doesn't have to be exact. For example, -you can say `AtLeast(5)` or `Between(2, 4)`. - -If the built-in set of cardinalities doesn't suit you, you are free to -define your own by implementing the following interface (in namespace -`testing`): - -``` -class CardinalityInterface { - public: - virtual ~CardinalityInterface(); - - // Returns true iff call_count calls will satisfy this cardinality. - virtual bool IsSatisfiedByCallCount(int call_count) const = 0; - - // Returns true iff call_count calls will saturate this cardinality. - virtual bool IsSaturatedByCallCount(int call_count) const = 0; - - // Describes self to an ostream. - virtual void DescribeTo(::std::ostream* os) const = 0; -}; -``` - -For example, to specify that a call must occur even number of times, -you can write - -``` -using ::testing::Cardinality; -using ::testing::CardinalityInterface; -using ::testing::MakeCardinality; - -class EvenNumberCardinality : public CardinalityInterface { - public: - virtual bool IsSatisfiedByCallCount(int call_count) const { - return (call_count % 2) == 0; - } - - virtual bool IsSaturatedByCallCount(int call_count) const { - return false; - } - - virtual void DescribeTo(::std::ostream* os) const { - *os << "called even number of times"; - } -}; - -Cardinality EvenNumber() { - return MakeCardinality(new EvenNumberCardinality); -} -... - - EXPECT_CALL(foo, Bar(3)) - .Times(EvenNumber()); -``` - -## Writing New Actions Quickly ## - -If the built-in actions don't work for you, and you find it -inconvenient to use `Invoke()`, you can use a macro from the `ACTION*` -family to quickly define a new action that can be used in your code as -if it's a built-in action. - -By writing -``` -ACTION(name) { statements; } -``` -in a namespace scope (i.e. not inside a class or function), you will -define an action with the given name that executes the statements. -The value returned by `statements` will be used as the return value of -the action. Inside the statements, you can refer to the K-th -(0-based) argument of the mock function as `argK`. For example: -``` -ACTION(IncrementArg1) { return ++(*arg1); } -``` -allows you to write -``` -... WillOnce(IncrementArg1()); -``` - -Note that you don't need to specify the types of the mock function -arguments. Rest assured that your code is type-safe though: -you'll get a compiler error if `*arg1` doesn't support the `++` -operator, or if the type of `++(*arg1)` isn't compatible with the mock -function's return type. - -Another example: -``` -ACTION(Foo) { - (*arg2)(5); - Blah(); - *arg1 = 0; - return arg0; -} -``` -defines an action `Foo()` that invokes argument #2 (a function pointer) -with 5, calls function `Blah()`, sets the value pointed to by argument -#1 to 0, and returns argument #0. - -For more convenience and flexibility, you can also use the following -pre-defined symbols in the body of `ACTION`: - -| `argK_type` | The type of the K-th (0-based) argument of the mock function | -|:------------|:-------------------------------------------------------------| -| `args` | All arguments of the mock function as a tuple | -| `args_type` | The type of all arguments of the mock function as a tuple | -| `return_type` | The return type of the mock function | -| `function_type` | The type of the mock function | - -For example, when using an `ACTION` as a stub action for mock function: -``` -int DoSomething(bool flag, int* ptr); -``` -we have: -| **Pre-defined Symbol** | **Is Bound To** | -|:-----------------------|:----------------| -| `arg0` | the value of `flag` | -| `arg0_type` | the type `bool` | -| `arg1` | the value of `ptr` | -| `arg1_type` | the type `int*` | -| `args` | the tuple `(flag, ptr)` | -| `args_type` | the type `std::tr1::tuple<bool, int*>` | -| `return_type` | the type `int` | -| `function_type` | the type `int(bool, int*)` | - -## Writing New Parameterized Actions Quickly ## - -Sometimes you'll want to parameterize an action you define. For that -we have another macro -``` -ACTION_P(name, param) { statements; } -``` - -For example, -``` -ACTION_P(Add, n) { return arg0 + n; } -``` -will allow you to write -``` -// Returns argument #0 + 5. -... WillOnce(Add(5)); -``` - -For convenience, we use the term _arguments_ for the values used to -invoke the mock function, and the term _parameters_ for the values -used to instantiate an action. - -Note that you don't need to provide the type of the parameter either. -Suppose the parameter is named `param`, you can also use the -Google-Mock-defined symbol `param_type` to refer to the type of the -parameter as inferred by the compiler. For example, in the body of -`ACTION_P(Add, n)` above, you can write `n_type` for the type of `n`. - -Google Mock also provides `ACTION_P2`, `ACTION_P3`, and etc to support -multi-parameter actions. For example, -``` -ACTION_P2(ReturnDistanceTo, x, y) { - double dx = arg0 - x; - double dy = arg1 - y; - return sqrt(dx*dx + dy*dy); -} -``` -lets you write -``` -... WillOnce(ReturnDistanceTo(5.0, 26.5)); -``` - -You can view `ACTION` as a degenerated parameterized action where the -number of parameters is 0. - -You can also easily define actions overloaded on the number of parameters: -``` -ACTION_P(Plus, a) { ... } -ACTION_P2(Plus, a, b) { ... } -``` - -## Restricting the Type of an Argument or Parameter in an ACTION ## - -For maximum brevity and reusability, the `ACTION*` macros don't ask -you to provide the types of the mock function arguments and the action -parameters. Instead, we let the compiler infer the types for us. - -Sometimes, however, we may want to be more explicit about the types. -There are several tricks to do that. For example: -``` -ACTION(Foo) { - // Makes sure arg0 can be converted to int. - int n = arg0; - ... use n instead of arg0 here ... -} - -ACTION_P(Bar, param) { - // Makes sure the type of arg1 is const char*. - ::testing::StaticAssertTypeEq<const char*, arg1_type>(); - - // Makes sure param can be converted to bool. - bool flag = param; -} -``` -where `StaticAssertTypeEq` is a compile-time assertion in Google Test -that verifies two types are the same. - -## Writing New Action Templates Quickly ## - -Sometimes you want to give an action explicit template parameters that -cannot be inferred from its value parameters. `ACTION_TEMPLATE()` -supports that and can be viewed as an extension to `ACTION()` and -`ACTION_P*()`. - -The syntax: -``` -ACTION_TEMPLATE(ActionName, - HAS_m_TEMPLATE_PARAMS(kind1, name1, ..., kind_m, name_m), - AND_n_VALUE_PARAMS(p1, ..., p_n)) { statements; } -``` - -defines an action template that takes _m_ explicit template parameters -and _n_ value parameters, where _m_ is between 1 and 10, and _n_ is -between 0 and 10. `name_i` is the name of the i-th template -parameter, and `kind_i` specifies whether it's a `typename`, an -integral constant, or a template. `p_i` is the name of the i-th value -parameter. - -Example: -``` -// DuplicateArg<k, T>(output) converts the k-th argument of the mock -// function to type T and copies it to *output. -ACTION_TEMPLATE(DuplicateArg, - // Note the comma between int and k: - HAS_2_TEMPLATE_PARAMS(int, k, typename, T), - AND_1_VALUE_PARAMS(output)) { - *output = T(std::tr1::get<k>(args)); -} -``` - -To create an instance of an action template, write: -``` - ActionName<t1, ..., t_m>(v1, ..., v_n) -``` -where the `t`s are the template arguments and the -`v`s are the value arguments. The value argument -types are inferred by the compiler. For example: -``` -using ::testing::_; -... - int n; - EXPECT_CALL(mock, Foo(_, _)) - .WillOnce(DuplicateArg<1, unsigned char>(&n)); -``` - -If you want to explicitly specify the value argument types, you can -provide additional template arguments: -``` - ActionName<t1, ..., t_m, u1, ..., u_k>(v1, ..., v_n) -``` -where `u_i` is the desired type of `v_i`. - -`ACTION_TEMPLATE` and `ACTION`/`ACTION_P*` can be overloaded on the -number of value parameters, but not on the number of template -parameters. Without the restriction, the meaning of the following is -unclear: - -``` - OverloadedAction<int, bool>(x); -``` - -Are we using a single-template-parameter action where `bool` refers to -the type of `x`, or a two-template-parameter action where the compiler -is asked to infer the type of `x`? - -## Using the ACTION Object's Type ## - -If you are writing a function that returns an `ACTION` object, you'll -need to know its type. The type depends on the macro used to define -the action and the parameter types. The rule is relatively simple: -| **Given Definition** | **Expression** | **Has Type** | -|:---------------------|:---------------|:-------------| -| `ACTION(Foo)` | `Foo()` | `FooAction` | -| `ACTION_TEMPLATE(Foo, HAS_m_TEMPLATE_PARAMS(...), AND_0_VALUE_PARAMS())` | `Foo<t1, ..., t_m>()` | `FooAction<t1, ..., t_m>` | -| `ACTION_P(Bar, param)` | `Bar(int_value)` | `BarActionP<int>` | -| `ACTION_TEMPLATE(Bar, HAS_m_TEMPLATE_PARAMS(...), AND_1_VALUE_PARAMS(p1))` | `Bar<t1, ..., t_m>(int_value)` | `FooActionP<t1, ..., t_m, int>` | -| `ACTION_P2(Baz, p1, p2)` | `Baz(bool_value, int_value)` | `BazActionP2<bool, int>` | -| `ACTION_TEMPLATE(Baz, HAS_m_TEMPLATE_PARAMS(...), AND_2_VALUE_PARAMS(p1, p2))` | `Baz<t1, ..., t_m>(bool_value, int_value)` | `FooActionP2<t1, ..., t_m, bool, int>` | -| ... | ... | ... | - -Note that we have to pick different suffixes (`Action`, `ActionP`, -`ActionP2`, and etc) for actions with different numbers of value -parameters, or the action definitions cannot be overloaded on the -number of them. - -## Writing New Monomorphic Actions ## - -While the `ACTION*` macros are very convenient, sometimes they are -inappropriate. For example, despite the tricks shown in the previous -recipes, they don't let you directly specify the types of the mock -function arguments and the action parameters, which in general leads -to unoptimized compiler error messages that can baffle unfamiliar -users. They also don't allow overloading actions based on parameter -types without jumping through some hoops. - -An alternative to the `ACTION*` macros is to implement -`::testing::ActionInterface<F>`, where `F` is the type of the mock -function in which the action will be used. For example: - -``` -template <typename F>class ActionInterface { - public: - virtual ~ActionInterface(); - - // Performs the action. Result is the return type of function type - // F, and ArgumentTuple is the tuple of arguments of F. - // - // For example, if F is int(bool, const string&), then Result would - // be int, and ArgumentTuple would be tr1::tuple<bool, const string&>. - virtual Result Perform(const ArgumentTuple& args) = 0; -}; - -using ::testing::_; -using ::testing::Action; -using ::testing::ActionInterface; -using ::testing::MakeAction; - -typedef int IncrementMethod(int*); - -class IncrementArgumentAction : public ActionInterface<IncrementMethod> { - public: - virtual int Perform(const tr1::tuple<int*>& args) { - int* p = tr1::get<0>(args); // Grabs the first argument. - return *p++; - } -}; - -Action<IncrementMethod> IncrementArgument() { - return MakeAction(new IncrementArgumentAction); -} -... - - EXPECT_CALL(foo, Baz(_)) - .WillOnce(IncrementArgument()); - - int n = 5; - foo.Baz(&n); // Should return 5 and change n to 6. -``` - -## Writing New Polymorphic Actions ## - -The previous recipe showed you how to define your own action. This is -all good, except that you need to know the type of the function in -which the action will be used. Sometimes that can be a problem. For -example, if you want to use the action in functions with _different_ -types (e.g. like `Return()` and `SetArgumentPointee()`). - -If an action can be used in several types of mock functions, we say -it's _polymorphic_. The `MakePolymorphicAction()` function template -makes it easy to define such an action: - -``` -namespace testing { - -template <typename Impl> -PolymorphicAction<Impl> MakePolymorphicAction(const Impl& impl); - -} // namespace testing -``` - -As an example, let's define an action that returns the second argument -in the mock function's argument list. The first step is to define an -implementation class: - -``` -class ReturnSecondArgumentAction { - public: - template <typename Result, typename ArgumentTuple> - Result Perform(const ArgumentTuple& args) const { - // To get the i-th (0-based) argument, use tr1::get<i>(args). - return tr1::get<1>(args); - } -}; -``` - -This implementation class does _not_ need to inherit from any -particular class. What matters is that it must have a `Perform()` -method template. This method template takes the mock function's -arguments as a tuple in a **single** argument, and returns the result of -the action. It can be either `const` or not, but must be invokable -with exactly one template argument, which is the result type. In other -words, you must be able to call `Perform<R>(args)` where `R` is the -mock function's return type and `args` is its arguments in a tuple. - -Next, we use `MakePolymorphicAction()` to turn an instance of the -implementation class into the polymorphic action we need. It will be -convenient to have a wrapper for this: - -``` -using ::testing::MakePolymorphicAction; -using ::testing::PolymorphicAction; - -PolymorphicAction<ReturnSecondArgumentAction> ReturnSecondArgument() { - return MakePolymorphicAction(ReturnSecondArgumentAction()); -} -``` - -Now, you can use this polymorphic action the same way you use the -built-in ones: - -``` -using ::testing::_; - -class MockFoo : public Foo { - public: - MOCK_METHOD2(DoThis, int(bool flag, int n)); - MOCK_METHOD3(DoThat, string(int x, const char* str1, const char* str2)); -}; -... - - MockFoo foo; - EXPECT_CALL(foo, DoThis(_, _)) - .WillOnce(ReturnSecondArgument()); - EXPECT_CALL(foo, DoThat(_, _, _)) - .WillOnce(ReturnSecondArgument()); - ... - foo.DoThis(true, 5); // Will return 5. - foo.DoThat(1, "Hi", "Bye"); // Will return "Hi". -``` - -## Teaching Google Mock How to Print Your Values ## - -When an uninteresting or unexpected call occurs, Google Mock prints -the argument values to help you debug. The `EXPECT_THAT` and -`ASSERT_THAT` assertions also print the value being validated when the -test fails. Google Mock does this using the user-extensible value -printer defined in `<gmock/gmock-printers.h>`. - -This printer knows how to print the built-in C++ types, native arrays, -STL containers, and any type that supports the `<<` operator. For -other types, it prints the raw bytes in the value and hope you the -user can figure it out. - -Did I say that the printer is `extensible`? That means you can teach -it to do a better job at printing your particular type than to dump -the bytes. To do that, you just need to define `<<` for your type: - -``` -#include <iostream> - -namespace foo { - -class Foo { ... }; - -// It's important that the << operator is defined in the SAME -// namespace that defines Foo. C++'s look-up rules rely on that. -::std::ostream& operator<<(::std::ostream& os, const Foo& foo) { - return os << foo.DebugString(); // Whatever needed to print foo to os. -} - -} // namespace foo -``` - -Sometimes, this might not be an option. For example, your team may -consider it dangerous or bad style to have a `<<` operator for `Foo`, -or `Foo` may already have a `<<` operator that doesn't do what you -want (and you cannot change it). Don't despair though - Google Mock -gives you a second chance to get it right. Namely, you can define a -`PrintTo()` function like this: - -``` -#include <iostream> - -namespace foo { - -class Foo { ... }; - -// It's important that PrintTo() is defined in the SAME -// namespace that defines Foo. C++'s look-up rules rely on that. -void PrintTo(const Foo& foo, ::std::ostream* os) { - *os << foo.DebugString(); // Whatever needed to print foo to os. -} - -} // namespace foo -``` - -What if you have both `<<` and `PrintTo()`? In this case, the latter -will override the former when Google Mock is concerned. This allows -you to customize how the value should appear in Google Mock's output -without affecting code that relies on the behavior of its `<<` -operator. - -**Note:** When printing a pointer of type `T*`, Google Mock calls -`PrintTo(T*, std::ostream* os)` instead of `operator<<(std::ostream&, T*)`. -Therefore the only way to affect how a pointer is printed by Google -Mock is to define `PrintTo()` for it. Also note that `T*` and `const T*` -are different types, so you may need to define `PrintTo()` for both. - -Why does Google Mock treat pointers specially? There are several reasons: - - * We cannot use `operator<<` to print a `signed char*` or `unsigned char*`, since it will print the pointer as a NUL-terminated C string, which likely will cause an access violation. - * We want `NULL` pointers to be printed as `"NULL"`, but `operator<<` prints it as `"0"`, `"nullptr"`, or something else, depending on the compiler. - * With some compilers, printing a `NULL` `char*` using `operator<<` will segfault. - * `operator<<` prints a function pointer as a `bool` (hence it always prints `"1"`), which is not very useful.
\ No newline at end of file diff --git a/googlemock/docs/v1_5/Documentation.md b/googlemock/docs/v1_5/Documentation.md deleted file mode 100644 index 315b0a2..0000000 --- a/googlemock/docs/v1_5/Documentation.md +++ /dev/null @@ -1,11 +0,0 @@ -This page lists all documentation wiki pages for Google Mock **version 1.5.0** -- **if you use a different version of Google Mock, please read the documentation for that specific version instead.** - - * [ForDummies](V1_5_ForDummies.md) -- start here if you are new to Google Mock. - * [CheatSheet](V1_5_CheatSheet.md) -- a quick reference. - * [CookBook](V1_5_CookBook.md) -- recipes for doing various tasks using Google Mock. - * [FrequentlyAskedQuestions](V1_5_FrequentlyAskedQuestions.md) -- check here before asking a question on the mailing list. - -To contribute code to Google Mock, read: - - * DevGuide -- read this _before_ writing your first patch. - * [Pump Manual](http://code.google.com/p/googletest/wiki/PumpManual) -- how we generate some of Google Mock's source files.
\ No newline at end of file diff --git a/googlemock/docs/v1_5/ForDummies.md b/googlemock/docs/v1_5/ForDummies.md deleted file mode 100644 index fcc3b56..0000000 --- a/googlemock/docs/v1_5/ForDummies.md +++ /dev/null @@ -1,439 +0,0 @@ - - -(**Note:** If you get compiler errors that you don't understand, be sure to consult [Google Mock Doctor](V1_5_FrequentlyAskedQuestions#How_am_I_supposed_to_make_sense_of_these_horrible_template_error.md).) - -# What Is Google C++ Mocking Framework? # -When you write a prototype or test, often it's not feasible or wise to rely on real objects entirely. A **mock object** implements the same interface as a real object (so it can be used as one), but lets you specify at run time how it will be used and what it should do (which methods will be called? in which order? how many times? with what arguments? what will they return? etc). - -**Note:** It is easy to confuse the term _fake objects_ with mock objects. Fakes and mocks actually mean very different things in the Test-Driven Development (TDD) community: - - * **Fake** objects have working implementations, but usually take some shortcut (perhaps to make the operations less expensive), which makes them not suitable for production. An in-memory file system would be an example of a fake. - * **Mocks** are objects pre-programmed with _expectations_, which form a specification of the calls they are expected to receive. - -If all this seems too abstract for you, don't worry - the most important thing to remember is that a mock allows you to check the _interaction_ between itself and code that uses it. The difference between fakes and mocks will become much clearer once you start to use mocks. - -**Google C++ Mocking Framework** (or **Google Mock** for short) is a library (sometimes we also call it a "framework" to make it sound cool) for creating mock classes and using them. It does to C++ what [jMock](http://www.jmock.org/) and [EasyMock](http://www.easymock.org/) do to Java. - -Using Google Mock involves three basic steps: - - 1. Use some simple macros to describe the interface you want to mock, and they will expand to the implementation of your mock class; - 1. Create some mock objects and specify its expectations and behavior using an intuitive syntax; - 1. Exercise code that uses the mock objects. Google Mock will catch any violation of the expectations as soon as it arises. - -# Why Google Mock? # -While mock objects help you remove unnecessary dependencies in tests and make them fast and reliable, using mocks manually in C++ is _hard_: - - * Someone has to implement the mocks. The job is usually tedious and error-prone. No wonder people go great distance to avoid it. - * The quality of those manually written mocks is a bit, uh, unpredictable. You may see some really polished ones, but you may also see some that were hacked up in a hurry and have all sorts of ad hoc restrictions. - * The knowledge you gained from using one mock doesn't transfer to the next. - -In contrast, Java and Python programmers have some fine mock frameworks, which automate the creation of mocks. As a result, mocking is a proven effective technique and widely adopted practice in those communities. Having the right tool absolutely makes the difference. - -Google Mock was built to help C++ programmers. It was inspired by [jMock](http://www.jmock.org/) and [EasyMock](http://www.easymock.org/), but designed with C++'s specifics in mind. It is your friend if any of the following problems is bothering you: - - * You are stuck with a sub-optimal design and wish you had done more prototyping before it was too late, but prototyping in C++ is by no means "rapid". - * Your tests are slow as they depend on too many libraries or use expensive resources (e.g. a database). - * Your tests are brittle as some resources they use are unreliable (e.g. the network). - * You want to test how your code handles a failure (e.g. a file checksum error), but it's not easy to cause one. - * You need to make sure that your module interacts with other modules in the right way, but it's hard to observe the interaction; therefore you resort to observing the side effects at the end of the action, which is awkward at best. - * You want to "mock out" your dependencies, except that they don't have mock implementations yet; and, frankly, you aren't thrilled by some of those hand-written mocks. - -We encourage you to use Google Mock as: - - * a _design_ tool, for it lets you experiment with your interface design early and often. More iterations lead to better designs! - * a _testing_ tool to cut your tests' outbound dependencies and probe the interaction between your module and its collaborators. - -# Getting Started # -Using Google Mock is easy! Inside your C++ source file, just `#include` `<gtest/gtest.h>` and `<gmock/gmock.h>`, and you are ready to go. - -# A Case for Mock Turtles # -Let's look at an example. Suppose you are developing a graphics program that relies on a LOGO-like API for drawing. How would you test that it does the right thing? Well, you can run it and compare the screen with a golden screen snapshot, but let's admit it: tests like this are expensive to run and fragile (What if you just upgraded to a shiny new graphics card that has better anti-aliasing? Suddenly you have to update all your golden images.). It would be too painful if all your tests are like this. Fortunately, you learned about Dependency Injection and know the right thing to do: instead of having your application talk to the drawing API directly, wrap the API in an interface (say, `Turtle`) and code to that interface: - -``` -class Turtle { - ... - virtual ~Turtle() {} - virtual void PenUp() = 0; - virtual void PenDown() = 0; - virtual void Forward(int distance) = 0; - virtual void Turn(int degrees) = 0; - virtual void GoTo(int x, int y) = 0; - virtual int GetX() const = 0; - virtual int GetY() const = 0; -}; -``` - -(Note that the destructor of `Turtle` **must** be virtual, as is the case for **all** classes you intend to inherit from - otherwise the destructor of the derived class will not be called when you delete an object through a base pointer, and you'll get corrupted program states like memory leaks.) - -You can control whether the turtle's movement will leave a trace using `PenUp()` and `PenDown()`, and control its movement using `Forward()`, `Turn()`, and `GoTo()`. Finally, `GetX()` and `GetY()` tell you the current position of the turtle. - -Your program will normally use a real implementation of this interface. In tests, you can use a mock implementation instead. This allows you to easily check what drawing primitives your program is calling, with what arguments, and in which order. Tests written this way are much more robust (they won't break because your new machine does anti-aliasing differently), easier to read and maintain (the intent of a test is expressed in the code, not in some binary images), and run _much, much faster_. - -# Writing the Mock Class # -If you are lucky, the mocks you need to use have already been implemented by some nice people. If, however, you find yourself in the position to write a mock class, relax - Google Mock turns this task into a fun game! (Well, almost.) - -## How to Define It ## -Using the `Turtle` interface as example, here are the simple steps you need to follow: - - 1. Derive a class `MockTurtle` from `Turtle`. - 1. Take a virtual function of `Turtle`. Count how many arguments it has. - 1. In the `public:` section of the child class, write `MOCK_METHODn();` (or `MOCK_CONST_METHODn();` if you are mocking a `const` method), where `n` is the number of the arguments; if you counted wrong, shame on you, and a compiler error will tell you so. - 1. Now comes the fun part: you take the function signature, cut-and-paste the _function name_ as the _first_ argument to the macro, and leave what's left as the _second_ argument (in case you're curious, this is the _type of the function_). - 1. Repeat until all virtual functions you want to mock are done. - -After the process, you should have something like: - -``` -#include <gmock/gmock.h> // Brings in Google Mock. -class MockTurtle : public Turtle { - public: - ... - MOCK_METHOD0(PenUp, void()); - MOCK_METHOD0(PenDown, void()); - MOCK_METHOD1(Forward, void(int distance)); - MOCK_METHOD1(Turn, void(int degrees)); - MOCK_METHOD2(GoTo, void(int x, int y)); - MOCK_CONST_METHOD0(GetX, int()); - MOCK_CONST_METHOD0(GetY, int()); -}; -``` - -You don't need to define these mock methods somewhere else - the `MOCK_METHOD*` macros will generate the definitions for you. It's that simple! Once you get the hang of it, you can pump out mock classes faster than your source-control system can handle your check-ins. - -**Tip:** If even this is too much work for you, you'll find the -`gmock_gen.py` tool in Google Mock's `scripts/generator/` directory (courtesy of the [cppclean](http://code.google.com/p/cppclean/) project) useful. This command-line -tool requires that you have Python 2.4 installed. You give it a C++ file and the name of an abstract class defined in it, -and it will print the definition of the mock class for you. Due to the -complexity of the C++ language, this script may not always work, but -it can be quite handy when it does. For more details, read the [user documentation](http://code.google.com/p/googlemock/source/browse/trunk/scripts/generator/README). - -## Where to Put It ## -When you define a mock class, you need to decide where to put its definition. Some people put it in a `*_test.cc`. This is fine when the interface being mocked (say, `Foo`) is owned by the same person or team. Otherwise, when the owner of `Foo` changes it, your test could break. (You can't really expect `Foo`'s maintainer to fix every test that uses `Foo`, can you?) - -So, the rule of thumb is: if you need to mock `Foo` and it's owned by others, define the mock class in `Foo`'s package (better, in a `testing` sub-package such that you can clearly separate production code and testing utilities), and put it in a `mock_foo.h`. Then everyone can reference `mock_foo.h` from their tests. If `Foo` ever changes, there is only one copy of `MockFoo` to change, and only tests that depend on the changed methods need to be fixed. - -Another way to do it: you can introduce a thin layer `FooAdaptor` on top of `Foo` and code to this new interface. Since you own `FooAdaptor`, you can absorb changes in `Foo` much more easily. While this is more work initially, carefully choosing the adaptor interface can make your code easier to write and more readable (a net win in the long run), as you can choose `FooAdaptor` to fit your specific domain much better than `Foo` does. - -# Using Mocks in Tests # -Once you have a mock class, using it is easy. The typical work flow is: - - 1. Import the Google Mock names from the `testing` namespace such that you can use them unqualified (You only have to do it once per file. Remember that namespaces are a good idea and good for your health.). - 1. Create some mock objects. - 1. Specify your expectations on them (How many times will a method be called? With what arguments? What should it do? etc.). - 1. Exercise some code that uses the mocks; optionally, check the result using Google Test assertions. If a mock method is called more than expected or with wrong arguments, you'll get an error immediately. - 1. When a mock is destructed, Google Mock will automatically check whether all expectations on it have been satisfied. - -Here's an example: - -``` -#include "path/to/mock-turtle.h" -#include <gmock/gmock.h> -#include <gtest/gtest.h> -using ::testing::AtLeast; // #1 - -TEST(PainterTest, CanDrawSomething) { - MockTurtle turtle; // #2 - EXPECT_CALL(turtle, PenDown()) // #3 - .Times(AtLeast(1)); - - Painter painter(&turtle); // #4 - - EXPECT_TRUE(painter.DrawCircle(0, 0, 10)); -} // #5 - -int main(int argc, char** argv) { - // The following line must be executed to initialize Google Mock - // (and Google Test) before running the tests. - ::testing::InitGoogleMock(&argc, argv); - return RUN_ALL_TESTS(); -} -``` - -As you might have guessed, this test checks that `PenDown()` is called at least once. If the `painter` object didn't call this method, your test will fail with a message like this: - -``` -path/to/my_test.cc:119: Failure -Actual function call count doesn't match this expectation: -Actually: never called; -Expected: called at least once. -``` - -**Tip 1:** If you run the test from an Emacs buffer, you can hit `<Enter>` on the line number displayed in the error message to jump right to the failed expectation. - -**Tip 2:** If your mock objects are never deleted, the final verification won't happen. Therefore it's a good idea to use a heap leak checker in your tests when you allocate mocks on the heap. - -**Important note:** Google Mock requires expectations to be set **before** the mock functions are called, otherwise the behavior is **undefined**. In particular, you mustn't interleave `EXPECT_CALL()`s and calls to the mock functions. - -This means `EXPECT_CALL()` should be read as expecting that a call will occur _in the future_, not that a call has occurred. Why does Google Mock work like that? Well, specifying the expectation beforehand allows Google Mock to report a violation as soon as it arises, when the context (stack trace, etc) is still available. This makes debugging much easier. - -Admittedly, this test is contrived and doesn't do much. You can easily achieve the same effect without using Google Mock. However, as we shall reveal soon, Google Mock allows you to do _much more_ with the mocks. - -## Using Google Mock with Any Testing Framework ## -If you want to use something other than Google Test (e.g. [CppUnit](http://apps.sourceforge.net/mediawiki/cppunit/index.php?title=Main_Page) or -[CxxTest](http://cxxtest.tigris.org/)) as your testing framework, just change the `main()` function in the previous section to: -``` -int main(int argc, char** argv) { - // The following line causes Google Mock to throw an exception on failure, - // which will be interpreted by your testing framework as a test failure. - ::testing::GTEST_FLAG(throw_on_failure) = true; - ::testing::InitGoogleMock(&argc, argv); - ... whatever your testing framework requires ... -} -``` - -This approach has a catch: it makes Google Mock throw an exception -from a mock object's destructor sometimes. With some compilers, this -sometimes causes the test program to crash. You'll still be able to -notice that the test has failed, but it's not a graceful failure. - -A better solution is to use Google Test's -[event listener API](http://code.google.com/p/googletest/wiki/GoogleTestAdvancedGuide#Extending_Google_Test_by_Handling_Test_Events) -to report a test failure to your testing framework properly. You'll need to -implement the `OnTestPartResult()` method of the event listener interface, but it -should be straightforward. - -If this turns out to be too much work, we suggest that you stick with -Google Test, which works with Google Mock seamlessly (in fact, it is -technically part of Google Mock.). If there is a reason that you -cannot use Google Test, please let us know. - -# Setting Expectations # -The key to using a mock object successfully is to set the _right expectations_ on it. If you set the expectations too strict, your test will fail as the result of unrelated changes. If you set them too loose, bugs can slip through. You want to do it just right such that your test can catch exactly the kind of bugs you intend it to catch. Google Mock provides the necessary means for you to do it "just right." - -## General Syntax ## -In Google Mock we use the `EXPECT_CALL()` macro to set an expectation on a mock method. The general syntax is: - -``` -EXPECT_CALL(mock_object, method(matchers)) - .Times(cardinality) - .WillOnce(action) - .WillRepeatedly(action); -``` - -The macro has two arguments: first the mock object, and then the method and its arguments. Note that the two are separated by a comma (`,`), not a period (`.`). (Why using a comma? The answer is that it was necessary for technical reasons.) - -The macro can be followed by some optional _clauses_ that provide more information about the expectation. We'll discuss how each clause works in the coming sections. - -This syntax is designed to make an expectation read like English. For example, you can probably guess that - -``` -using ::testing::Return;... -EXPECT_CALL(turtle, GetX()) - .Times(5) - .WillOnce(Return(100)) - .WillOnce(Return(150)) - .WillRepeatedly(Return(200)); -``` - -says that the `turtle` object's `GetX()` method will be called five times, it will return 100 the first time, 150 the second time, and then 200 every time. Some people like to call this style of syntax a Domain-Specific Language (DSL). - -**Note:** Why do we use a macro to do this? It serves two purposes: first it makes expectations easily identifiable (either by `grep` or by a human reader), and second it allows Google Mock to include the source file location of a failed expectation in messages, making debugging easier. - -## Matchers: What Arguments Do We Expect? ## -When a mock function takes arguments, we must specify what arguments we are expecting; for example: - -``` -// Expects the turtle to move forward by 100 units. -EXPECT_CALL(turtle, Forward(100)); -``` - -Sometimes you may not want to be too specific (Remember that talk about tests being too rigid? Over specification leads to brittle tests and obscures the intent of tests. Therefore we encourage you to specify only what's necessary - no more, no less.). If you care to check that `Forward()` will be called but aren't interested in its actual argument, write `_` as the argument, which means "anything goes": - -``` -using ::testing::_; -... -// Expects the turtle to move forward. -EXPECT_CALL(turtle, Forward(_)); -``` - -`_` is an instance of what we call **matchers**. A matcher is like a predicate and can test whether an argument is what we'd expect. You can use a matcher inside `EXPECT_CALL()` wherever a function argument is expected. - -A list of built-in matchers can be found in the [CheatSheet](V1_5_CheatSheet.md). For example, here's the `Ge` (greater than or equal) matcher: - -``` -using ::testing::Ge;... -EXPECT_CALL(turtle, Forward(Ge(100))); -``` - -This checks that the turtle will be told to go forward by at least 100 units. - -## Cardinalities: How Many Times Will It Be Called? ## -The first clause we can specify following an `EXPECT_CALL()` is `Times()`. We call its argument a **cardinality** as it tells _how many times_ the call should occur. It allows us to repeat an expectation many times without actually writing it as many times. More importantly, a cardinality can be "fuzzy", just like a matcher can be. This allows a user to express the intent of a test exactly. - -An interesting special case is when we say `Times(0)`. You may have guessed - it means that the function shouldn't be called with the given arguments at all, and Google Mock will report a Google Test failure whenever the function is (wrongfully) called. - -We've seen `AtLeast(n)` as an example of fuzzy cardinalities earlier. For the list of built-in cardinalities you can use, see the [CheatSheet](V1_5_CheatSheet.md). - -The `Times()` clause can be omitted. **If you omit `Times()`, Google Mock will infer the cardinality for you.** The rules are easy to remember: - - * If **neither** `WillOnce()` **nor** `WillRepeatedly()` is in the `EXPECT_CALL()`, the inferred cardinality is `Times(1)`. - * If there are `n WillOnce()`'s but **no** `WillRepeatedly()`, where `n` >= 1, the cardinality is `Times(n)`. - * If there are `n WillOnce()`'s and **one** `WillRepeatedly()`, where `n` >= 0, the cardinality is `Times(AtLeast(n))`. - -**Quick quiz:** what do you think will happen if a function is expected to be called twice but actually called four times? - -## Actions: What Should It Do? ## -Remember that a mock object doesn't really have a working implementation? We as users have to tell it what to do when a method is invoked. This is easy in Google Mock. - -First, if the return type of a mock function is a built-in type or a pointer, the function has a **default action** (a `void` function will just return, a `bool` function will return `false`, and other functions will return 0). If you don't say anything, this behavior will be used. - -Second, if a mock function doesn't have a default action, or the default action doesn't suit you, you can specify the action to be taken each time the expectation matches using a series of `WillOnce()` clauses followed by an optional `WillRepeatedly()`. For example, - -``` -using ::testing::Return;... -EXPECT_CALL(turtle, GetX()) - .WillOnce(Return(100)) - .WillOnce(Return(200)) - .WillOnce(Return(300)); -``` - -This says that `turtle.GetX()` will be called _exactly three times_ (Google Mock inferred this from how many `WillOnce()` clauses we've written, since we didn't explicitly write `Times()`), and will return 100, 200, and 300 respectively. - -``` -using ::testing::Return;... -EXPECT_CALL(turtle, GetY()) - .WillOnce(Return(100)) - .WillOnce(Return(200)) - .WillRepeatedly(Return(300)); -``` - -says that `turtle.GetY()` will be called _at least twice_ (Google Mock knows this as we've written two `WillOnce()` clauses and a `WillRepeatedly()` while having no explicit `Times()`), will return 100 the first time, 200 the second time, and 300 from the third time on. - -Of course, if you explicitly write a `Times()`, Google Mock will not try to infer the cardinality itself. What if the number you specified is larger than there are `WillOnce()` clauses? Well, after all `WillOnce()`s are used up, Google Mock will do the _default_ action for the function every time (unless, of course, you have a `WillRepeatedly()`.). - -What can we do inside `WillOnce()` besides `Return()`? You can return a reference using `ReturnRef(variable)`, or invoke a pre-defined function, among [others](V1_5_CheatSheet#Actions.md). - -**Important note:** The `EXPECT_CALL()` statement evaluates the action clause only once, even though the action may be performed many times. Therefore you must be careful about side effects. The following may not do what you want: - -``` -int n = 100; -EXPECT_CALL(turtle, GetX()) -.Times(4) -.WillOnce(Return(n++)); -``` - -Instead of returning 100, 101, 102, ..., consecutively, this mock function will always return 100 as `n++` is only evaluated once. Similarly, `Return(new Foo)` will create a new `Foo` object when the `EXPECT_CALL()` is executed, and will return the same pointer every time. If you want the side effect to happen every time, you need to define a custom action, which we'll teach in the [CookBook](V1_5_CookBook.md). - -Time for another quiz! What do you think the following means? - -``` -using ::testing::Return;... -EXPECT_CALL(turtle, GetY()) -.Times(4) -.WillOnce(Return(100)); -``` - -Obviously `turtle.GetY()` is expected to be called four times. But if you think it will return 100 every time, think twice! Remember that one `WillOnce()` clause will be consumed each time the function is invoked and the default action will be taken afterwards. So the right answer is that `turtle.GetY()` will return 100 the first time, but **return 0 from the second time on**, as returning 0 is the default action for `int` functions. - -## Using Multiple Expectations ## -So far we've only shown examples where you have a single expectation. More realistically, you're going to specify expectations on multiple mock methods, which may be from multiple mock objects. - -By default, when a mock method is invoked, Google Mock will search the expectations in the **reverse order** they are defined, and stop when an active expectation that matches the arguments is found (you can think of it as "newer rules override older ones."). If the matching expectation cannot take any more calls, you will get an upper-bound-violated failure. Here's an example: - -``` -using ::testing::_;... -EXPECT_CALL(turtle, Forward(_)); // #1 -EXPECT_CALL(turtle, Forward(10)) // #2 - .Times(2); -``` - -If `Forward(10)` is called three times in a row, the third time it will be an error, as the last matching expectation (#2) has been saturated. If, however, the third `Forward(10)` call is replaced by `Forward(20)`, then it would be OK, as now #1 will be the matching expectation. - -**Side note:** Why does Google Mock search for a match in the _reverse_ order of the expectations? The reason is that this allows a user to set up the default expectations in a mock object's constructor or the test fixture's set-up phase and then customize the mock by writing more specific expectations in the test body. So, if you have two expectations on the same method, you want to put the one with more specific matchers **after** the other, or the more specific rule would be shadowed by the more general one that comes after it. - -## Ordered vs Unordered Calls ## -By default, an expectation can match a call even though an earlier expectation hasn't been satisfied. In other words, the calls don't have to occur in the order the expectations are specified. - -Sometimes, you may want all the expected calls to occur in a strict order. To say this in Google Mock is easy: - -``` -using ::testing::InSequence;... -TEST(FooTest, DrawsLineSegment) { - ... - { - InSequence dummy; - - EXPECT_CALL(turtle, PenDown()); - EXPECT_CALL(turtle, Forward(100)); - EXPECT_CALL(turtle, PenUp()); - } - Foo(); -} -``` - -By creating an object of type `InSequence`, all expectations in its scope are put into a _sequence_ and have to occur _sequentially_. Since we are just relying on the constructor and destructor of this object to do the actual work, its name is really irrelevant. - -In this example, we test that `Foo()` calls the three expected functions in the order as written. If a call is made out-of-order, it will be an error. - -(What if you care about the relative order of some of the calls, but not all of them? Can you specify an arbitrary partial order? The answer is ... yes! If you are impatient, the details can be found in the [CookBook](V1_5_CookBook.md).) - -## All Expectations Are Sticky (Unless Said Otherwise) ## -Now let's do a quick quiz to see how well you can use this mock stuff already. How would you test that the turtle is asked to go to the origin _exactly twice_ (you want to ignore any other instructions it receives)? - -After you've come up with your answer, take a look at ours and compare notes (solve it yourself first - don't cheat!): - -``` -using ::testing::_;... -EXPECT_CALL(turtle, GoTo(_, _)) // #1 - .Times(AnyNumber()); -EXPECT_CALL(turtle, GoTo(0, 0)) // #2 - .Times(2); -``` - -Suppose `turtle.GoTo(0, 0)` is called three times. In the third time, Google Mock will see that the arguments match expectation #2 (remember that we always pick the last matching expectation). Now, since we said that there should be only two such calls, Google Mock will report an error immediately. This is basically what we've told you in the "Using Multiple Expectations" section above. - -This example shows that **expectations in Google Mock are "sticky" by default**, in the sense that they remain active even after we have reached their invocation upper bounds. This is an important rule to remember, as it affects the meaning of the spec, and is **different** to how it's done in many other mocking frameworks (Why'd we do that? Because we think our rule makes the common cases easier to express and understand.). - -Simple? Let's see if you've really understood it: what does the following code say? - -``` -using ::testing::Return; -... -for (int i = n; i > 0; i--) { - EXPECT_CALL(turtle, GetX()) - .WillOnce(Return(10*i)); -} -``` - -If you think it says that `turtle.GetX()` will be called `n` times and will return 10, 20, 30, ..., consecutively, think twice! The problem is that, as we said, expectations are sticky. So, the second time `turtle.GetX()` is called, the last (latest) `EXPECT_CALL()` statement will match, and will immediately lead to an "upper bound exceeded" error - this piece of code is not very useful! - -One correct way of saying that `turtle.GetX()` will return 10, 20, 30, ..., is to explicitly say that the expectations are _not_ sticky. In other words, they should _retire_ as soon as they are saturated: - -``` -using ::testing::Return; -... -for (int i = n; i > 0; i--) { - EXPECT_CALL(turtle, GetX()) - .WillOnce(Return(10*i)) - .RetiresOnSaturation(); -} -``` - -And, there's a better way to do it: in this case, we expect the calls to occur in a specific order, and we line up the actions to match the order. Since the order is important here, we should make it explicit using a sequence: - -``` -using ::testing::InSequence; -using ::testing::Return; -... -{ - InSequence s; - - for (int i = 1; i <= n; i++) { - EXPECT_CALL(turtle, GetX()) - .WillOnce(Return(10*i)) - .RetiresOnSaturation(); - } -} -``` - -By the way, the other situation where an expectation may _not_ be sticky is when it's in a sequence - as soon as another expectation that comes after it in the sequence has been used, it automatically retires (and will never be used to match any call). - -## Uninteresting Calls ## -A mock object may have many methods, and not all of them are that interesting. For example, in some tests we may not care about how many times `GetX()` and `GetY()` get called. - -In Google Mock, if you are not interested in a method, just don't say anything about it. If a call to this method occurs, you'll see a warning in the test output, but it won't be a failure. - -# What Now? # -Congratulations! You've learned enough about Google Mock to start using it. Now, you might want to join the [googlemock](http://groups.google.com/group/googlemock) discussion group and actually write some tests using Google Mock - it will be fun. Hey, it may even be addictive - you've been warned. - -Then, if you feel like increasing your mock quotient, you should move on to the [CookBook](V1_5_CookBook.md). You can learn many advanced features of Google Mock there -- and advance your level of enjoyment and testing bliss.
\ No newline at end of file diff --git a/googlemock/docs/v1_5/FrequentlyAskedQuestions.md b/googlemock/docs/v1_5/FrequentlyAskedQuestions.md deleted file mode 100644 index 7593243..0000000 --- a/googlemock/docs/v1_5/FrequentlyAskedQuestions.md +++ /dev/null @@ -1,624 +0,0 @@ - - -Please send your questions to the -[googlemock](http://groups.google.com/group/googlemock) discussion -group. If you need help with compiler errors, make sure you have -tried [Google Mock Doctor](#How_am_I_supposed_to_make_sense_of_these_horrible_template_error.md) first. - -## I wrote some matchers. After I upgraded to a new version of Google Mock, they no longer compile. What's going on? ## - -After version 1.4.0 of Google Mock was released, we had an idea on how -to make it easier to write matchers that can generate informative -messages efficiently. We experimented with this idea and liked what -we saw. Therefore we decided to implement it. - -Unfortunately, this means that if you have defined your own matchers -by implementing `MatcherInterface` or using `MakePolymorphicMatcher()`, -your definitions will no longer compile. Matchers defined using the -`MATCHER*` family of macros are not affected. - -Sorry for the hassle if your matchers are affected. We believe it's -in everyone's long-term interest to make this change sooner than -later. Fortunately, it's usually not hard to migrate an existing -matcher to the new API. Here's what you need to do: - -If you wrote your matcher like this: -``` -// Old matcher definition that doesn't work with the latest -// Google Mock. -using ::testing::MatcherInterface; -... -class MyWonderfulMatcher : public MatcherInterface<MyType> { - public: - ... - virtual bool Matches(MyType value) const { - // Returns true if value matches. - return value.GetFoo() > 5; - } - ... -}; -``` - -you'll need to change it to: -``` -// New matcher definition that works with the latest Google Mock. -using ::testing::MatcherInterface; -using ::testing::MatchResultListener; -... -class MyWonderfulMatcher : public MatcherInterface<MyType> { - public: - ... - virtual bool MatchAndExplain(MyType value, - MatchResultListener* listener) const { - // Returns true if value matches. - return value.GetFoo() > 5; - } - ... -}; -``` -(i.e. rename `Matches()` to `MatchAndExplain()` and give it a second -argument of type `MatchResultListener*`.) - -If you were also using `ExplainMatchResultTo()` to improve the matcher -message: -``` -// Old matcher definition that doesn't work with the lastest -// Google Mock. -using ::testing::MatcherInterface; -... -class MyWonderfulMatcher : public MatcherInterface<MyType> { - public: - ... - virtual bool Matches(MyType value) const { - // Returns true if value matches. - return value.GetFoo() > 5; - } - - virtual void ExplainMatchResultTo(MyType value, - ::std::ostream* os) const { - // Prints some helpful information to os to help - // a user understand why value matches (or doesn't match). - *os << "the Foo property is " << value.GetFoo(); - } - ... -}; -``` - -you should move the logic of `ExplainMatchResultTo()` into -`MatchAndExplain()`, using the `MatchResultListener` argument where -the `::std::ostream` was used: -``` -// New matcher definition that works with the latest Google Mock. -using ::testing::MatcherInterface; -using ::testing::MatchResultListener; -... -class MyWonderfulMatcher : public MatcherInterface<MyType> { - public: - ... - virtual bool MatchAndExplain(MyType value, - MatchResultListener* listener) const { - // Returns true if value matches. - *listener << "the Foo property is " << value.GetFoo(); - return value.GetFoo() > 5; - } - ... -}; -``` - -If your matcher is defined using `MakePolymorphicMatcher()`: -``` -// Old matcher definition that doesn't work with the latest -// Google Mock. -using ::testing::MakePolymorphicMatcher; -... -class MyGreatMatcher { - public: - ... - bool Matches(MyType value) const { - // Returns true if value matches. - return value.GetBar() < 42; - } - ... -}; -... MakePolymorphicMatcher(MyGreatMatcher()) ... -``` - -you should rename the `Matches()` method to `MatchAndExplain()` and -add a `MatchResultListener*` argument (the same as what you need to do -for matchers defined by implementing `MatcherInterface`): -``` -// New matcher definition that works with the latest Google Mock. -using ::testing::MakePolymorphicMatcher; -using ::testing::MatchResultListener; -... -class MyGreatMatcher { - public: - ... - bool MatchAndExplain(MyType value, - MatchResultListener* listener) const { - // Returns true if value matches. - return value.GetBar() < 42; - } - ... -}; -... MakePolymorphicMatcher(MyGreatMatcher()) ... -``` - -If your polymorphic matcher uses `ExplainMatchResultTo()` for better -failure messages: -``` -// Old matcher definition that doesn't work with the latest -// Google Mock. -using ::testing::MakePolymorphicMatcher; -... -class MyGreatMatcher { - public: - ... - bool Matches(MyType value) const { - // Returns true if value matches. - return value.GetBar() < 42; - } - ... -}; -void ExplainMatchResultTo(const MyGreatMatcher& matcher, - MyType value, - ::std::ostream* os) { - // Prints some helpful information to os to help - // a user understand why value matches (or doesn't match). - *os << "the Bar property is " << value.GetBar(); -} -... MakePolymorphicMatcher(MyGreatMatcher()) ... -``` - -you'll need to move the logic inside `ExplainMatchResultTo()` to -`MatchAndExplain()`: -``` -// New matcher definition that works with the latest Google Mock. -using ::testing::MakePolymorphicMatcher; -using ::testing::MatchResultListener; -... -class MyGreatMatcher { - public: - ... - bool MatchAndExplain(MyType value, - MatchResultListener* listener) const { - // Returns true if value matches. - *listener << "the Bar property is " << value.GetBar(); - return value.GetBar() < 42; - } - ... -}; -... MakePolymorphicMatcher(MyGreatMatcher()) ... -``` - -For more information, you can read these -[two](V1_5_CookBook#Writing_New_Monomorphic_Matchers.md) -[recipes](V1_5_CookBook#Writing_New_Polymorphic_Matchers.md) -from the cookbook. As always, you -are welcome to post questions on `googlemock@googlegroups.com` if you -need any help. - -## When using Google Mock, do I have to use Google Test as the testing framework? I have my favorite testing framework and don't want to switch. ## - -Google Mock works out of the box with Google Test. However, it's easy -to configure it to work with any testing framework of your choice. -[Here](V1_5_ForDummies#Using_Google_Mock_with_Any_Testing_Framework.md) is how. - -## How am I supposed to make sense of these horrible template errors? ## - -If you are confused by the compiler errors gcc threw at you, -try consulting the _Google Mock Doctor_ tool first. What it does is to -scan stdin for gcc error messages, and spit out diagnoses on the -problems (we call them diseases) your code has. - -To "install", run command: -``` -alias gmd='<path to googlemock>/scripts/gmock_doctor.py' -``` - -To use it, do: -``` -<your-favorite-build-command> <your-test> 2>&1 | gmd -``` - -For example: -``` -make my_test 2>&1 | gmd -``` - -Or you can run `gmd` and copy-n-paste gcc's error messages to it. - -## Can I mock a variadic function? ## - -You cannot mock a variadic function (i.e. a function taking ellipsis -(`...`) arguments) directly in Google Mock. - -The problem is that in general, there is _no way_ for a mock object to -know how many arguments are passed to the variadic method, and what -the arguments' types are. Only the _author of the base class_ knows -the protocol, and we cannot look into his head. - -Therefore, to mock such a function, the _user_ must teach the mock -object how to figure out the number of arguments and their types. One -way to do it is to provide overloaded versions of the function. - -Ellipsis arguments are inherited from C and not really a C++ feature. -They are unsafe to use and don't work with arguments that have -constructors or destructors. Therefore we recommend to avoid them in -C++ as much as possible. - -## MSVC gives me warning C4301 or C4373 when I define a mock method with a const parameter. Why? ## - -If you compile this using Microsoft Visual C++ 2005 SP1: -``` -class Foo { - ... - virtual void Bar(const int i) = 0; -}; - -class MockFoo : public Foo { - ... - MOCK_METHOD1(Bar, void(const int i)); -}; -``` -You may get the following warning: -``` -warning C4301: 'MockFoo::Bar': overriding virtual function only differs from 'Foo::Bar' by const/volatile qualifier -``` - -This is a MSVC bug. The same code compiles fine with gcc ,for -example. If you use Visual C++ 2008 SP1, you would get the warning: -``` -warning C4373: 'MockFoo::Bar': virtual function overrides 'Foo::Bar', previous versions of the compiler did not override when parameters only differed by const/volatile qualifiers -``` - -In C++, if you _declare_ a function with a `const` parameter, the -`const` modifier is _ignored_. Therefore, the `Foo` base class above -is equivalent to: -``` -class Foo { - ... - virtual void Bar(int i) = 0; // int or const int? Makes no difference. -}; -``` - -In fact, you can _declare_ Bar() with an `int` parameter, and _define_ -it with a `const int` parameter. The compiler will still match them -up. - -Since making a parameter `const` is meaningless in the method -_declaration_, we recommend to remove it in both `Foo` and `MockFoo`. -That should workaround the VC bug. - -Note that we are talking about the _top-level_ `const` modifier here. -If the function parameter is passed by pointer or reference, declaring -the _pointee_ or _referee_ as `const` is still meaningful. For -example, the following two declarations are _not_ equivalent: -``` -void Bar(int* p); // Neither p nor *p is const. -void Bar(const int* p); // p is not const, but *p is. -``` - -## I have a huge mock class, and Microsoft Visual C++ runs out of memory when compiling it. What can I do? ## - -We've noticed that when the `/clr` compiler flag is used, Visual C++ -uses 5~6 times as much memory when compiling a mock class. We suggest -to avoid `/clr` when compiling native C++ mocks. - -## I can't figure out why Google Mock thinks my expectations are not satisfied. What should I do? ## - -You might want to run your test with -`--gmock_verbose=info`. This flag lets Google Mock print a trace -of every mock function call it receives. By studying the trace, -you'll gain insights on why the expectations you set are not met. - -## How can I assert that a function is NEVER called? ## - -``` -EXPECT_CALL(foo, Bar(_)) - .Times(0); -``` - -## I have a failed test where Google Mock tells me TWICE that a particular expectation is not satisfied. Isn't this redundant? ## - -When Google Mock detects a failure, it prints relevant information -(the mock function arguments, the state of relevant expectations, and -etc) to help the user debug. If another failure is detected, Google -Mock will do the same, including printing the state of relevant -expectations. - -Sometimes an expectation's state didn't change between two failures, -and you'll see the same description of the state twice. They are -however _not_ redundant, as they refer to _different points in time_. -The fact they are the same _is_ interesting information. - -## I get a heap check failure when using a mock object, but using a real object is fine. What can be wrong? ## - -Does the class (hopefully a pure interface) you are mocking have a -virtual destructor? - -Whenever you derive from a base class, make sure its destructor is -virtual. Otherwise Bad Things will happen. Consider the following -code: - -``` -class Base { - public: - // Not virtual, but should be. - ~Base() { ... } - ... -}; - -class Derived : public Base { - public: - ... - private: - std::string value_; -}; - -... - Base* p = new Derived; - ... - delete p; // Surprise! ~Base() will be called, but ~Derived() will not - // - value_ is leaked. -``` - -By changing `~Base()` to virtual, `~Derived()` will be correctly -called when `delete p` is executed, and the heap checker -will be happy. - -## The "newer expectations override older ones" rule makes writing expectations awkward. Why does Google Mock do that? ## - -When people complain about this, often they are referring to code like: - -``` -// foo.Bar() should be called twice, return 1 the first time, and return -// 2 the second time. However, I have to write the expectations in the -// reverse order. This sucks big time!!! -EXPECT_CALL(foo, Bar()) - .WillOnce(Return(2)) - .RetiresOnSaturation(); -EXPECT_CALL(foo, Bar()) - .WillOnce(Return(1)) - .RetiresOnSaturation(); -``` - -The problem is that they didn't pick the **best** way to express the test's -intent. - -By default, expectations don't have to be matched in _any_ particular -order. If you want them to match in a certain order, you need to be -explicit. This is Google Mock's (and jMock's) fundamental philosophy: it's -easy to accidentally over-specify your tests, and we want to make it -harder to do so. - -There are two better ways to write the test spec. You could either -put the expectations in sequence: - -``` -// foo.Bar() should be called twice, return 1 the first time, and return -// 2 the second time. Using a sequence, we can write the expectations -// in their natural order. -{ - InSequence s; - EXPECT_CALL(foo, Bar()) - .WillOnce(Return(1)) - .RetiresOnSaturation(); - EXPECT_CALL(foo, Bar()) - .WillOnce(Return(2)) - .RetiresOnSaturation(); -} -``` - -or you can put the sequence of actions in the same expectation: - -``` -// foo.Bar() should be called twice, return 1 the first time, and return -// 2 the second time. -EXPECT_CALL(foo, Bar()) - .WillOnce(Return(1)) - .WillOnce(Return(2)) - .RetiresOnSaturation(); -``` - -Back to the original questions: why does Google Mock search the -expectations (and `ON_CALL`s) from back to front? Because this -allows a user to set up a mock's behavior for the common case early -(e.g. in the mock's constructor or the test fixture's set-up phase) -and customize it with more specific rules later. If Google Mock -searches from front to back, this very useful pattern won't be -possible. - -## Google Mock prints a warning when a function without EXPECT\_CALL is called, even if I have set its behavior using ON\_CALL. Would it be reasonable not to show the warning in this case? ## - -When choosing between being neat and being safe, we lean toward the -latter. So the answer is that we think it's better to show the -warning. - -Often people write `ON_CALL`s in the mock object's -constructor or `SetUp()`, as the default behavior rarely changes from -test to test. Then in the test body they set the expectations, which -are often different for each test. Having an `ON_CALL` in the set-up -part of a test doesn't mean that the calls are expected. If there's -no `EXPECT_CALL` and the method is called, it's possibly an error. If -we quietly let the call go through without notifying the user, bugs -may creep in unnoticed. - -If, however, you are sure that the calls are OK, you can write - -``` -EXPECT_CALL(foo, Bar(_)) - .WillRepeatedly(...); -``` - -instead of - -``` -ON_CALL(foo, Bar(_)) - .WillByDefault(...); -``` - -This tells Google Mock that you do expect the calls and no warning should be -printed. - -Also, you can control the verbosity using the `--gmock_verbose` flag. -If you find the output too noisy when debugging, just choose a less -verbose level. - -## How can I delete the mock function's argument in an action? ## - -If you find yourself needing to perform some action that's not -supported by Google Mock directly, remember that you can define your own -actions using -[MakeAction()](V1_5_CookBook#Writing_New_Actions.md) or -[MakePolymorphicAction()](V1_5_CookBook#Writing_New_Polymorphic_Actions.md), -or you can write a stub function and invoke it using -[Invoke()](V1_5_CookBook#Using_Functions_Methods_Functors.md). - -## MOCK\_METHODn()'s second argument looks funny. Why don't you use the MOCK\_METHODn(Method, return\_type, arg\_1, ..., arg\_n) syntax? ## - -What?! I think it's beautiful. :-) - -While which syntax looks more natural is a subjective matter to some -extent, Google Mock's syntax was chosen for several practical advantages it -has. - -Try to mock a function that takes a map as an argument: -``` -virtual int GetSize(const map<int, std::string>& m); -``` - -Using the proposed syntax, it would be: -``` -MOCK_METHOD1(GetSize, int, const map<int, std::string>& m); -``` - -Guess what? You'll get a compiler error as the compiler thinks that -`const map<int, std::string>& m` are **two**, not one, arguments. To work -around this you can use `typedef` to give the map type a name, but -that gets in the way of your work. Google Mock's syntax avoids this -problem as the function's argument types are protected inside a pair -of parentheses: -``` -// This compiles fine. -MOCK_METHOD1(GetSize, int(const map<int, std::string>& m)); -``` - -You still need a `typedef` if the return type contains an unprotected -comma, but that's much rarer. - -Other advantages include: - 1. `MOCK_METHOD1(Foo, int, bool)` can leave a reader wonder whether the method returns `int` or `bool`, while there won't be such confusion using Google Mock's syntax. - 1. The way Google Mock describes a function type is nothing new, although many people may not be familiar with it. The same syntax was used in C, and the `function` library in `tr1` uses this syntax extensively. Since `tr1` will become a part of the new version of STL, we feel very comfortable to be consistent with it. - 1. The function type syntax is also used in other parts of Google Mock's API (e.g. the action interface) in order to make the implementation tractable. A user needs to learn it anyway in order to utilize Google Mock's more advanced features. We'd as well stick to the same syntax in `MOCK_METHOD*`! - -## My code calls a static/global function. Can I mock it? ## - -You can, but you need to make some changes. - -In general, if you find yourself needing to mock a static function, -it's a sign that your modules are too tightly coupled (and less -flexible, less reusable, less testable, etc). You are probably better -off defining a small interface and call the function through that -interface, which then can be easily mocked. It's a bit of work -initially, but usually pays for itself quickly. - -This Google Testing Blog -[post](http://googletesting.blogspot.com/2008/06/defeat-static-cling.html) -says it excellently. Check it out. - -## My mock object needs to do complex stuff. It's a lot of pain to specify the actions. Google Mock sucks! ## - -I know it's not a question, but you get an answer for free any way. :-) - -With Google Mock, you can create mocks in C++ easily. And people might be -tempted to use them everywhere. Sometimes they work great, and -sometimes you may find them, well, a pain to use. So, what's wrong in -the latter case? - -When you write a test without using mocks, you exercise the code and -assert that it returns the correct value or that the system is in an -expected state. This is sometimes called "state-based testing". - -Mocks are great for what some call "interaction-based" testing: -instead of checking the system state at the very end, mock objects -verify that they are invoked the right way and report an error as soon -as it arises, giving you a handle on the precise context in which the -error was triggered. This is often more effective and economical to -do than state-based testing. - -If you are doing state-based testing and using a test double just to -simulate the real object, you are probably better off using a fake. -Using a mock in this case causes pain, as it's not a strong point for -mocks to perform complex actions. If you experience this and think -that mocks suck, you are just not using the right tool for your -problem. Or, you might be trying to solve the wrong problem. :-) - -## I got a warning "Uninteresting function call encountered - default action taken.." Should I panic? ## - -By all means, NO! It's just an FYI. - -What it means is that you have a mock function, you haven't set any -expectations on it (by Google Mock's rule this means that you are not -interested in calls to this function and therefore it can be called -any number of times), and it is called. That's OK - you didn't say -it's not OK to call the function! - -What if you actually meant to disallow this function to be called, but -forgot to write `EXPECT_CALL(foo, Bar()).Times(0)`? While -one can argue that it's the user's fault, Google Mock tries to be nice and -prints you a note. - -So, when you see the message and believe that there shouldn't be any -uninteresting calls, you should investigate what's going on. To make -your life easier, Google Mock prints the function name and arguments -when an uninteresting call is encountered. - -## I want to define a custom action. Should I use Invoke() or implement the action interface? ## - -Either way is fine - you want to choose the one that's more convenient -for your circumstance. - -Usually, if your action is for a particular function type, defining it -using `Invoke()` should be easier; if your action can be used in -functions of different types (e.g. if you are defining -`Return(value)`), `MakePolymorphicAction()` is -easiest. Sometimes you want precise control on what types of -functions the action can be used in, and implementing -`ActionInterface` is the way to go here. See the implementation of -`Return()` in `include/gmock/gmock-actions.h` for an example. - -## I'm using the set-argument-pointee action, and the compiler complains about "conflicting return type specified". What does it mean? ## - -You got this error as Google Mock has no idea what value it should return -when the mock method is called. `SetArgumentPointee()` says what the -side effect is, but doesn't say what the return value should be. You -need `DoAll()` to chain a `SetArgumentPointee()` with a `Return()`. - -See this [recipe](V1_5_CookBook#Mocking_Side_Effects.md) for more details and an example. - - -## My question is not in your FAQ! ## - -If you cannot find the answer to your question in this FAQ, there are -some other resources you can use: - - 1. read other [wiki pages](http://code.google.com/p/googlemock/w/list), - 1. search the mailing list [archive](http://groups.google.com/group/googlemock/topics), - 1. ask it on [googlemock@googlegroups.com](mailto:googlemock@googlegroups.com) and someone will answer it (to prevent spam, we require you to join the [discussion group](http://groups.google.com/group/googlemock) before you can post.). - -Please note that creating an issue in the -[issue tracker](http://code.google.com/p/googlemock/issues/list) is _not_ -a good way to get your answer, as it is monitored infrequently by a -very small number of people. - -When asking a question, it's helpful to provide as much of the -following information as possible (people cannot help you if there's -not enough information in your question): - - * the version (or the revision number if you check out from SVN directly) of Google Mock you use (Google Mock is under active development, so it's possible that your problem has been solved in a later version), - * your operating system, - * the name and version of your compiler, - * the complete command line flags you give to your compiler, - * the complete compiler error messages (if the question is about compilation), - * the _actual_ code (ideally, a minimal but complete program) that has the problem you encounter.
\ No newline at end of file diff --git a/googlemock/docs/v1_6/CheatSheet.md b/googlemock/docs/v1_6/CheatSheet.md deleted file mode 100644 index 91de1d2..0000000 --- a/googlemock/docs/v1_6/CheatSheet.md +++ /dev/null @@ -1,534 +0,0 @@ - - -# Defining a Mock Class # - -## Mocking a Normal Class ## - -Given -``` -class Foo { - ... - virtual ~Foo(); - virtual int GetSize() const = 0; - virtual string Describe(const char* name) = 0; - virtual string Describe(int type) = 0; - virtual bool Process(Bar elem, int count) = 0; -}; -``` -(note that `~Foo()` **must** be virtual) we can define its mock as -``` -#include "gmock/gmock.h" - -class MockFoo : public Foo { - MOCK_CONST_METHOD0(GetSize, int()); - MOCK_METHOD1(Describe, string(const char* name)); - MOCK_METHOD1(Describe, string(int type)); - MOCK_METHOD2(Process, bool(Bar elem, int count)); -}; -``` - -To create a "nice" mock object which ignores all uninteresting calls, -or a "strict" mock object, which treats them as failures: -``` -NiceMock<MockFoo> nice_foo; // The type is a subclass of MockFoo. -StrictMock<MockFoo> strict_foo; // The type is a subclass of MockFoo. -``` - -## Mocking a Class Template ## - -To mock -``` -template <typename Elem> -class StackInterface { - public: - ... - virtual ~StackInterface(); - virtual int GetSize() const = 0; - virtual void Push(const Elem& x) = 0; -}; -``` -(note that `~StackInterface()` **must** be virtual) just append `_T` to the `MOCK_*` macros: -``` -template <typename Elem> -class MockStack : public StackInterface<Elem> { - public: - ... - MOCK_CONST_METHOD0_T(GetSize, int()); - MOCK_METHOD1_T(Push, void(const Elem& x)); -}; -``` - -## Specifying Calling Conventions for Mock Functions ## - -If your mock function doesn't use the default calling convention, you -can specify it by appending `_WITH_CALLTYPE` to any of the macros -described in the previous two sections and supplying the calling -convention as the first argument to the macro. For example, -``` - MOCK_METHOD_1_WITH_CALLTYPE(STDMETHODCALLTYPE, Foo, bool(int n)); - MOCK_CONST_METHOD2_WITH_CALLTYPE(STDMETHODCALLTYPE, Bar, int(double x, double y)); -``` -where `STDMETHODCALLTYPE` is defined by `<objbase.h>` on Windows. - -# Using Mocks in Tests # - -The typical flow is: - 1. Import the Google Mock names you need to use. All Google Mock names are in the `testing` namespace unless they are macros or otherwise noted. - 1. Create the mock objects. - 1. Optionally, set the default actions of the mock objects. - 1. Set your expectations on the mock objects (How will they be called? What wil they do?). - 1. Exercise code that uses the mock objects; if necessary, check the result using [Google Test](http://code.google.com/p/googletest/) assertions. - 1. When a mock objects is destructed, Google Mock automatically verifies that all expectations on it have been satisfied. - -Here is an example: -``` -using ::testing::Return; // #1 - -TEST(BarTest, DoesThis) { - MockFoo foo; // #2 - - ON_CALL(foo, GetSize()) // #3 - .WillByDefault(Return(1)); - // ... other default actions ... - - EXPECT_CALL(foo, Describe(5)) // #4 - .Times(3) - .WillRepeatedly(Return("Category 5")); - // ... other expectations ... - - EXPECT_EQ("good", MyProductionFunction(&foo)); // #5 -} // #6 -``` - -# Setting Default Actions # - -Google Mock has a **built-in default action** for any function that -returns `void`, `bool`, a numeric value, or a pointer. - -To customize the default action for functions with return type `T` globally: -``` -using ::testing::DefaultValue; - -DefaultValue<T>::Set(value); // Sets the default value to be returned. -// ... use the mocks ... -DefaultValue<T>::Clear(); // Resets the default value. -``` - -To customize the default action for a particular method, use `ON_CALL()`: -``` -ON_CALL(mock_object, method(matchers)) - .With(multi_argument_matcher) ? - .WillByDefault(action); -``` - -# Setting Expectations # - -`EXPECT_CALL()` sets **expectations** on a mock method (How will it be -called? What will it do?): -``` -EXPECT_CALL(mock_object, method(matchers)) - .With(multi_argument_matcher) ? - .Times(cardinality) ? - .InSequence(sequences) * - .After(expectations) * - .WillOnce(action) * - .WillRepeatedly(action) ? - .RetiresOnSaturation(); ? -``` - -If `Times()` is omitted, the cardinality is assumed to be: - - * `Times(1)` when there is neither `WillOnce()` nor `WillRepeatedly()`; - * `Times(n)` when there are `n WillOnce()`s but no `WillRepeatedly()`, where `n` >= 1; or - * `Times(AtLeast(n))` when there are `n WillOnce()`s and a `WillRepeatedly()`, where `n` >= 0. - -A method with no `EXPECT_CALL()` is free to be invoked _any number of times_, and the default action will be taken each time. - -# Matchers # - -A **matcher** matches a _single_ argument. You can use it inside -`ON_CALL()` or `EXPECT_CALL()`, or use it to validate a value -directly: - -| `EXPECT_THAT(value, matcher)` | Asserts that `value` matches `matcher`. | -|:------------------------------|:----------------------------------------| -| `ASSERT_THAT(value, matcher)` | The same as `EXPECT_THAT(value, matcher)`, except that it generates a **fatal** failure. | - -Built-in matchers (where `argument` is the function argument) are -divided into several categories: - -## Wildcard ## -|`_`|`argument` can be any value of the correct type.| -|:--|:-----------------------------------------------| -|`A<type>()` or `An<type>()`|`argument` can be any value of type `type`. | - -## Generic Comparison ## - -|`Eq(value)` or `value`|`argument == value`| -|:---------------------|:------------------| -|`Ge(value)` |`argument >= value`| -|`Gt(value)` |`argument > value` | -|`Le(value)` |`argument <= value`| -|`Lt(value)` |`argument < value` | -|`Ne(value)` |`argument != value`| -|`IsNull()` |`argument` is a `NULL` pointer (raw or smart).| -|`NotNull()` |`argument` is a non-null pointer (raw or smart).| -|`Ref(variable)` |`argument` is a reference to `variable`.| -|`TypedEq<type>(value)`|`argument` has type `type` and is equal to `value`. You may need to use this instead of `Eq(value)` when the mock function is overloaded.| - -Except `Ref()`, these matchers make a _copy_ of `value` in case it's -modified or destructed later. If the compiler complains that `value` -doesn't have a public copy constructor, try wrap it in `ByRef()`, -e.g. `Eq(ByRef(non_copyable_value))`. If you do that, make sure -`non_copyable_value` is not changed afterwards, or the meaning of your -matcher will be changed. - -## Floating-Point Matchers ## - -|`DoubleEq(a_double)`|`argument` is a `double` value approximately equal to `a_double`, treating two NaNs as unequal.| -|:-------------------|:----------------------------------------------------------------------------------------------| -|`FloatEq(a_float)` |`argument` is a `float` value approximately equal to `a_float`, treating two NaNs as unequal. | -|`NanSensitiveDoubleEq(a_double)`|`argument` is a `double` value approximately equal to `a_double`, treating two NaNs as equal. | -|`NanSensitiveFloatEq(a_float)`|`argument` is a `float` value approximately equal to `a_float`, treating two NaNs as equal. | - -These matchers use ULP-based comparison (the same as used in -[Google Test](http://code.google.com/p/googletest/)). They -automatically pick a reasonable error bound based on the absolute -value of the expected value. `DoubleEq()` and `FloatEq()` conform to -the IEEE standard, which requires comparing two NaNs for equality to -return false. The `NanSensitive*` version instead treats two NaNs as -equal, which is often what a user wants. - -## String Matchers ## - -The `argument` can be either a C string or a C++ string object: - -|`ContainsRegex(string)`|`argument` matches the given regular expression.| -|:----------------------|:-----------------------------------------------| -|`EndsWith(suffix)` |`argument` ends with string `suffix`. | -|`HasSubstr(string)` |`argument` contains `string` as a sub-string. | -|`MatchesRegex(string)` |`argument` matches the given regular expression with the match starting at the first character and ending at the last character.| -|`StartsWith(prefix)` |`argument` starts with string `prefix`. | -|`StrCaseEq(string)` |`argument` is equal to `string`, ignoring case. | -|`StrCaseNe(string)` |`argument` is not equal to `string`, ignoring case.| -|`StrEq(string)` |`argument` is equal to `string`. | -|`StrNe(string)` |`argument` is not equal to `string`. | - -`ContainsRegex()` and `MatchesRegex()` use the regular expression -syntax defined -[here](http://code.google.com/p/googletest/wiki/V1_6_AdvancedGuide#Regular_Expression_Syntax). -`StrCaseEq()`, `StrCaseNe()`, `StrEq()`, and `StrNe()` work for wide -strings as well. - -## Container Matchers ## - -Most STL-style containers support `==`, so you can use -`Eq(expected_container)` or simply `expected_container` to match a -container exactly. If you want to write the elements in-line, -match them more flexibly, or get more informative messages, you can use: - -| `Contains(e)` | `argument` contains an element that matches `e`, which can be either a value or a matcher. | -|:--------------|:-------------------------------------------------------------------------------------------| -| `Each(e)` | `argument` is a container where _every_ element matches `e`, which can be either a value or a matcher. | -| `ElementsAre(e0, e1, ..., en)` | `argument` has `n + 1` elements, where the i-th element matches `ei`, which can be a value or a matcher. 0 to 10 arguments are allowed. | -| `ElementsAreArray(array)` or `ElementsAreArray(array, count)` | The same as `ElementsAre()` except that the expected element values/matchers come from a C-style array. | -| `ContainerEq(container)` | The same as `Eq(container)` except that the failure message also includes which elements are in one container but not the other. | -| `Pointwise(m, container)` | `argument` contains the same number of elements as in `container`, and for all i, (the i-th element in `argument`, the i-th element in `container`) match `m`, which is a matcher on 2-tuples. E.g. `Pointwise(Le(), upper_bounds)` verifies that each element in `argument` doesn't exceed the corresponding element in `upper_bounds`. | - -These matchers can also match: - - 1. a native array passed by reference (e.g. in `Foo(const int (&a)[5])`), and - 1. an array passed as a pointer and a count (e.g. in `Bar(const T* buffer, int len)` -- see [Multi-argument Matchers](#Multiargument_Matchers.md)). - -where the array may be multi-dimensional (i.e. its elements can be arrays). - -## Member Matchers ## - -|`Field(&class::field, m)`|`argument.field` (or `argument->field` when `argument` is a plain pointer) matches matcher `m`, where `argument` is an object of type _class_.| -|:------------------------|:---------------------------------------------------------------------------------------------------------------------------------------------| -|`Key(e)` |`argument.first` matches `e`, which can be either a value or a matcher. E.g. `Contains(Key(Le(5)))` can verify that a `map` contains a key `<= 5`.| -|`Pair(m1, m2)` |`argument` is an `std::pair` whose `first` field matches `m1` and `second` field matches `m2`. | -|`Property(&class::property, m)`|`argument.property()` (or `argument->property()` when `argument` is a plain pointer) matches matcher `m`, where `argument` is an object of type _class_.| - -## Matching the Result of a Function or Functor ## - -|`ResultOf(f, m)`|`f(argument)` matches matcher `m`, where `f` is a function or functor.| -|:---------------|:---------------------------------------------------------------------| - -## Pointer Matchers ## - -|`Pointee(m)`|`argument` (either a smart pointer or a raw pointer) points to a value that matches matcher `m`.| -|:-----------|:-----------------------------------------------------------------------------------------------| - -## Multiargument Matchers ## - -Technically, all matchers match a _single_ value. A "multi-argument" -matcher is just one that matches a _tuple_. The following matchers can -be used to match a tuple `(x, y)`: - -|`Eq()`|`x == y`| -|:-----|:-------| -|`Ge()`|`x >= y`| -|`Gt()`|`x > y` | -|`Le()`|`x <= y`| -|`Lt()`|`x < y` | -|`Ne()`|`x != y`| - -You can use the following selectors to pick a subset of the arguments -(or reorder them) to participate in the matching: - -|`AllArgs(m)`|Equivalent to `m`. Useful as syntactic sugar in `.With(AllArgs(m))`.| -|:-----------|:-------------------------------------------------------------------| -|`Args<N1, N2, ..., Nk>(m)`|The tuple of the `k` selected (using 0-based indices) arguments matches `m`, e.g. `Args<1, 2>(Eq())`.| - -## Composite Matchers ## - -You can make a matcher from one or more other matchers: - -|`AllOf(m1, m2, ..., mn)`|`argument` matches all of the matchers `m1` to `mn`.| -|:-----------------------|:---------------------------------------------------| -|`AnyOf(m1, m2, ..., mn)`|`argument` matches at least one of the matchers `m1` to `mn`.| -|`Not(m)` |`argument` doesn't match matcher `m`. | - -## Adapters for Matchers ## - -|`MatcherCast<T>(m)`|casts matcher `m` to type `Matcher<T>`.| -|:------------------|:--------------------------------------| -|`SafeMatcherCast<T>(m)`| [safely casts](http://code.google.com/p/googlemock/wiki/V1_6_CookBook#Casting_Matchers) matcher `m` to type `Matcher<T>`. | -|`Truly(predicate)` |`predicate(argument)` returns something considered by C++ to be true, where `predicate` is a function or functor.| - -## Matchers as Predicates ## - -|`Matches(m)(value)`|evaluates to `true` if `value` matches `m`. You can use `Matches(m)` alone as a unary functor.| -|:------------------|:---------------------------------------------------------------------------------------------| -|`ExplainMatchResult(m, value, result_listener)`|evaluates to `true` if `value` matches `m`, explaining the result to `result_listener`. | -|`Value(value, m)` |evaluates to `true` if `value` matches `m`. | - -## Defining Matchers ## - -| `MATCHER(IsEven, "") { return (arg % 2) == 0; }` | Defines a matcher `IsEven()` to match an even number. | -|:-------------------------------------------------|:------------------------------------------------------| -| `MATCHER_P(IsDivisibleBy, n, "") { *result_listener << "where the remainder is " << (arg % n); return (arg % n) == 0; }` | Defines a macher `IsDivisibleBy(n)` to match a number divisible by `n`. | -| `MATCHER_P2(IsBetween, a, b, std::string(negation ? "isn't" : "is") + " between " + PrintToString(a) + " and " + PrintToString(b)) { return a <= arg && arg <= b; }` | Defines a matcher `IsBetween(a, b)` to match a value in the range [`a`, `b`]. | - -**Notes:** - - 1. The `MATCHER*` macros cannot be used inside a function or class. - 1. The matcher body must be _purely functional_ (i.e. it cannot have any side effect, and the result must not depend on anything other than the value being matched and the matcher parameters). - 1. You can use `PrintToString(x)` to convert a value `x` of any type to a string. - -## Matchers as Test Assertions ## - -|`ASSERT_THAT(expression, m)`|Generates a [fatal failure](http://code.google.com/p/googletest/wiki/V1_6_Primer#Assertions) if the value of `expression` doesn't match matcher `m`.| -|:---------------------------|:---------------------------------------------------------------------------------------------------------------------------------------------------| -|`EXPECT_THAT(expression, m)`|Generates a non-fatal failure if the value of `expression` doesn't match matcher `m`. | - -# Actions # - -**Actions** specify what a mock function should do when invoked. - -## Returning a Value ## - -|`Return()`|Return from a `void` mock function.| -|:---------|:----------------------------------| -|`Return(value)`|Return `value`. If the type of `value` is different to the mock function's return type, `value` is converted to the latter type <i>at the time the expectation is set</i>, not when the action is executed.| -|`ReturnArg<N>()`|Return the `N`-th (0-based) argument.| -|`ReturnNew<T>(a1, ..., ak)`|Return `new T(a1, ..., ak)`; a different object is created each time.| -|`ReturnNull()`|Return a null pointer. | -|`ReturnPointee(ptr)`|Return the value pointed to by `ptr`.| -|`ReturnRef(variable)`|Return a reference to `variable`. | -|`ReturnRefOfCopy(value)`|Return a reference to a copy of `value`; the copy lives as long as the action.| - -## Side Effects ## - -|`Assign(&variable, value)`|Assign `value` to variable.| -|:-------------------------|:--------------------------| -| `DeleteArg<N>()` | Delete the `N`-th (0-based) argument, which must be a pointer. | -| `SaveArg<N>(pointer)` | Save the `N`-th (0-based) argument to `*pointer`. | -| `SaveArgPointee<N>(pointer)` | Save the value pointed to by the `N`-th (0-based) argument to `*pointer`. | -| `SetArgReferee<N>(value)` | Assign value to the variable referenced by the `N`-th (0-based) argument. | -|`SetArgPointee<N>(value)` |Assign `value` to the variable pointed by the `N`-th (0-based) argument.| -|`SetArgumentPointee<N>(value)`|Same as `SetArgPointee<N>(value)`. Deprecated. Will be removed in v1.7.0.| -|`SetArrayArgument<N>(first, last)`|Copies the elements in source range [`first`, `last`) to the array pointed to by the `N`-th (0-based) argument, which can be either a pointer or an iterator. The action does not take ownership of the elements in the source range.| -|`SetErrnoAndReturn(error, value)`|Set `errno` to `error` and return `value`.| -|`Throw(exception)` |Throws the given exception, which can be any copyable value. Available since v1.1.0.| - -## Using a Function or a Functor as an Action ## - -|`Invoke(f)`|Invoke `f` with the arguments passed to the mock function, where `f` can be a global/static function or a functor.| -|:----------|:-----------------------------------------------------------------------------------------------------------------| -|`Invoke(object_pointer, &class::method)`|Invoke the {method on the object with the arguments passed to the mock function. | -|`InvokeWithoutArgs(f)`|Invoke `f`, which can be a global/static function or a functor. `f` must take no arguments. | -|`InvokeWithoutArgs(object_pointer, &class::method)`|Invoke the method on the object, which takes no arguments. | -|`InvokeArgument<N>(arg1, arg2, ..., argk)`|Invoke the mock function's `N`-th (0-based) argument, which must be a function or a functor, with the `k` arguments.| - -The return value of the invoked function is used as the return value -of the action. - -When defining a function or functor to be used with `Invoke*()`, you can declare any unused parameters as `Unused`: -``` - double Distance(Unused, double x, double y) { return sqrt(x*x + y*y); } - ... - EXPECT_CALL(mock, Foo("Hi", _, _)).WillOnce(Invoke(Distance)); -``` - -In `InvokeArgument<N>(...)`, if an argument needs to be passed by reference, wrap it inside `ByRef()`. For example, -``` - InvokeArgument<2>(5, string("Hi"), ByRef(foo)) -``` -calls the mock function's #2 argument, passing to it `5` and `string("Hi")` by value, and `foo` by reference. - -## Default Action ## - -|`DoDefault()`|Do the default action (specified by `ON_CALL()` or the built-in one).| -|:------------|:--------------------------------------------------------------------| - -**Note:** due to technical reasons, `DoDefault()` cannot be used inside a composite action - trying to do so will result in a run-time error. - -## Composite Actions ## - -|`DoAll(a1, a2, ..., an)`|Do all actions `a1` to `an` and return the result of `an` in each invocation. The first `n - 1` sub-actions must return void. | -|:-----------------------|:-----------------------------------------------------------------------------------------------------------------------------| -|`IgnoreResult(a)` |Perform action `a` and ignore its result. `a` must not return void. | -|`WithArg<N>(a)` |Pass the `N`-th (0-based) argument of the mock function to action `a` and perform it. | -|`WithArgs<N1, N2, ..., Nk>(a)`|Pass the selected (0-based) arguments of the mock function to action `a` and perform it. | -|`WithoutArgs(a)` |Perform action `a` without any arguments. | - -## Defining Actions ## - -| `ACTION(Sum) { return arg0 + arg1; }` | Defines an action `Sum()` to return the sum of the mock function's argument #0 and #1. | -|:--------------------------------------|:---------------------------------------------------------------------------------------| -| `ACTION_P(Plus, n) { return arg0 + n; }` | Defines an action `Plus(n)` to return the sum of the mock function's argument #0 and `n`. | -| `ACTION_Pk(Foo, p1, ..., pk) { statements; }` | Defines a parameterized action `Foo(p1, ..., pk)` to execute the given `statements`. | - -The `ACTION*` macros cannot be used inside a function or class. - -# Cardinalities # - -These are used in `Times()` to specify how many times a mock function will be called: - -|`AnyNumber()`|The function can be called any number of times.| -|:------------|:----------------------------------------------| -|`AtLeast(n)` |The call is expected at least `n` times. | -|`AtMost(n)` |The call is expected at most `n` times. | -|`Between(m, n)`|The call is expected between `m` and `n` (inclusive) times.| -|`Exactly(n) or n`|The call is expected exactly `n` times. In particular, the call should never happen when `n` is 0.| - -# Expectation Order # - -By default, the expectations can be matched in _any_ order. If some -or all expectations must be matched in a given order, there are two -ways to specify it. They can be used either independently or -together. - -## The After Clause ## - -``` -using ::testing::Expectation; -... -Expectation init_x = EXPECT_CALL(foo, InitX()); -Expectation init_y = EXPECT_CALL(foo, InitY()); -EXPECT_CALL(foo, Bar()) - .After(init_x, init_y); -``` -says that `Bar()` can be called only after both `InitX()` and -`InitY()` have been called. - -If you don't know how many pre-requisites an expectation has when you -write it, you can use an `ExpectationSet` to collect them: - -``` -using ::testing::ExpectationSet; -... -ExpectationSet all_inits; -for (int i = 0; i < element_count; i++) { - all_inits += EXPECT_CALL(foo, InitElement(i)); -} -EXPECT_CALL(foo, Bar()) - .After(all_inits); -``` -says that `Bar()` can be called only after all elements have been -initialized (but we don't care about which elements get initialized -before the others). - -Modifying an `ExpectationSet` after using it in an `.After()` doesn't -affect the meaning of the `.After()`. - -## Sequences ## - -When you have a long chain of sequential expectations, it's easier to -specify the order using **sequences**, which don't require you to given -each expectation in the chain a different name. <i>All expected<br> -calls</i> in the same sequence must occur in the order they are -specified. - -``` -using ::testing::Sequence; -Sequence s1, s2; -... -EXPECT_CALL(foo, Reset()) - .InSequence(s1, s2) - .WillOnce(Return(true)); -EXPECT_CALL(foo, GetSize()) - .InSequence(s1) - .WillOnce(Return(1)); -EXPECT_CALL(foo, Describe(A<const char*>())) - .InSequence(s2) - .WillOnce(Return("dummy")); -``` -says that `Reset()` must be called before _both_ `GetSize()` _and_ -`Describe()`, and the latter two can occur in any order. - -To put many expectations in a sequence conveniently: -``` -using ::testing::InSequence; -{ - InSequence dummy; - - EXPECT_CALL(...)...; - EXPECT_CALL(...)...; - ... - EXPECT_CALL(...)...; -} -``` -says that all expected calls in the scope of `dummy` must occur in -strict order. The name `dummy` is irrelevant.) - -# Verifying and Resetting a Mock # - -Google Mock will verify the expectations on a mock object when it is destructed, or you can do it earlier: -``` -using ::testing::Mock; -... -// Verifies and removes the expectations on mock_obj; -// returns true iff successful. -Mock::VerifyAndClearExpectations(&mock_obj); -... -// Verifies and removes the expectations on mock_obj; -// also removes the default actions set by ON_CALL(); -// returns true iff successful. -Mock::VerifyAndClear(&mock_obj); -``` - -You can also tell Google Mock that a mock object can be leaked and doesn't -need to be verified: -``` -Mock::AllowLeak(&mock_obj); -``` - -# Mock Classes # - -Google Mock defines a convenient mock class template -``` -class MockFunction<R(A1, ..., An)> { - public: - MOCK_METHODn(Call, R(A1, ..., An)); -}; -``` -See this [recipe](http://code.google.com/p/googlemock/wiki/V1_6_CookBook#Using_Check_Points) for one application of it. - -# Flags # - -| `--gmock_catch_leaked_mocks=0` | Don't report leaked mock objects as failures. | -|:-------------------------------|:----------------------------------------------| -| `--gmock_verbose=LEVEL` | Sets the default verbosity level (`info`, `warning`, or `error`) of Google Mock messages. |
\ No newline at end of file diff --git a/googlemock/docs/v1_6/CookBook.md b/googlemock/docs/v1_6/CookBook.md deleted file mode 100644 index f5975a0..0000000 --- a/googlemock/docs/v1_6/CookBook.md +++ /dev/null @@ -1,3342 +0,0 @@ - - -You can find recipes for using Google Mock here. If you haven't yet, -please read the [ForDummies](V1_6_ForDummies.md) document first to make sure you understand -the basics. - -**Note:** Google Mock lives in the `testing` name space. For -readability, it is recommended to write `using ::testing::Foo;` once in -your file before using the name `Foo` defined by Google Mock. We omit -such `using` statements in this page for brevity, but you should do it -in your own code. - -# Creating Mock Classes # - -## Mocking Private or Protected Methods ## - -You must always put a mock method definition (`MOCK_METHOD*`) in a -`public:` section of the mock class, regardless of the method being -mocked being `public`, `protected`, or `private` in the base class. -This allows `ON_CALL` and `EXPECT_CALL` to reference the mock function -from outside of the mock class. (Yes, C++ allows a subclass to change -the access level of a virtual function in the base class.) Example: - -``` -class Foo { - public: - ... - virtual bool Transform(Gadget* g) = 0; - - protected: - virtual void Resume(); - - private: - virtual int GetTimeOut(); -}; - -class MockFoo : public Foo { - public: - ... - MOCK_METHOD1(Transform, bool(Gadget* g)); - - // The following must be in the public section, even though the - // methods are protected or private in the base class. - MOCK_METHOD0(Resume, void()); - MOCK_METHOD0(GetTimeOut, int()); -}; -``` - -## Mocking Overloaded Methods ## - -You can mock overloaded functions as usual. No special attention is required: - -``` -class Foo { - ... - - // Must be virtual as we'll inherit from Foo. - virtual ~Foo(); - - // Overloaded on the types and/or numbers of arguments. - virtual int Add(Element x); - virtual int Add(int times, Element x); - - // Overloaded on the const-ness of this object. - virtual Bar& GetBar(); - virtual const Bar& GetBar() const; -}; - -class MockFoo : public Foo { - ... - MOCK_METHOD1(Add, int(Element x)); - MOCK_METHOD2(Add, int(int times, Element x); - - MOCK_METHOD0(GetBar, Bar&()); - MOCK_CONST_METHOD0(GetBar, const Bar&()); -}; -``` - -**Note:** if you don't mock all versions of the overloaded method, the -compiler will give you a warning about some methods in the base class -being hidden. To fix that, use `using` to bring them in scope: - -``` -class MockFoo : public Foo { - ... - using Foo::Add; - MOCK_METHOD1(Add, int(Element x)); - // We don't want to mock int Add(int times, Element x); - ... -}; -``` - -## Mocking Class Templates ## - -To mock a class template, append `_T` to the `MOCK_*` macros: - -``` -template <typename Elem> -class StackInterface { - ... - // Must be virtual as we'll inherit from StackInterface. - virtual ~StackInterface(); - - virtual int GetSize() const = 0; - virtual void Push(const Elem& x) = 0; -}; - -template <typename Elem> -class MockStack : public StackInterface<Elem> { - ... - MOCK_CONST_METHOD0_T(GetSize, int()); - MOCK_METHOD1_T(Push, void(const Elem& x)); -}; -``` - -## Mocking Nonvirtual Methods ## - -Google Mock can mock non-virtual functions to be used in what we call _hi-perf -dependency injection_. - -In this case, instead of sharing a common base class with the real -class, your mock class will be _unrelated_ to the real class, but -contain methods with the same signatures. The syntax for mocking -non-virtual methods is the _same_ as mocking virtual methods: - -``` -// A simple packet stream class. None of its members is virtual. -class ConcretePacketStream { - public: - void AppendPacket(Packet* new_packet); - const Packet* GetPacket(size_t packet_number) const; - size_t NumberOfPackets() const; - ... -}; - -// A mock packet stream class. It inherits from no other, but defines -// GetPacket() and NumberOfPackets(). -class MockPacketStream { - public: - MOCK_CONST_METHOD1(GetPacket, const Packet*(size_t packet_number)); - MOCK_CONST_METHOD0(NumberOfPackets, size_t()); - ... -}; -``` - -Note that the mock class doesn't define `AppendPacket()`, unlike the -real class. That's fine as long as the test doesn't need to call it. - -Next, you need a way to say that you want to use -`ConcretePacketStream` in production code, and use `MockPacketStream` -in tests. Since the functions are not virtual and the two classes are -unrelated, you must specify your choice at _compile time_ (as opposed -to run time). - -One way to do it is to templatize your code that needs to use a packet -stream. More specifically, you will give your code a template type -argument for the type of the packet stream. In production, you will -instantiate your template with `ConcretePacketStream` as the type -argument. In tests, you will instantiate the same template with -`MockPacketStream`. For example, you may write: - -``` -template <class PacketStream> -void CreateConnection(PacketStream* stream) { ... } - -template <class PacketStream> -class PacketReader { - public: - void ReadPackets(PacketStream* stream, size_t packet_num); -}; -``` - -Then you can use `CreateConnection<ConcretePacketStream>()` and -`PacketReader<ConcretePacketStream>` in production code, and use -`CreateConnection<MockPacketStream>()` and -`PacketReader<MockPacketStream>` in tests. - -``` - MockPacketStream mock_stream; - EXPECT_CALL(mock_stream, ...)...; - .. set more expectations on mock_stream ... - PacketReader<MockPacketStream> reader(&mock_stream); - ... exercise reader ... -``` - -## Mocking Free Functions ## - -It's possible to use Google Mock to mock a free function (i.e. a -C-style function or a static method). You just need to rewrite your -code to use an interface (abstract class). - -Instead of calling a free function (say, `OpenFile`) directly, -introduce an interface for it and have a concrete subclass that calls -the free function: - -``` -class FileInterface { - public: - ... - virtual bool Open(const char* path, const char* mode) = 0; -}; - -class File : public FileInterface { - public: - ... - virtual bool Open(const char* path, const char* mode) { - return OpenFile(path, mode); - } -}; -``` - -Your code should talk to `FileInterface` to open a file. Now it's -easy to mock out the function. - -This may seem much hassle, but in practice you often have multiple -related functions that you can put in the same interface, so the -per-function syntactic overhead will be much lower. - -If you are concerned about the performance overhead incurred by -virtual functions, and profiling confirms your concern, you can -combine this with the recipe for [mocking non-virtual methods](#Mocking_Nonvirtual_Methods.md). - -## Nice Mocks and Strict Mocks ## - -If a mock method has no `EXPECT_CALL` spec but is called, Google Mock -will print a warning about the "uninteresting call". The rationale is: - - * New methods may be added to an interface after a test is written. We shouldn't fail a test just because a method it doesn't know about is called. - * However, this may also mean there's a bug in the test, so Google Mock shouldn't be silent either. If the user believes these calls are harmless, he can add an `EXPECT_CALL()` to suppress the warning. - -However, sometimes you may want to suppress all "uninteresting call" -warnings, while sometimes you may want the opposite, i.e. to treat all -of them as errors. Google Mock lets you make the decision on a -per-mock-object basis. - -Suppose your test uses a mock class `MockFoo`: - -``` -TEST(...) { - MockFoo mock_foo; - EXPECT_CALL(mock_foo, DoThis()); - ... code that uses mock_foo ... -} -``` - -If a method of `mock_foo` other than `DoThis()` is called, it will be -reported by Google Mock as a warning. However, if you rewrite your -test to use `NiceMock<MockFoo>` instead, the warning will be gone, -resulting in a cleaner test output: - -``` -using ::testing::NiceMock; - -TEST(...) { - NiceMock<MockFoo> mock_foo; - EXPECT_CALL(mock_foo, DoThis()); - ... code that uses mock_foo ... -} -``` - -`NiceMock<MockFoo>` is a subclass of `MockFoo`, so it can be used -wherever `MockFoo` is accepted. - -It also works if `MockFoo`'s constructor takes some arguments, as -`NiceMock<MockFoo>` "inherits" `MockFoo`'s constructors: - -``` -using ::testing::NiceMock; - -TEST(...) { - NiceMock<MockFoo> mock_foo(5, "hi"); // Calls MockFoo(5, "hi"). - EXPECT_CALL(mock_foo, DoThis()); - ... code that uses mock_foo ... -} -``` - -The usage of `StrictMock` is similar, except that it makes all -uninteresting calls failures: - -``` -using ::testing::StrictMock; - -TEST(...) { - StrictMock<MockFoo> mock_foo; - EXPECT_CALL(mock_foo, DoThis()); - ... code that uses mock_foo ... - - // The test will fail if a method of mock_foo other than DoThis() - // is called. -} -``` - -There are some caveats though (I don't like them just as much as the -next guy, but sadly they are side effects of C++'s limitations): - - 1. `NiceMock<MockFoo>` and `StrictMock<MockFoo>` only work for mock methods defined using the `MOCK_METHOD*` family of macros **directly** in the `MockFoo` class. If a mock method is defined in a **base class** of `MockFoo`, the "nice" or "strict" modifier may not affect it, depending on the compiler. In particular, nesting `NiceMock` and `StrictMock` (e.g. `NiceMock<StrictMock<MockFoo> >`) is **not** supported. - 1. The constructors of the base mock (`MockFoo`) cannot have arguments passed by non-const reference, which happens to be banned by the [Google C++ style guide](http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml). - 1. During the constructor or destructor of `MockFoo`, the mock object is _not_ nice or strict. This may cause surprises if the constructor or destructor calls a mock method on `this` object. (This behavior, however, is consistent with C++'s general rule: if a constructor or destructor calls a virtual method of `this` object, that method is treated as non-virtual. In other words, to the base class's constructor or destructor, `this` object behaves like an instance of the base class, not the derived class. This rule is required for safety. Otherwise a base constructor may use members of a derived class before they are initialized, or a base destructor may use members of a derived class after they have been destroyed.) - -Finally, you should be **very cautious** when using this feature, as the -decision you make applies to **all** future changes to the mock -class. If an important change is made in the interface you are mocking -(and thus in the mock class), it could break your tests (if you use -`StrictMock`) or let bugs pass through without a warning (if you use -`NiceMock`). Therefore, try to specify the mock's behavior using -explicit `EXPECT_CALL` first, and only turn to `NiceMock` or -`StrictMock` as the last resort. - -## Simplifying the Interface without Breaking Existing Code ## - -Sometimes a method has a long list of arguments that is mostly -uninteresting. For example, - -``` -class LogSink { - public: - ... - virtual void send(LogSeverity severity, const char* full_filename, - const char* base_filename, int line, - const struct tm* tm_time, - const char* message, size_t message_len) = 0; -}; -``` - -This method's argument list is lengthy and hard to work with (let's -say that the `message` argument is not even 0-terminated). If we mock -it as is, using the mock will be awkward. If, however, we try to -simplify this interface, we'll need to fix all clients depending on -it, which is often infeasible. - -The trick is to re-dispatch the method in the mock class: - -``` -class ScopedMockLog : public LogSink { - public: - ... - virtual void send(LogSeverity severity, const char* full_filename, - const char* base_filename, int line, const tm* tm_time, - const char* message, size_t message_len) { - // We are only interested in the log severity, full file name, and - // log message. - Log(severity, full_filename, std::string(message, message_len)); - } - - // Implements the mock method: - // - // void Log(LogSeverity severity, - // const string& file_path, - // const string& message); - MOCK_METHOD3(Log, void(LogSeverity severity, const string& file_path, - const string& message)); -}; -``` - -By defining a new mock method with a trimmed argument list, we make -the mock class much more user-friendly. - -## Alternative to Mocking Concrete Classes ## - -Often you may find yourself using classes that don't implement -interfaces. In order to test your code that uses such a class (let's -call it `Concrete`), you may be tempted to make the methods of -`Concrete` virtual and then mock it. - -Try not to do that. - -Making a non-virtual function virtual is a big decision. It creates an -extension point where subclasses can tweak your class' behavior. This -weakens your control on the class because now it's harder to maintain -the class' invariants. You should make a function virtual only when -there is a valid reason for a subclass to override it. - -Mocking concrete classes directly is problematic as it creates a tight -coupling between the class and the tests - any small change in the -class may invalidate your tests and make test maintenance a pain. - -To avoid such problems, many programmers have been practicing "coding -to interfaces": instead of talking to the `Concrete` class, your code -would define an interface and talk to it. Then you implement that -interface as an adaptor on top of `Concrete`. In tests, you can easily -mock that interface to observe how your code is doing. - -This technique incurs some overhead: - - * You pay the cost of virtual function calls (usually not a problem). - * There is more abstraction for the programmers to learn. - -However, it can also bring significant benefits in addition to better -testability: - - * `Concrete`'s API may not fit your problem domain very well, as you may not be the only client it tries to serve. By designing your own interface, you have a chance to tailor it to your need - you may add higher-level functionalities, rename stuff, etc instead of just trimming the class. This allows you to write your code (user of the interface) in a more natural way, which means it will be more readable, more maintainable, and you'll be more productive. - * If `Concrete`'s implementation ever has to change, you don't have to rewrite everywhere it is used. Instead, you can absorb the change in your implementation of the interface, and your other code and tests will be insulated from this change. - -Some people worry that if everyone is practicing this technique, they -will end up writing lots of redundant code. This concern is totally -understandable. However, there are two reasons why it may not be the -case: - - * Different projects may need to use `Concrete` in different ways, so the best interfaces for them will be different. Therefore, each of them will have its own domain-specific interface on top of `Concrete`, and they will not be the same code. - * If enough projects want to use the same interface, they can always share it, just like they have been sharing `Concrete`. You can check in the interface and the adaptor somewhere near `Concrete` (perhaps in a `contrib` sub-directory) and let many projects use it. - -You need to weigh the pros and cons carefully for your particular -problem, but I'd like to assure you that the Java community has been -practicing this for a long time and it's a proven effective technique -applicable in a wide variety of situations. :-) - -## Delegating Calls to a Fake ## - -Some times you have a non-trivial fake implementation of an -interface. For example: - -``` -class Foo { - public: - virtual ~Foo() {} - virtual char DoThis(int n) = 0; - virtual void DoThat(const char* s, int* p) = 0; -}; - -class FakeFoo : public Foo { - public: - virtual char DoThis(int n) { - return (n > 0) ? '+' : - (n < 0) ? '-' : '0'; - } - - virtual void DoThat(const char* s, int* p) { - *p = strlen(s); - } -}; -``` - -Now you want to mock this interface such that you can set expectations -on it. However, you also want to use `FakeFoo` for the default -behavior, as duplicating it in the mock object is, well, a lot of -work. - -When you define the mock class using Google Mock, you can have it -delegate its default action to a fake class you already have, using -this pattern: - -``` -using ::testing::_; -using ::testing::Invoke; - -class MockFoo : public Foo { - public: - // Normal mock method definitions using Google Mock. - MOCK_METHOD1(DoThis, char(int n)); - MOCK_METHOD2(DoThat, void(const char* s, int* p)); - - // Delegates the default actions of the methods to a FakeFoo object. - // This must be called *before* the custom ON_CALL() statements. - void DelegateToFake() { - ON_CALL(*this, DoThis(_)) - .WillByDefault(Invoke(&fake_, &FakeFoo::DoThis)); - ON_CALL(*this, DoThat(_, _)) - .WillByDefault(Invoke(&fake_, &FakeFoo::DoThat)); - } - private: - FakeFoo fake_; // Keeps an instance of the fake in the mock. -}; -``` - -With that, you can use `MockFoo` in your tests as usual. Just remember -that if you don't explicitly set an action in an `ON_CALL()` or -`EXPECT_CALL()`, the fake will be called upon to do it: - -``` -using ::testing::_; - -TEST(AbcTest, Xyz) { - MockFoo foo; - foo.DelegateToFake(); // Enables the fake for delegation. - - // Put your ON_CALL(foo, ...)s here, if any. - - // No action specified, meaning to use the default action. - EXPECT_CALL(foo, DoThis(5)); - EXPECT_CALL(foo, DoThat(_, _)); - - int n = 0; - EXPECT_EQ('+', foo.DoThis(5)); // FakeFoo::DoThis() is invoked. - foo.DoThat("Hi", &n); // FakeFoo::DoThat() is invoked. - EXPECT_EQ(2, n); -} -``` - -**Some tips:** - - * If you want, you can still override the default action by providing your own `ON_CALL()` or using `.WillOnce()` / `.WillRepeatedly()` in `EXPECT_CALL()`. - * In `DelegateToFake()`, you only need to delegate the methods whose fake implementation you intend to use. - * The general technique discussed here works for overloaded methods, but you'll need to tell the compiler which version you mean. To disambiguate a mock function (the one you specify inside the parentheses of `ON_CALL()`), see the "Selecting Between Overloaded Functions" section on this page; to disambiguate a fake function (the one you place inside `Invoke()`), use a `static_cast` to specify the function's type. - * Having to mix a mock and a fake is often a sign of something gone wrong. Perhaps you haven't got used to the interaction-based way of testing yet. Or perhaps your interface is taking on too many roles and should be split up. Therefore, **don't abuse this**. We would only recommend to do it as an intermediate step when you are refactoring your code. - -Regarding the tip on mixing a mock and a fake, here's an example on -why it may be a bad sign: Suppose you have a class `System` for -low-level system operations. In particular, it does file and I/O -operations. And suppose you want to test how your code uses `System` -to do I/O, and you just want the file operations to work normally. If -you mock out the entire `System` class, you'll have to provide a fake -implementation for the file operation part, which suggests that -`System` is taking on too many roles. - -Instead, you can define a `FileOps` interface and an `IOOps` interface -and split `System`'s functionalities into the two. Then you can mock -`IOOps` without mocking `FileOps`. - -## Delegating Calls to a Real Object ## - -When using testing doubles (mocks, fakes, stubs, and etc), sometimes -their behaviors will differ from those of the real objects. This -difference could be either intentional (as in simulating an error such -that you can test the error handling code) or unintentional. If your -mocks have different behaviors than the real objects by mistake, you -could end up with code that passes the tests but fails in production. - -You can use the _delegating-to-real_ technique to ensure that your -mock has the same behavior as the real object while retaining the -ability to validate calls. This technique is very similar to the -delegating-to-fake technique, the difference being that we use a real -object instead of a fake. Here's an example: - -``` -using ::testing::_; -using ::testing::AtLeast; -using ::testing::Invoke; - -class MockFoo : public Foo { - public: - MockFoo() { - // By default, all calls are delegated to the real object. - ON_CALL(*this, DoThis()) - .WillByDefault(Invoke(&real_, &Foo::DoThis)); - ON_CALL(*this, DoThat(_)) - .WillByDefault(Invoke(&real_, &Foo::DoThat)); - ... - } - MOCK_METHOD0(DoThis, ...); - MOCK_METHOD1(DoThat, ...); - ... - private: - Foo real_; -}; -... - - MockFoo mock; - - EXPECT_CALL(mock, DoThis()) - .Times(3); - EXPECT_CALL(mock, DoThat("Hi")) - .Times(AtLeast(1)); - ... use mock in test ... -``` - -With this, Google Mock will verify that your code made the right calls -(with the right arguments, in the right order, called the right number -of times, etc), and a real object will answer the calls (so the -behavior will be the same as in production). This gives you the best -of both worlds. - -## Delegating Calls to a Parent Class ## - -Ideally, you should code to interfaces, whose methods are all pure -virtual. In reality, sometimes you do need to mock a virtual method -that is not pure (i.e, it already has an implementation). For example: - -``` -class Foo { - public: - virtual ~Foo(); - - virtual void Pure(int n) = 0; - virtual int Concrete(const char* str) { ... } -}; - -class MockFoo : public Foo { - public: - // Mocking a pure method. - MOCK_METHOD1(Pure, void(int n)); - // Mocking a concrete method. Foo::Concrete() is shadowed. - MOCK_METHOD1(Concrete, int(const char* str)); -}; -``` - -Sometimes you may want to call `Foo::Concrete()` instead of -`MockFoo::Concrete()`. Perhaps you want to do it as part of a stub -action, or perhaps your test doesn't need to mock `Concrete()` at all -(but it would be oh-so painful to have to define a new mock class -whenever you don't need to mock one of its methods). - -The trick is to leave a back door in your mock class for accessing the -real methods in the base class: - -``` -class MockFoo : public Foo { - public: - // Mocking a pure method. - MOCK_METHOD1(Pure, void(int n)); - // Mocking a concrete method. Foo::Concrete() is shadowed. - MOCK_METHOD1(Concrete, int(const char* str)); - - // Use this to call Concrete() defined in Foo. - int FooConcrete(const char* str) { return Foo::Concrete(str); } -}; -``` - -Now, you can call `Foo::Concrete()` inside an action by: - -``` -using ::testing::_; -using ::testing::Invoke; -... - EXPECT_CALL(foo, Concrete(_)) - .WillOnce(Invoke(&foo, &MockFoo::FooConcrete)); -``` - -or tell the mock object that you don't want to mock `Concrete()`: - -``` -using ::testing::Invoke; -... - ON_CALL(foo, Concrete(_)) - .WillByDefault(Invoke(&foo, &MockFoo::FooConcrete)); -``` - -(Why don't we just write `Invoke(&foo, &Foo::Concrete)`? If you do -that, `MockFoo::Concrete()` will be called (and cause an infinite -recursion) since `Foo::Concrete()` is virtual. That's just how C++ -works.) - -# Using Matchers # - -## Matching Argument Values Exactly ## - -You can specify exactly which arguments a mock method is expecting: - -``` -using ::testing::Return; -... - EXPECT_CALL(foo, DoThis(5)) - .WillOnce(Return('a')); - EXPECT_CALL(foo, DoThat("Hello", bar)); -``` - -## Using Simple Matchers ## - -You can use matchers to match arguments that have a certain property: - -``` -using ::testing::Ge; -using ::testing::NotNull; -using ::testing::Return; -... - EXPECT_CALL(foo, DoThis(Ge(5))) // The argument must be >= 5. - .WillOnce(Return('a')); - EXPECT_CALL(foo, DoThat("Hello", NotNull())); - // The second argument must not be NULL. -``` - -A frequently used matcher is `_`, which matches anything: - -``` -using ::testing::_; -using ::testing::NotNull; -... - EXPECT_CALL(foo, DoThat(_, NotNull())); -``` - -## Combining Matchers ## - -You can build complex matchers from existing ones using `AllOf()`, -`AnyOf()`, and `Not()`: - -``` -using ::testing::AllOf; -using ::testing::Gt; -using ::testing::HasSubstr; -using ::testing::Ne; -using ::testing::Not; -... - // The argument must be > 5 and != 10. - EXPECT_CALL(foo, DoThis(AllOf(Gt(5), - Ne(10)))); - - // The first argument must not contain sub-string "blah". - EXPECT_CALL(foo, DoThat(Not(HasSubstr("blah")), - NULL)); -``` - -## Casting Matchers ## - -Google Mock matchers are statically typed, meaning that the compiler -can catch your mistake if you use a matcher of the wrong type (for -example, if you use `Eq(5)` to match a `string` argument). Good for -you! - -Sometimes, however, you know what you're doing and want the compiler -to give you some slack. One example is that you have a matcher for -`long` and the argument you want to match is `int`. While the two -types aren't exactly the same, there is nothing really wrong with -using a `Matcher<long>` to match an `int` - after all, we can first -convert the `int` argument to a `long` before giving it to the -matcher. - -To support this need, Google Mock gives you the -`SafeMatcherCast<T>(m)` function. It casts a matcher `m` to type -`Matcher<T>`. To ensure safety, Google Mock checks that (let `U` be the -type `m` accepts): - - 1. Type `T` can be implicitly cast to type `U`; - 1. When both `T` and `U` are built-in arithmetic types (`bool`, integers, and floating-point numbers), the conversion from `T` to `U` is not lossy (in other words, any value representable by `T` can also be represented by `U`); and - 1. When `U` is a reference, `T` must also be a reference (as the underlying matcher may be interested in the address of the `U` value). - -The code won't compile if any of these conditions isn't met. - -Here's one example: - -``` -using ::testing::SafeMatcherCast; - -// A base class and a child class. -class Base { ... }; -class Derived : public Base { ... }; - -class MockFoo : public Foo { - public: - MOCK_METHOD1(DoThis, void(Derived* derived)); -}; -... - - MockFoo foo; - // m is a Matcher<Base*> we got from somewhere. - EXPECT_CALL(foo, DoThis(SafeMatcherCast<Derived*>(m))); -``` - -If you find `SafeMatcherCast<T>(m)` too limiting, you can use a similar -function `MatcherCast<T>(m)`. The difference is that `MatcherCast` works -as long as you can `static_cast` type `T` to type `U`. - -`MatcherCast` essentially lets you bypass C++'s type system -(`static_cast` isn't always safe as it could throw away information, -for example), so be careful not to misuse/abuse it. - -## Selecting Between Overloaded Functions ## - -If you expect an overloaded function to be called, the compiler may -need some help on which overloaded version it is. - -To disambiguate functions overloaded on the const-ness of this object, -use the `Const()` argument wrapper. - -``` -using ::testing::ReturnRef; - -class MockFoo : public Foo { - ... - MOCK_METHOD0(GetBar, Bar&()); - MOCK_CONST_METHOD0(GetBar, const Bar&()); -}; -... - - MockFoo foo; - Bar bar1, bar2; - EXPECT_CALL(foo, GetBar()) // The non-const GetBar(). - .WillOnce(ReturnRef(bar1)); - EXPECT_CALL(Const(foo), GetBar()) // The const GetBar(). - .WillOnce(ReturnRef(bar2)); -``` - -(`Const()` is defined by Google Mock and returns a `const` reference -to its argument.) - -To disambiguate overloaded functions with the same number of arguments -but different argument types, you may need to specify the exact type -of a matcher, either by wrapping your matcher in `Matcher<type>()`, or -using a matcher whose type is fixed (`TypedEq<type>`, `An<type>()`, -etc): - -``` -using ::testing::An; -using ::testing::Lt; -using ::testing::Matcher; -using ::testing::TypedEq; - -class MockPrinter : public Printer { - public: - MOCK_METHOD1(Print, void(int n)); - MOCK_METHOD1(Print, void(char c)); -}; - -TEST(PrinterTest, Print) { - MockPrinter printer; - - EXPECT_CALL(printer, Print(An<int>())); // void Print(int); - EXPECT_CALL(printer, Print(Matcher<int>(Lt(5)))); // void Print(int); - EXPECT_CALL(printer, Print(TypedEq<char>('a'))); // void Print(char); - - printer.Print(3); - printer.Print(6); - printer.Print('a'); -} -``` - -## Performing Different Actions Based on the Arguments ## - -When a mock method is called, the _last_ matching expectation that's -still active will be selected (think "newer overrides older"). So, you -can make a method do different things depending on its argument values -like this: - -``` -using ::testing::_; -using ::testing::Lt; -using ::testing::Return; -... - // The default case. - EXPECT_CALL(foo, DoThis(_)) - .WillRepeatedly(Return('b')); - - // The more specific case. - EXPECT_CALL(foo, DoThis(Lt(5))) - .WillRepeatedly(Return('a')); -``` - -Now, if `foo.DoThis()` is called with a value less than 5, `'a'` will -be returned; otherwise `'b'` will be returned. - -## Matching Multiple Arguments as a Whole ## - -Sometimes it's not enough to match the arguments individually. For -example, we may want to say that the first argument must be less than -the second argument. The `With()` clause allows us to match -all arguments of a mock function as a whole. For example, - -``` -using ::testing::_; -using ::testing::Lt; -using ::testing::Ne; -... - EXPECT_CALL(foo, InRange(Ne(0), _)) - .With(Lt()); -``` - -says that the first argument of `InRange()` must not be 0, and must be -less than the second argument. - -The expression inside `With()` must be a matcher of type -`Matcher<tr1::tuple<A1, ..., An> >`, where `A1`, ..., `An` are the -types of the function arguments. - -You can also write `AllArgs(m)` instead of `m` inside `.With()`. The -two forms are equivalent, but `.With(AllArgs(Lt()))` is more readable -than `.With(Lt())`. - -You can use `Args<k1, ..., kn>(m)` to match the `n` selected arguments -(as a tuple) against `m`. For example, - -``` -using ::testing::_; -using ::testing::AllOf; -using ::testing::Args; -using ::testing::Lt; -... - EXPECT_CALL(foo, Blah(_, _, _)) - .With(AllOf(Args<0, 1>(Lt()), Args<1, 2>(Lt()))); -``` - -says that `Blah()` will be called with arguments `x`, `y`, and `z` where -`x < y < z`. - -As a convenience and example, Google Mock provides some matchers for -2-tuples, including the `Lt()` matcher above. See the [CheatSheet](V1_6_CheatSheet.md) for -the complete list. - -Note that if you want to pass the arguments to a predicate of your own -(e.g. `.With(Args<0, 1>(Truly(&MyPredicate)))`), that predicate MUST be -written to take a `tr1::tuple` as its argument; Google Mock will pass the `n` -selected arguments as _one_ single tuple to the predicate. - -## Using Matchers as Predicates ## - -Have you noticed that a matcher is just a fancy predicate that also -knows how to describe itself? Many existing algorithms take predicates -as arguments (e.g. those defined in STL's `<algorithm>` header), and -it would be a shame if Google Mock matchers are not allowed to -participate. - -Luckily, you can use a matcher where a unary predicate functor is -expected by wrapping it inside the `Matches()` function. For example, - -``` -#include <algorithm> -#include <vector> - -std::vector<int> v; -... -// How many elements in v are >= 10? -const int count = count_if(v.begin(), v.end(), Matches(Ge(10))); -``` - -Since you can build complex matchers from simpler ones easily using -Google Mock, this gives you a way to conveniently construct composite -predicates (doing the same using STL's `<functional>` header is just -painful). For example, here's a predicate that's satisfied by any -number that is >= 0, <= 100, and != 50: - -``` -Matches(AllOf(Ge(0), Le(100), Ne(50))) -``` - -## Using Matchers in Google Test Assertions ## - -Since matchers are basically predicates that also know how to describe -themselves, there is a way to take advantage of them in -[Google Test](http://code.google.com/p/googletest/) assertions. It's -called `ASSERT_THAT` and `EXPECT_THAT`: - -``` - ASSERT_THAT(value, matcher); // Asserts that value matches matcher. - EXPECT_THAT(value, matcher); // The non-fatal version. -``` - -For example, in a Google Test test you can write: - -``` -#include "gmock/gmock.h" - -using ::testing::AllOf; -using ::testing::Ge; -using ::testing::Le; -using ::testing::MatchesRegex; -using ::testing::StartsWith; -... - - EXPECT_THAT(Foo(), StartsWith("Hello")); - EXPECT_THAT(Bar(), MatchesRegex("Line \\d+")); - ASSERT_THAT(Baz(), AllOf(Ge(5), Le(10))); -``` - -which (as you can probably guess) executes `Foo()`, `Bar()`, and -`Baz()`, and verifies that: - - * `Foo()` returns a string that starts with `"Hello"`. - * `Bar()` returns a string that matches regular expression `"Line \\d+"`. - * `Baz()` returns a number in the range [5, 10]. - -The nice thing about these macros is that _they read like -English_. They generate informative messages too. For example, if the -first `EXPECT_THAT()` above fails, the message will be something like: - -``` -Value of: Foo() - Actual: "Hi, world!" -Expected: starts with "Hello" -``` - -**Credit:** The idea of `(ASSERT|EXPECT)_THAT` was stolen from the -[Hamcrest](http://code.google.com/p/hamcrest/) project, which adds -`assertThat()` to JUnit. - -## Using Predicates as Matchers ## - -Google Mock provides a built-in set of matchers. In case you find them -lacking, you can use an arbitray unary predicate function or functor -as a matcher - as long as the predicate accepts a value of the type -you want. You do this by wrapping the predicate inside the `Truly()` -function, for example: - -``` -using ::testing::Truly; - -int IsEven(int n) { return (n % 2) == 0 ? 1 : 0; } -... - - // Bar() must be called with an even number. - EXPECT_CALL(foo, Bar(Truly(IsEven))); -``` - -Note that the predicate function / functor doesn't have to return -`bool`. It works as long as the return value can be used as the -condition in statement `if (condition) ...`. - -## Matching Arguments that Are Not Copyable ## - -When you do an `EXPECT_CALL(mock_obj, Foo(bar))`, Google Mock saves -away a copy of `bar`. When `Foo()` is called later, Google Mock -compares the argument to `Foo()` with the saved copy of `bar`. This -way, you don't need to worry about `bar` being modified or destroyed -after the `EXPECT_CALL()` is executed. The same is true when you use -matchers like `Eq(bar)`, `Le(bar)`, and so on. - -But what if `bar` cannot be copied (i.e. has no copy constructor)? You -could define your own matcher function and use it with `Truly()`, as -the previous couple of recipes have shown. Or, you may be able to get -away from it if you can guarantee that `bar` won't be changed after -the `EXPECT_CALL()` is executed. Just tell Google Mock that it should -save a reference to `bar`, instead of a copy of it. Here's how: - -``` -using ::testing::Eq; -using ::testing::ByRef; -using ::testing::Lt; -... - // Expects that Foo()'s argument == bar. - EXPECT_CALL(mock_obj, Foo(Eq(ByRef(bar)))); - - // Expects that Foo()'s argument < bar. - EXPECT_CALL(mock_obj, Foo(Lt(ByRef(bar)))); -``` - -Remember: if you do this, don't change `bar` after the -`EXPECT_CALL()`, or the result is undefined. - -## Validating a Member of an Object ## - -Often a mock function takes a reference to object as an argument. When -matching the argument, you may not want to compare the entire object -against a fixed object, as that may be over-specification. Instead, -you may need to validate a certain member variable or the result of a -certain getter method of the object. You can do this with `Field()` -and `Property()`. More specifically, - -``` -Field(&Foo::bar, m) -``` - -is a matcher that matches a `Foo` object whose `bar` member variable -satisfies matcher `m`. - -``` -Property(&Foo::baz, m) -``` - -is a matcher that matches a `Foo` object whose `baz()` method returns -a value that satisfies matcher `m`. - -For example: - -> | `Field(&Foo::number, Ge(3))` | Matches `x` where `x.number >= 3`. | -|:-----------------------------|:-----------------------------------| -> | `Property(&Foo::name, StartsWith("John "))` | Matches `x` where `x.name()` starts with `"John "`. | - -Note that in `Property(&Foo::baz, ...)`, method `baz()` must take no -argument and be declared as `const`. - -BTW, `Field()` and `Property()` can also match plain pointers to -objects. For instance, - -``` -Field(&Foo::number, Ge(3)) -``` - -matches a plain pointer `p` where `p->number >= 3`. If `p` is `NULL`, -the match will always fail regardless of the inner matcher. - -What if you want to validate more than one members at the same time? -Remember that there is `AllOf()`. - -## Validating the Value Pointed to by a Pointer Argument ## - -C++ functions often take pointers as arguments. You can use matchers -like `NULL`, `NotNull()`, and other comparison matchers to match a -pointer, but what if you want to make sure the value _pointed to_ by -the pointer, instead of the pointer itself, has a certain property? -Well, you can use the `Pointee(m)` matcher. - -`Pointee(m)` matches a pointer iff `m` matches the value the pointer -points to. For example: - -``` -using ::testing::Ge; -using ::testing::Pointee; -... - EXPECT_CALL(foo, Bar(Pointee(Ge(3)))); -``` - -expects `foo.Bar()` to be called with a pointer that points to a value -greater than or equal to 3. - -One nice thing about `Pointee()` is that it treats a `NULL` pointer as -a match failure, so you can write `Pointee(m)` instead of - -``` - AllOf(NotNull(), Pointee(m)) -``` - -without worrying that a `NULL` pointer will crash your test. - -Also, did we tell you that `Pointee()` works with both raw pointers -**and** smart pointers (`linked_ptr`, `shared_ptr`, `scoped_ptr`, and -etc)? - -What if you have a pointer to pointer? You guessed it - you can use -nested `Pointee()` to probe deeper inside the value. For example, -`Pointee(Pointee(Lt(3)))` matches a pointer that points to a pointer -that points to a number less than 3 (what a mouthful...). - -## Testing a Certain Property of an Object ## - -Sometimes you want to specify that an object argument has a certain -property, but there is no existing matcher that does this. If you want -good error messages, you should define a matcher. If you want to do it -quick and dirty, you could get away with writing an ordinary function. - -Let's say you have a mock function that takes an object of type `Foo`, -which has an `int bar()` method and an `int baz()` method, and you -want to constrain that the argument's `bar()` value plus its `baz()` -value is a given number. Here's how you can define a matcher to do it: - -``` -using ::testing::MatcherInterface; -using ::testing::MatchResultListener; - -class BarPlusBazEqMatcher : public MatcherInterface<const Foo&> { - public: - explicit BarPlusBazEqMatcher(int expected_sum) - : expected_sum_(expected_sum) {} - - virtual bool MatchAndExplain(const Foo& foo, - MatchResultListener* listener) const { - return (foo.bar() + foo.baz()) == expected_sum_; - } - - virtual void DescribeTo(::std::ostream* os) const { - *os << "bar() + baz() equals " << expected_sum_; - } - - virtual void DescribeNegationTo(::std::ostream* os) const { - *os << "bar() + baz() does not equal " << expected_sum_; - } - private: - const int expected_sum_; -}; - -inline Matcher<const Foo&> BarPlusBazEq(int expected_sum) { - return MakeMatcher(new BarPlusBazEqMatcher(expected_sum)); -} - -... - - EXPECT_CALL(..., DoThis(BarPlusBazEq(5)))...; -``` - -## Matching Containers ## - -Sometimes an STL container (e.g. list, vector, map, ...) is passed to -a mock function and you may want to validate it. Since most STL -containers support the `==` operator, you can write -`Eq(expected_container)` or simply `expected_container` to match a -container exactly. - -Sometimes, though, you may want to be more flexible (for example, the -first element must be an exact match, but the second element can be -any positive number, and so on). Also, containers used in tests often -have a small number of elements, and having to define the expected -container out-of-line is a bit of a hassle. - -You can use the `ElementsAre()` matcher in such cases: - -``` -using ::testing::_; -using ::testing::ElementsAre; -using ::testing::Gt; -... - - MOCK_METHOD1(Foo, void(const vector<int>& numbers)); -... - - EXPECT_CALL(mock, Foo(ElementsAre(1, Gt(0), _, 5))); -``` - -The above matcher says that the container must have 4 elements, which -must be 1, greater than 0, anything, and 5 respectively. - -`ElementsAre()` is overloaded to take 0 to 10 arguments. If more are -needed, you can place them in a C-style array and use -`ElementsAreArray()` instead: - -``` -using ::testing::ElementsAreArray; -... - - // ElementsAreArray accepts an array of element values. - const int expected_vector1[] = { 1, 5, 2, 4, ... }; - EXPECT_CALL(mock, Foo(ElementsAreArray(expected_vector1))); - - // Or, an array of element matchers. - Matcher<int> expected_vector2 = { 1, Gt(2), _, 3, ... }; - EXPECT_CALL(mock, Foo(ElementsAreArray(expected_vector2))); -``` - -In case the array needs to be dynamically created (and therefore the -array size cannot be inferred by the compiler), you can give -`ElementsAreArray()` an additional argument to specify the array size: - -``` -using ::testing::ElementsAreArray; -... - int* const expected_vector3 = new int[count]; - ... fill expected_vector3 with values ... - EXPECT_CALL(mock, Foo(ElementsAreArray(expected_vector3, count))); -``` - -**Tips:** - - * `ElementAre*()` works with _any_ container that implements the STL iterator concept (i.e. it has a `const_iterator` type and supports `begin()/end()`) and supports `size()`, not just the ones defined in STL. It will even work with container types yet to be written - as long as they follows the above pattern. - * You can use nested `ElementAre*()` to match nested (multi-dimensional) containers. - * If the container is passed by pointer instead of by reference, just write `Pointee(ElementsAre*(...))`. - * The order of elements _matters_ for `ElementsAre*()`. Therefore don't use it with containers whose element order is undefined (e.g. `hash_map`). - -## Sharing Matchers ## - -Under the hood, a Google Mock matcher object consists of a pointer to -a ref-counted implementation object. Copying matchers is allowed and -very efficient, as only the pointer is copied. When the last matcher -that references the implementation object dies, the implementation -object will be deleted. - -Therefore, if you have some complex matcher that you want to use again -and again, there is no need to build it everytime. Just assign it to a -matcher variable and use that variable repeatedly! For example, - -``` - Matcher<int> in_range = AllOf(Gt(5), Le(10)); - ... use in_range as a matcher in multiple EXPECT_CALLs ... -``` - -# Setting Expectations # - -## Ignoring Uninteresting Calls ## - -If you are not interested in how a mock method is called, just don't -say anything about it. In this case, if the method is ever called, -Google Mock will perform its default action to allow the test program -to continue. If you are not happy with the default action taken by -Google Mock, you can override it using `DefaultValue<T>::Set()` -(described later in this document) or `ON_CALL()`. - -Please note that once you expressed interest in a particular mock -method (via `EXPECT_CALL()`), all invocations to it must match some -expectation. If this function is called but the arguments don't match -any `EXPECT_CALL()` statement, it will be an error. - -## Disallowing Unexpected Calls ## - -If a mock method shouldn't be called at all, explicitly say so: - -``` -using ::testing::_; -... - EXPECT_CALL(foo, Bar(_)) - .Times(0); -``` - -If some calls to the method are allowed, but the rest are not, just -list all the expected calls: - -``` -using ::testing::AnyNumber; -using ::testing::Gt; -... - EXPECT_CALL(foo, Bar(5)); - EXPECT_CALL(foo, Bar(Gt(10))) - .Times(AnyNumber()); -``` - -A call to `foo.Bar()` that doesn't match any of the `EXPECT_CALL()` -statements will be an error. - -## Expecting Ordered Calls ## - -Although an `EXPECT_CALL()` statement defined earlier takes precedence -when Google Mock tries to match a function call with an expectation, -by default calls don't have to happen in the order `EXPECT_CALL()` -statements are written. For example, if the arguments match the -matchers in the third `EXPECT_CALL()`, but not those in the first two, -then the third expectation will be used. - -If you would rather have all calls occur in the order of the -expectations, put the `EXPECT_CALL()` statements in a block where you -define a variable of type `InSequence`: - -``` - using ::testing::_; - using ::testing::InSequence; - - { - InSequence s; - - EXPECT_CALL(foo, DoThis(5)); - EXPECT_CALL(bar, DoThat(_)) - .Times(2); - EXPECT_CALL(foo, DoThis(6)); - } -``` - -In this example, we expect a call to `foo.DoThis(5)`, followed by two -calls to `bar.DoThat()` where the argument can be anything, which are -in turn followed by a call to `foo.DoThis(6)`. If a call occurred -out-of-order, Google Mock will report an error. - -## Expecting Partially Ordered Calls ## - -Sometimes requiring everything to occur in a predetermined order can -lead to brittle tests. For example, we may care about `A` occurring -before both `B` and `C`, but aren't interested in the relative order -of `B` and `C`. In this case, the test should reflect our real intent, -instead of being overly constraining. - -Google Mock allows you to impose an arbitrary DAG (directed acyclic -graph) on the calls. One way to express the DAG is to use the -[After](http://code.google.com/p/googlemock/wiki/V1_6_CheatSheet#The_After_Clause) clause of `EXPECT_CALL`. - -Another way is via the `InSequence()` clause (not the same as the -`InSequence` class), which we borrowed from jMock 2. It's less -flexible than `After()`, but more convenient when you have long chains -of sequential calls, as it doesn't require you to come up with -different names for the expectations in the chains. Here's how it -works: - -If we view `EXPECT_CALL()` statements as nodes in a graph, and add an -edge from node A to node B wherever A must occur before B, we can get -a DAG. We use the term "sequence" to mean a directed path in this -DAG. Now, if we decompose the DAG into sequences, we just need to know -which sequences each `EXPECT_CALL()` belongs to in order to be able to -reconstruct the orginal DAG. - -So, to specify the partial order on the expectations we need to do two -things: first to define some `Sequence` objects, and then for each -`EXPECT_CALL()` say which `Sequence` objects it is part -of. Expectations in the same sequence must occur in the order they are -written. For example, - -``` - using ::testing::Sequence; - - Sequence s1, s2; - - EXPECT_CALL(foo, A()) - .InSequence(s1, s2); - EXPECT_CALL(bar, B()) - .InSequence(s1); - EXPECT_CALL(bar, C()) - .InSequence(s2); - EXPECT_CALL(foo, D()) - .InSequence(s2); -``` - -specifies the following DAG (where `s1` is `A -> B`, and `s2` is `A -> -C -> D`): - -``` - +---> B - | - A ---| - | - +---> C ---> D -``` - -This means that A must occur before B and C, and C must occur before -D. There's no restriction about the order other than these. - -## Controlling When an Expectation Retires ## - -When a mock method is called, Google Mock only consider expectations -that are still active. An expectation is active when created, and -becomes inactive (aka _retires_) when a call that has to occur later -has occurred. For example, in - -``` - using ::testing::_; - using ::testing::Sequence; - - Sequence s1, s2; - - EXPECT_CALL(log, Log(WARNING, _, "File too large.")) // #1 - .Times(AnyNumber()) - .InSequence(s1, s2); - EXPECT_CALL(log, Log(WARNING, _, "Data set is empty.")) // #2 - .InSequence(s1); - EXPECT_CALL(log, Log(WARNING, _, "User not found.")) // #3 - .InSequence(s2); -``` - -as soon as either #2 or #3 is matched, #1 will retire. If a warning -`"File too large."` is logged after this, it will be an error. - -Note that an expectation doesn't retire automatically when it's -saturated. For example, - -``` -using ::testing::_; -... - EXPECT_CALL(log, Log(WARNING, _, _)); // #1 - EXPECT_CALL(log, Log(WARNING, _, "File too large.")); // #2 -``` - -says that there will be exactly one warning with the message `"File -too large."`. If the second warning contains this message too, #2 will -match again and result in an upper-bound-violated error. - -If this is not what you want, you can ask an expectation to retire as -soon as it becomes saturated: - -``` -using ::testing::_; -... - EXPECT_CALL(log, Log(WARNING, _, _)); // #1 - EXPECT_CALL(log, Log(WARNING, _, "File too large.")) // #2 - .RetiresOnSaturation(); -``` - -Here #2 can be used only once, so if you have two warnings with the -message `"File too large."`, the first will match #2 and the second -will match #1 - there will be no error. - -# Using Actions # - -## Returning References from Mock Methods ## - -If a mock function's return type is a reference, you need to use -`ReturnRef()` instead of `Return()` to return a result: - -``` -using ::testing::ReturnRef; - -class MockFoo : public Foo { - public: - MOCK_METHOD0(GetBar, Bar&()); -}; -... - - MockFoo foo; - Bar bar; - EXPECT_CALL(foo, GetBar()) - .WillOnce(ReturnRef(bar)); -``` - -## Returning Live Values from Mock Methods ## - -The `Return(x)` action saves a copy of `x` when the action is -_created_, and always returns the same value whenever it's -executed. Sometimes you may want to instead return the _live_ value of -`x` (i.e. its value at the time when the action is _executed_.). - -If the mock function's return type is a reference, you can do it using -`ReturnRef(x)`, as shown in the previous recipe ("Returning References -from Mock Methods"). However, Google Mock doesn't let you use -`ReturnRef()` in a mock function whose return type is not a reference, -as doing that usually indicates a user error. So, what shall you do? - -You may be tempted to try `ByRef()`: - -``` -using testing::ByRef; -using testing::Return; - -class MockFoo : public Foo { - public: - MOCK_METHOD0(GetValue, int()); -}; -... - int x = 0; - MockFoo foo; - EXPECT_CALL(foo, GetValue()) - .WillRepeatedly(Return(ByRef(x))); - x = 42; - EXPECT_EQ(42, foo.GetValue()); -``` - -Unfortunately, it doesn't work here. The above code will fail with error: - -``` -Value of: foo.GetValue() - Actual: 0 -Expected: 42 -``` - -The reason is that `Return(value)` converts `value` to the actual -return type of the mock function at the time when the action is -_created_, not when it is _executed_. (This behavior was chosen for -the action to be safe when `value` is a proxy object that references -some temporary objects.) As a result, `ByRef(x)` is converted to an -`int` value (instead of a `const int&`) when the expectation is set, -and `Return(ByRef(x))` will always return 0. - -`ReturnPointee(pointer)` was provided to solve this problem -specifically. It returns the value pointed to by `pointer` at the time -the action is _executed_: - -``` -using testing::ReturnPointee; -... - int x = 0; - MockFoo foo; - EXPECT_CALL(foo, GetValue()) - .WillRepeatedly(ReturnPointee(&x)); // Note the & here. - x = 42; - EXPECT_EQ(42, foo.GetValue()); // This will succeed now. -``` - -## Combining Actions ## - -Want to do more than one thing when a function is called? That's -fine. `DoAll()` allow you to do sequence of actions every time. Only -the return value of the last action in the sequence will be used. - -``` -using ::testing::DoAll; - -class MockFoo : public Foo { - public: - MOCK_METHOD1(Bar, bool(int n)); -}; -... - - EXPECT_CALL(foo, Bar(_)) - .WillOnce(DoAll(action_1, - action_2, - ... - action_n)); -``` - -## Mocking Side Effects ## - -Sometimes a method exhibits its effect not via returning a value but -via side effects. For example, it may change some global state or -modify an output argument. To mock side effects, in general you can -define your own action by implementing `::testing::ActionInterface`. - -If all you need to do is to change an output argument, the built-in -`SetArgPointee()` action is convenient: - -``` -using ::testing::SetArgPointee; - -class MockMutator : public Mutator { - public: - MOCK_METHOD2(Mutate, void(bool mutate, int* value)); - ... -}; -... - - MockMutator mutator; - EXPECT_CALL(mutator, Mutate(true, _)) - .WillOnce(SetArgPointee<1>(5)); -``` - -In this example, when `mutator.Mutate()` is called, we will assign 5 -to the `int` variable pointed to by argument #1 -(0-based). - -`SetArgPointee()` conveniently makes an internal copy of the -value you pass to it, removing the need to keep the value in scope and -alive. The implication however is that the value must have a copy -constructor and assignment operator. - -If the mock method also needs to return a value as well, you can chain -`SetArgPointee()` with `Return()` using `DoAll()`: - -``` -using ::testing::_; -using ::testing::Return; -using ::testing::SetArgPointee; - -class MockMutator : public Mutator { - public: - ... - MOCK_METHOD1(MutateInt, bool(int* value)); -}; -... - - MockMutator mutator; - EXPECT_CALL(mutator, MutateInt(_)) - .WillOnce(DoAll(SetArgPointee<0>(5), - Return(true))); -``` - -If the output argument is an array, use the -`SetArrayArgument<N>(first, last)` action instead. It copies the -elements in source range `[first, last)` to the array pointed to by -the `N`-th (0-based) argument: - -``` -using ::testing::NotNull; -using ::testing::SetArrayArgument; - -class MockArrayMutator : public ArrayMutator { - public: - MOCK_METHOD2(Mutate, void(int* values, int num_values)); - ... -}; -... - - MockArrayMutator mutator; - int values[5] = { 1, 2, 3, 4, 5 }; - EXPECT_CALL(mutator, Mutate(NotNull(), 5)) - .WillOnce(SetArrayArgument<0>(values, values + 5)); -``` - -This also works when the argument is an output iterator: - -``` -using ::testing::_; -using ::testing::SeArrayArgument; - -class MockRolodex : public Rolodex { - public: - MOCK_METHOD1(GetNames, void(std::back_insert_iterator<vector<string> >)); - ... -}; -... - - MockRolodex rolodex; - vector<string> names; - names.push_back("George"); - names.push_back("John"); - names.push_back("Thomas"); - EXPECT_CALL(rolodex, GetNames(_)) - .WillOnce(SetArrayArgument<0>(names.begin(), names.end())); -``` - -## Changing a Mock Object's Behavior Based on the State ## - -If you expect a call to change the behavior of a mock object, you can use `::testing::InSequence` to specify different behaviors before and after the call: - -``` -using ::testing::InSequence; -using ::testing::Return; - -... - { - InSequence seq; - EXPECT_CALL(my_mock, IsDirty()) - .WillRepeatedly(Return(true)); - EXPECT_CALL(my_mock, Flush()); - EXPECT_CALL(my_mock, IsDirty()) - .WillRepeatedly(Return(false)); - } - my_mock.FlushIfDirty(); -``` - -This makes `my_mock.IsDirty()` return `true` before `my_mock.Flush()` is called and return `false` afterwards. - -If the behavior change is more complex, you can store the effects in a variable and make a mock method get its return value from that variable: - -``` -using ::testing::_; -using ::testing::SaveArg; -using ::testing::Return; - -ACTION_P(ReturnPointee, p) { return *p; } -... - int previous_value = 0; - EXPECT_CALL(my_mock, GetPrevValue()) - .WillRepeatedly(ReturnPointee(&previous_value)); - EXPECT_CALL(my_mock, UpdateValue(_)) - .WillRepeatedly(SaveArg<0>(&previous_value)); - my_mock.DoSomethingToUpdateValue(); -``` - -Here `my_mock.GetPrevValue()` will always return the argument of the last `UpdateValue()` call. - -## Setting the Default Value for a Return Type ## - -If a mock method's return type is a built-in C++ type or pointer, by -default it will return 0 when invoked. You only need to specify an -action if this default value doesn't work for you. - -Sometimes, you may want to change this default value, or you may want -to specify a default value for types Google Mock doesn't know -about. You can do this using the `::testing::DefaultValue` class -template: - -``` -class MockFoo : public Foo { - public: - MOCK_METHOD0(CalculateBar, Bar()); -}; -... - - Bar default_bar; - // Sets the default return value for type Bar. - DefaultValue<Bar>::Set(default_bar); - - MockFoo foo; - - // We don't need to specify an action here, as the default - // return value works for us. - EXPECT_CALL(foo, CalculateBar()); - - foo.CalculateBar(); // This should return default_bar. - - // Unsets the default return value. - DefaultValue<Bar>::Clear(); -``` - -Please note that changing the default value for a type can make you -tests hard to understand. We recommend you to use this feature -judiciously. For example, you may want to make sure the `Set()` and -`Clear()` calls are right next to the code that uses your mock. - -## Setting the Default Actions for a Mock Method ## - -You've learned how to change the default value of a given -type. However, this may be too coarse for your purpose: perhaps you -have two mock methods with the same return type and you want them to -have different behaviors. The `ON_CALL()` macro allows you to -customize your mock's behavior at the method level: - -``` -using ::testing::_; -using ::testing::AnyNumber; -using ::testing::Gt; -using ::testing::Return; -... - ON_CALL(foo, Sign(_)) - .WillByDefault(Return(-1)); - ON_CALL(foo, Sign(0)) - .WillByDefault(Return(0)); - ON_CALL(foo, Sign(Gt(0))) - .WillByDefault(Return(1)); - - EXPECT_CALL(foo, Sign(_)) - .Times(AnyNumber()); - - foo.Sign(5); // This should return 1. - foo.Sign(-9); // This should return -1. - foo.Sign(0); // This should return 0. -``` - -As you may have guessed, when there are more than one `ON_CALL()` -statements, the news order take precedence over the older ones. In -other words, the **last** one that matches the function arguments will -be used. This matching order allows you to set up the common behavior -in a mock object's constructor or the test fixture's set-up phase and -specialize the mock's behavior later. - -## Using Functions/Methods/Functors as Actions ## - -If the built-in actions don't suit you, you can easily use an existing -function, method, or functor as an action: - -``` -using ::testing::_; -using ::testing::Invoke; - -class MockFoo : public Foo { - public: - MOCK_METHOD2(Sum, int(int x, int y)); - MOCK_METHOD1(ComplexJob, bool(int x)); -}; - -int CalculateSum(int x, int y) { return x + y; } - -class Helper { - public: - bool ComplexJob(int x); -}; -... - - MockFoo foo; - Helper helper; - EXPECT_CALL(foo, Sum(_, _)) - .WillOnce(Invoke(CalculateSum)); - EXPECT_CALL(foo, ComplexJob(_)) - .WillOnce(Invoke(&helper, &Helper::ComplexJob)); - - foo.Sum(5, 6); // Invokes CalculateSum(5, 6). - foo.ComplexJob(10); // Invokes helper.ComplexJob(10); -``` - -The only requirement is that the type of the function, etc must be -_compatible_ with the signature of the mock function, meaning that the -latter's arguments can be implicitly converted to the corresponding -arguments of the former, and the former's return type can be -implicitly converted to that of the latter. So, you can invoke -something whose type is _not_ exactly the same as the mock function, -as long as it's safe to do so - nice, huh? - -## Invoking a Function/Method/Functor Without Arguments ## - -`Invoke()` is very useful for doing actions that are more complex. It -passes the mock function's arguments to the function or functor being -invoked such that the callee has the full context of the call to work -with. If the invoked function is not interested in some or all of the -arguments, it can simply ignore them. - -Yet, a common pattern is that a test author wants to invoke a function -without the arguments of the mock function. `Invoke()` allows her to -do that using a wrapper function that throws away the arguments before -invoking an underlining nullary function. Needless to say, this can be -tedious and obscures the intent of the test. - -`InvokeWithoutArgs()` solves this problem. It's like `Invoke()` except -that it doesn't pass the mock function's arguments to the -callee. Here's an example: - -``` -using ::testing::_; -using ::testing::InvokeWithoutArgs; - -class MockFoo : public Foo { - public: - MOCK_METHOD1(ComplexJob, bool(int n)); -}; - -bool Job1() { ... } -... - - MockFoo foo; - EXPECT_CALL(foo, ComplexJob(_)) - .WillOnce(InvokeWithoutArgs(Job1)); - - foo.ComplexJob(10); // Invokes Job1(). -``` - -## Invoking an Argument of the Mock Function ## - -Sometimes a mock function will receive a function pointer or a functor -(in other words, a "callable") as an argument, e.g. - -``` -class MockFoo : public Foo { - public: - MOCK_METHOD2(DoThis, bool(int n, bool (*fp)(int))); -}; -``` - -and you may want to invoke this callable argument: - -``` -using ::testing::_; -... - MockFoo foo; - EXPECT_CALL(foo, DoThis(_, _)) - .WillOnce(...); - // Will execute (*fp)(5), where fp is the - // second argument DoThis() receives. -``` - -Arghh, you need to refer to a mock function argument but C++ has no -lambda (yet), so you have to define your own action. :-( Or do you -really? - -Well, Google Mock has an action to solve _exactly_ this problem: - -``` - InvokeArgument<N>(arg_1, arg_2, ..., arg_m) -``` - -will invoke the `N`-th (0-based) argument the mock function receives, -with `arg_1`, `arg_2`, ..., and `arg_m`. No matter if the argument is -a function pointer or a functor, Google Mock handles them both. - -With that, you could write: - -``` -using ::testing::_; -using ::testing::InvokeArgument; -... - EXPECT_CALL(foo, DoThis(_, _)) - .WillOnce(InvokeArgument<1>(5)); - // Will execute (*fp)(5), where fp is the - // second argument DoThis() receives. -``` - -What if the callable takes an argument by reference? No problem - just -wrap it inside `ByRef()`: - -``` -... - MOCK_METHOD1(Bar, bool(bool (*fp)(int, const Helper&))); -... -using ::testing::_; -using ::testing::ByRef; -using ::testing::InvokeArgument; -... - - MockFoo foo; - Helper helper; - ... - EXPECT_CALL(foo, Bar(_)) - .WillOnce(InvokeArgument<0>(5, ByRef(helper))); - // ByRef(helper) guarantees that a reference to helper, not a copy of it, - // will be passed to the callable. -``` - -What if the callable takes an argument by reference and we do **not** -wrap the argument in `ByRef()`? Then `InvokeArgument()` will _make a -copy_ of the argument, and pass a _reference to the copy_, instead of -a reference to the original value, to the callable. This is especially -handy when the argument is a temporary value: - -``` -... - MOCK_METHOD1(DoThat, bool(bool (*f)(const double& x, const string& s))); -... -using ::testing::_; -using ::testing::InvokeArgument; -... - - MockFoo foo; - ... - EXPECT_CALL(foo, DoThat(_)) - .WillOnce(InvokeArgument<0>(5.0, string("Hi"))); - // Will execute (*f)(5.0, string("Hi")), where f is the function pointer - // DoThat() receives. Note that the values 5.0 and string("Hi") are - // temporary and dead once the EXPECT_CALL() statement finishes. Yet - // it's fine to perform this action later, since a copy of the values - // are kept inside the InvokeArgument action. -``` - -## Ignoring an Action's Result ## - -Sometimes you have an action that returns _something_, but you need an -action that returns `void` (perhaps you want to use it in a mock -function that returns `void`, or perhaps it needs to be used in -`DoAll()` and it's not the last in the list). `IgnoreResult()` lets -you do that. For example: - -``` -using ::testing::_; -using ::testing::Invoke; -using ::testing::Return; - -int Process(const MyData& data); -string DoSomething(); - -class MockFoo : public Foo { - public: - MOCK_METHOD1(Abc, void(const MyData& data)); - MOCK_METHOD0(Xyz, bool()); -}; -... - - MockFoo foo; - EXPECT_CALL(foo, Abc(_)) - // .WillOnce(Invoke(Process)); - // The above line won't compile as Process() returns int but Abc() needs - // to return void. - .WillOnce(IgnoreResult(Invoke(Process))); - - EXPECT_CALL(foo, Xyz()) - .WillOnce(DoAll(IgnoreResult(Invoke(DoSomething)), - // Ignores the string DoSomething() returns. - Return(true))); -``` - -Note that you **cannot** use `IgnoreResult()` on an action that already -returns `void`. Doing so will lead to ugly compiler errors. - -## Selecting an Action's Arguments ## - -Say you have a mock function `Foo()` that takes seven arguments, and -you have a custom action that you want to invoke when `Foo()` is -called. Trouble is, the custom action only wants three arguments: - -``` -using ::testing::_; -using ::testing::Invoke; -... - MOCK_METHOD7(Foo, bool(bool visible, const string& name, int x, int y, - const map<pair<int, int>, double>& weight, - double min_weight, double max_wight)); -... - -bool IsVisibleInQuadrant1(bool visible, int x, int y) { - return visible && x >= 0 && y >= 0; -} -... - - EXPECT_CALL(mock, Foo(_, _, _, _, _, _, _)) - .WillOnce(Invoke(IsVisibleInQuadrant1)); // Uh, won't compile. :-( -``` - -To please the compiler God, you can to define an "adaptor" that has -the same signature as `Foo()` and calls the custom action with the -right arguments: - -``` -using ::testing::_; -using ::testing::Invoke; - -bool MyIsVisibleInQuadrant1(bool visible, const string& name, int x, int y, - const map<pair<int, int>, double>& weight, - double min_weight, double max_wight) { - return IsVisibleInQuadrant1(visible, x, y); -} -... - - EXPECT_CALL(mock, Foo(_, _, _, _, _, _, _)) - .WillOnce(Invoke(MyIsVisibleInQuadrant1)); // Now it works. -``` - -But isn't this awkward? - -Google Mock provides a generic _action adaptor_, so you can spend your -time minding more important business than writing your own -adaptors. Here's the syntax: - -``` - WithArgs<N1, N2, ..., Nk>(action) -``` - -creates an action that passes the arguments of the mock function at -the given indices (0-based) to the inner `action` and performs -it. Using `WithArgs`, our original example can be written as: - -``` -using ::testing::_; -using ::testing::Invoke; -using ::testing::WithArgs; -... - EXPECT_CALL(mock, Foo(_, _, _, _, _, _, _)) - .WillOnce(WithArgs<0, 2, 3>(Invoke(IsVisibleInQuadrant1))); - // No need to define your own adaptor. -``` - -For better readability, Google Mock also gives you: - - * `WithoutArgs(action)` when the inner `action` takes _no_ argument, and - * `WithArg<N>(action)` (no `s` after `Arg`) when the inner `action` takes _one_ argument. - -As you may have realized, `InvokeWithoutArgs(...)` is just syntactic -sugar for `WithoutArgs(Inovke(...))`. - -Here are more tips: - - * The inner action used in `WithArgs` and friends does not have to be `Invoke()` -- it can be anything. - * You can repeat an argument in the argument list if necessary, e.g. `WithArgs<2, 3, 3, 5>(...)`. - * You can change the order of the arguments, e.g. `WithArgs<3, 2, 1>(...)`. - * The types of the selected arguments do _not_ have to match the signature of the inner action exactly. It works as long as they can be implicitly converted to the corresponding arguments of the inner action. For example, if the 4-th argument of the mock function is an `int` and `my_action` takes a `double`, `WithArg<4>(my_action)` will work. - -## Ignoring Arguments in Action Functions ## - -The selecting-an-action's-arguments recipe showed us one way to make a -mock function and an action with incompatible argument lists fit -together. The downside is that wrapping the action in -`WithArgs<...>()` can get tedious for people writing the tests. - -If you are defining a function, method, or functor to be used with -`Invoke*()`, and you are not interested in some of its arguments, an -alternative to `WithArgs` is to declare the uninteresting arguments as -`Unused`. This makes the definition less cluttered and less fragile in -case the types of the uninteresting arguments change. It could also -increase the chance the action function can be reused. For example, -given - -``` - MOCK_METHOD3(Foo, double(const string& label, double x, double y)); - MOCK_METHOD3(Bar, double(int index, double x, double y)); -``` - -instead of - -``` -using ::testing::_; -using ::testing::Invoke; - -double DistanceToOriginWithLabel(const string& label, double x, double y) { - return sqrt(x*x + y*y); -} - -double DistanceToOriginWithIndex(int index, double x, double y) { - return sqrt(x*x + y*y); -} -... - - EXEPCT_CALL(mock, Foo("abc", _, _)) - .WillOnce(Invoke(DistanceToOriginWithLabel)); - EXEPCT_CALL(mock, Bar(5, _, _)) - .WillOnce(Invoke(DistanceToOriginWithIndex)); -``` - -you could write - -``` -using ::testing::_; -using ::testing::Invoke; -using ::testing::Unused; - -double DistanceToOrigin(Unused, double x, double y) { - return sqrt(x*x + y*y); -} -... - - EXEPCT_CALL(mock, Foo("abc", _, _)) - .WillOnce(Invoke(DistanceToOrigin)); - EXEPCT_CALL(mock, Bar(5, _, _)) - .WillOnce(Invoke(DistanceToOrigin)); -``` - -## Sharing Actions ## - -Just like matchers, a Google Mock action object consists of a pointer -to a ref-counted implementation object. Therefore copying actions is -also allowed and very efficient. When the last action that references -the implementation object dies, the implementation object will be -deleted. - -If you have some complex action that you want to use again and again, -you may not have to build it from scratch everytime. If the action -doesn't have an internal state (i.e. if it always does the same thing -no matter how many times it has been called), you can assign it to an -action variable and use that variable repeatedly. For example: - -``` - Action<bool(int*)> set_flag = DoAll(SetArgPointee<0>(5), - Return(true)); - ... use set_flag in .WillOnce() and .WillRepeatedly() ... -``` - -However, if the action has its own state, you may be surprised if you -share the action object. Suppose you have an action factory -`IncrementCounter(init)` which creates an action that increments and -returns a counter whose initial value is `init`, using two actions -created from the same expression and using a shared action will -exihibit different behaviors. Example: - -``` - EXPECT_CALL(foo, DoThis()) - .WillRepeatedly(IncrementCounter(0)); - EXPECT_CALL(foo, DoThat()) - .WillRepeatedly(IncrementCounter(0)); - foo.DoThis(); // Returns 1. - foo.DoThis(); // Returns 2. - foo.DoThat(); // Returns 1 - Blah() uses a different - // counter than Bar()'s. -``` - -versus - -``` - Action<int()> increment = IncrementCounter(0); - - EXPECT_CALL(foo, DoThis()) - .WillRepeatedly(increment); - EXPECT_CALL(foo, DoThat()) - .WillRepeatedly(increment); - foo.DoThis(); // Returns 1. - foo.DoThis(); // Returns 2. - foo.DoThat(); // Returns 3 - the counter is shared. -``` - -# Misc Recipes on Using Google Mock # - -## Making the Compilation Faster ## - -Believe it or not, the _vast majority_ of the time spent on compiling -a mock class is in generating its constructor and destructor, as they -perform non-trivial tasks (e.g. verification of the -expectations). What's more, mock methods with different signatures -have different types and thus their constructors/destructors need to -be generated by the compiler separately. As a result, if you mock many -different types of methods, compiling your mock class can get really -slow. - -If you are experiencing slow compilation, you can move the definition -of your mock class' constructor and destructor out of the class body -and into a `.cpp` file. This way, even if you `#include` your mock -class in N files, the compiler only needs to generate its constructor -and destructor once, resulting in a much faster compilation. - -Let's illustrate the idea using an example. Here's the definition of a -mock class before applying this recipe: - -``` -// File mock_foo.h. -... -class MockFoo : public Foo { - public: - // Since we don't declare the constructor or the destructor, - // the compiler will generate them in every translation unit - // where this mock class is used. - - MOCK_METHOD0(DoThis, int()); - MOCK_METHOD1(DoThat, bool(const char* str)); - ... more mock methods ... -}; -``` - -After the change, it would look like: - -``` -// File mock_foo.h. -... -class MockFoo : public Foo { - public: - // The constructor and destructor are declared, but not defined, here. - MockFoo(); - virtual ~MockFoo(); - - MOCK_METHOD0(DoThis, int()); - MOCK_METHOD1(DoThat, bool(const char* str)); - ... more mock methods ... -}; -``` -and -``` -// File mock_foo.cpp. -#include "path/to/mock_foo.h" - -// The definitions may appear trivial, but the functions actually do a -// lot of things through the constructors/destructors of the member -// variables used to implement the mock methods. -MockFoo::MockFoo() {} -MockFoo::~MockFoo() {} -``` - -## Forcing a Verification ## - -When it's being destoyed, your friendly mock object will automatically -verify that all expectations on it have been satisfied, and will -generate [Google Test](http://code.google.com/p/googletest/) failures -if not. This is convenient as it leaves you with one less thing to -worry about. That is, unless you are not sure if your mock object will -be destoyed. - -How could it be that your mock object won't eventually be destroyed? -Well, it might be created on the heap and owned by the code you are -testing. Suppose there's a bug in that code and it doesn't delete the -mock object properly - you could end up with a passing test when -there's actually a bug. - -Using a heap checker is a good idea and can alleviate the concern, but -its implementation may not be 100% reliable. So, sometimes you do want -to _force_ Google Mock to verify a mock object before it is -(hopefully) destructed. You can do this with -`Mock::VerifyAndClearExpectations(&mock_object)`: - -``` -TEST(MyServerTest, ProcessesRequest) { - using ::testing::Mock; - - MockFoo* const foo = new MockFoo; - EXPECT_CALL(*foo, ...)...; - // ... other expectations ... - - // server now owns foo. - MyServer server(foo); - server.ProcessRequest(...); - - // In case that server's destructor will forget to delete foo, - // this will verify the expectations anyway. - Mock::VerifyAndClearExpectations(foo); -} // server is destroyed when it goes out of scope here. -``` - -**Tip:** The `Mock::VerifyAndClearExpectations()` function returns a -`bool` to indicate whether the verification was successful (`true` for -yes), so you can wrap that function call inside a `ASSERT_TRUE()` if -there is no point going further when the verification has failed. - -## Using Check Points ## - -Sometimes you may want to "reset" a mock object at various check -points in your test: at each check point, you verify that all existing -expectations on the mock object have been satisfied, and then you set -some new expectations on it as if it's newly created. This allows you -to work with a mock object in "phases" whose sizes are each -manageable. - -One such scenario is that in your test's `SetUp()` function, you may -want to put the object you are testing into a certain state, with the -help from a mock object. Once in the desired state, you want to clear -all expectations on the mock, such that in the `TEST_F` body you can -set fresh expectations on it. - -As you may have figured out, the `Mock::VerifyAndClearExpectations()` -function we saw in the previous recipe can help you here. Or, if you -are using `ON_CALL()` to set default actions on the mock object and -want to clear the default actions as well, use -`Mock::VerifyAndClear(&mock_object)` instead. This function does what -`Mock::VerifyAndClearExpectations(&mock_object)` does and returns the -same `bool`, **plus** it clears the `ON_CALL()` statements on -`mock_object` too. - -Another trick you can use to achieve the same effect is to put the -expectations in sequences and insert calls to a dummy "check-point" -function at specific places. Then you can verify that the mock -function calls do happen at the right time. For example, if you are -exercising code: - -``` -Foo(1); -Foo(2); -Foo(3); -``` - -and want to verify that `Foo(1)` and `Foo(3)` both invoke -`mock.Bar("a")`, but `Foo(2)` doesn't invoke anything. You can write: - -``` -using ::testing::MockFunction; - -TEST(FooTest, InvokesBarCorrectly) { - MyMock mock; - // Class MockFunction<F> has exactly one mock method. It is named - // Call() and has type F. - MockFunction<void(string check_point_name)> check; - { - InSequence s; - - EXPECT_CALL(mock, Bar("a")); - EXPECT_CALL(check, Call("1")); - EXPECT_CALL(check, Call("2")); - EXPECT_CALL(mock, Bar("a")); - } - Foo(1); - check.Call("1"); - Foo(2); - check.Call("2"); - Foo(3); -} -``` - -The expectation spec says that the first `Bar("a")` must happen before -check point "1", the second `Bar("a")` must happen after check point "2", -and nothing should happen between the two check points. The explicit -check points make it easy to tell which `Bar("a")` is called by which -call to `Foo()`. - -## Mocking Destructors ## - -Sometimes you want to make sure a mock object is destructed at the -right time, e.g. after `bar->A()` is called but before `bar->B()` is -called. We already know that you can specify constraints on the order -of mock function calls, so all we need to do is to mock the destructor -of the mock function. - -This sounds simple, except for one problem: a destructor is a special -function with special syntax and special semantics, and the -`MOCK_METHOD0` macro doesn't work for it: - -``` - MOCK_METHOD0(~MockFoo, void()); // Won't compile! -``` - -The good news is that you can use a simple pattern to achieve the same -effect. First, add a mock function `Die()` to your mock class and call -it in the destructor, like this: - -``` -class MockFoo : public Foo { - ... - // Add the following two lines to the mock class. - MOCK_METHOD0(Die, void()); - virtual ~MockFoo() { Die(); } -}; -``` - -(If the name `Die()` clashes with an existing symbol, choose another -name.) Now, we have translated the problem of testing when a `MockFoo` -object dies to testing when its `Die()` method is called: - -``` - MockFoo* foo = new MockFoo; - MockBar* bar = new MockBar; - ... - { - InSequence s; - - // Expects *foo to die after bar->A() and before bar->B(). - EXPECT_CALL(*bar, A()); - EXPECT_CALL(*foo, Die()); - EXPECT_CALL(*bar, B()); - } -``` - -And that's that. - -## Using Google Mock and Threads ## - -**IMPORTANT NOTE:** What we describe in this recipe is **ONLY** true on -platforms where Google Mock is thread-safe. Currently these are only -platforms that support the pthreads library (this includes Linux and Mac). -To make it thread-safe on other platforms we only need to implement -some synchronization operations in `"gtest/internal/gtest-port.h"`. - -In a **unit** test, it's best if you could isolate and test a piece of -code in a single-threaded context. That avoids race conditions and -dead locks, and makes debugging your test much easier. - -Yet many programs are multi-threaded, and sometimes to test something -we need to pound on it from more than one thread. Google Mock works -for this purpose too. - -Remember the steps for using a mock: - - 1. Create a mock object `foo`. - 1. Set its default actions and expectations using `ON_CALL()` and `EXPECT_CALL()`. - 1. The code under test calls methods of `foo`. - 1. Optionally, verify and reset the mock. - 1. Destroy the mock yourself, or let the code under test destroy it. The destructor will automatically verify it. - -If you follow the following simple rules, your mocks and threads can -live happily togeter: - - * Execute your _test code_ (as opposed to the code being tested) in _one_ thread. This makes your test easy to follow. - * Obviously, you can do step #1 without locking. - * When doing step #2 and #5, make sure no other thread is accessing `foo`. Obvious too, huh? - * #3 and #4 can be done either in one thread or in multiple threads - anyway you want. Google Mock takes care of the locking, so you don't have to do any - unless required by your test logic. - -If you violate the rules (for example, if you set expectations on a -mock while another thread is calling its methods), you get undefined -behavior. That's not fun, so don't do it. - -Google Mock guarantees that the action for a mock function is done in -the same thread that called the mock function. For example, in - -``` - EXPECT_CALL(mock, Foo(1)) - .WillOnce(action1); - EXPECT_CALL(mock, Foo(2)) - .WillOnce(action2); -``` - -if `Foo(1)` is called in thread 1 and `Foo(2)` is called in thread 2, -Google Mock will execute `action1` in thread 1 and `action2` in thread -2. - -Google Mock does _not_ impose a sequence on actions performed in -different threads (doing so may create deadlocks as the actions may -need to cooperate). This means that the execution of `action1` and -`action2` in the above example _may_ interleave. If this is a problem, -you should add proper synchronization logic to `action1` and `action2` -to make the test thread-safe. - - -Also, remember that `DefaultValue<T>` is a global resource that -potentially affects _all_ living mock objects in your -program. Naturally, you won't want to mess with it from multiple -threads or when there still are mocks in action. - -## Controlling How Much Information Google Mock Prints ## - -When Google Mock sees something that has the potential of being an -error (e.g. a mock function with no expectation is called, a.k.a. an -uninteresting call, which is allowed but perhaps you forgot to -explicitly ban the call), it prints some warning messages, including -the arguments of the function and the return value. Hopefully this -will remind you to take a look and see if there is indeed a problem. - -Sometimes you are confident that your tests are correct and may not -appreciate such friendly messages. Some other times, you are debugging -your tests or learning about the behavior of the code you are testing, -and wish you could observe every mock call that happens (including -argument values and the return value). Clearly, one size doesn't fit -all. - -You can control how much Google Mock tells you using the -`--gmock_verbose=LEVEL` command-line flag, where `LEVEL` is a string -with three possible values: - - * `info`: Google Mock will print all informational messages, warnings, and errors (most verbose). At this setting, Google Mock will also log any calls to the `ON_CALL/EXPECT_CALL` macros. - * `warning`: Google Mock will print both warnings and errors (less verbose). This is the default. - * `error`: Google Mock will print errors only (least verbose). - -Alternatively, you can adjust the value of that flag from within your -tests like so: - -``` - ::testing::FLAGS_gmock_verbose = "error"; -``` - -Now, judiciously use the right flag to enable Google Mock serve you better! - -## Running Tests in Emacs ## - -If you build and run your tests in Emacs, the source file locations of -Google Mock and [Google Test](http://code.google.com/p/googletest/) -errors will be highlighted. Just press `<Enter>` on one of them and -you'll be taken to the offending line. Or, you can just type `C-x `` -to jump to the next error. - -To make it even easier, you can add the following lines to your -`~/.emacs` file: - -``` -(global-set-key "\M-m" 'compile) ; m is for make -(global-set-key [M-down] 'next-error) -(global-set-key [M-up] '(lambda () (interactive) (next-error -1))) -``` - -Then you can type `M-m` to start a build, or `M-up`/`M-down` to move -back and forth between errors. - -## Fusing Google Mock Source Files ## - -Google Mock's implementation consists of dozens of files (excluding -its own tests). Sometimes you may want them to be packaged up in -fewer files instead, such that you can easily copy them to a new -machine and start hacking there. For this we provide an experimental -Python script `fuse_gmock_files.py` in the `scripts/` directory -(starting with release 1.2.0). Assuming you have Python 2.4 or above -installed on your machine, just go to that directory and run -``` -python fuse_gmock_files.py OUTPUT_DIR -``` - -and you should see an `OUTPUT_DIR` directory being created with files -`gtest/gtest.h`, `gmock/gmock.h`, and `gmock-gtest-all.cc` in it. -These three files contain everything you need to use Google Mock (and -Google Test). Just copy them to anywhere you want and you are ready -to write tests and use mocks. You can use the -[scrpts/test/Makefile](http://code.google.com/p/googlemock/source/browse/trunk/scripts/test/Makefile) file as an example on how to compile your tests -against them. - -# Extending Google Mock # - -## Writing New Matchers Quickly ## - -The `MATCHER*` family of macros can be used to define custom matchers -easily. The syntax: - -``` -MATCHER(name, description_string_expression) { statements; } -``` - -will define a matcher with the given name that executes the -statements, which must return a `bool` to indicate if the match -succeeds. Inside the statements, you can refer to the value being -matched by `arg`, and refer to its type by `arg_type`. - -The description string is a `string`-typed expression that documents -what the matcher does, and is used to generate the failure message -when the match fails. It can (and should) reference the special -`bool` variable `negation`, and should evaluate to the description of -the matcher when `negation` is `false`, or that of the matcher's -negation when `negation` is `true`. - -For convenience, we allow the description string to be empty (`""`), -in which case Google Mock will use the sequence of words in the -matcher name as the description. - -For example: -``` -MATCHER(IsDivisibleBy7, "") { return (arg % 7) == 0; } -``` -allows you to write -``` - // Expects mock_foo.Bar(n) to be called where n is divisible by 7. - EXPECT_CALL(mock_foo, Bar(IsDivisibleBy7())); -``` -or, -``` -using ::testing::Not; -... - EXPECT_THAT(some_expression, IsDivisibleBy7()); - EXPECT_THAT(some_other_expression, Not(IsDivisibleBy7())); -``` -If the above assertions fail, they will print something like: -``` - Value of: some_expression - Expected: is divisible by 7 - Actual: 27 -... - Value of: some_other_expression - Expected: not (is divisible by 7) - Actual: 21 -``` -where the descriptions `"is divisible by 7"` and `"not (is divisible -by 7)"` are automatically calculated from the matcher name -`IsDivisibleBy7`. - -As you may have noticed, the auto-generated descriptions (especially -those for the negation) may not be so great. You can always override -them with a string expression of your own: -``` -MATCHER(IsDivisibleBy7, std::string(negation ? "isn't" : "is") + - " divisible by 7") { - return (arg % 7) == 0; -} -``` - -Optionally, you can stream additional information to a hidden argument -named `result_listener` to explain the match result. For example, a -better definition of `IsDivisibleBy7` is: -``` -MATCHER(IsDivisibleBy7, "") { - if ((arg % 7) == 0) - return true; - - *result_listener << "the remainder is " << (arg % 7); - return false; -} -``` - -With this definition, the above assertion will give a better message: -``` - Value of: some_expression - Expected: is divisible by 7 - Actual: 27 (the remainder is 6) -``` - -You should let `MatchAndExplain()` print _any additional information_ -that can help a user understand the match result. Note that it should -explain why the match succeeds in case of a success (unless it's -obvious) - this is useful when the matcher is used inside -`Not()`. There is no need to print the argument value itself, as -Google Mock already prints it for you. - -**Notes:** - - 1. The type of the value being matched (`arg_type`) is determined by the context in which you use the matcher and is supplied to you by the compiler, so you don't need to worry about declaring it (nor can you). This allows the matcher to be polymorphic. For example, `IsDivisibleBy7()` can be used to match any type where the value of `(arg % 7) == 0` can be implicitly converted to a `bool`. In the `Bar(IsDivisibleBy7())` example above, if method `Bar()` takes an `int`, `arg_type` will be `int`; if it takes an `unsigned long`, `arg_type` will be `unsigned long`; and so on. - 1. Google Mock doesn't guarantee when or how many times a matcher will be invoked. Therefore the matcher logic must be _purely functional_ (i.e. it cannot have any side effect, and the result must not depend on anything other than the value being matched and the matcher parameters). This requirement must be satisfied no matter how you define the matcher (e.g. using one of the methods described in the following recipes). In particular, a matcher can never call a mock function, as that will affect the state of the mock object and Google Mock. - -## Writing New Parameterized Matchers Quickly ## - -Sometimes you'll want to define a matcher that has parameters. For that you -can use the macro: -``` -MATCHER_P(name, param_name, description_string) { statements; } -``` -where the description string can be either `""` or a string expression -that references `negation` and `param_name`. - -For example: -``` -MATCHER_P(HasAbsoluteValue, value, "") { return abs(arg) == value; } -``` -will allow you to write: -``` - EXPECT_THAT(Blah("a"), HasAbsoluteValue(n)); -``` -which may lead to this message (assuming `n` is 10): -``` - Value of: Blah("a") - Expected: has absolute value 10 - Actual: -9 -``` - -Note that both the matcher description and its parameter are -printed, making the message human-friendly. - -In the matcher definition body, you can write `foo_type` to -reference the type of a parameter named `foo`. For example, in the -body of `MATCHER_P(HasAbsoluteValue, value)` above, you can write -`value_type` to refer to the type of `value`. - -Google Mock also provides `MATCHER_P2`, `MATCHER_P3`, ..., up to -`MATCHER_P10` to support multi-parameter matchers: -``` -MATCHER_Pk(name, param_1, ..., param_k, description_string) { statements; } -``` - -Please note that the custom description string is for a particular -**instance** of the matcher, where the parameters have been bound to -actual values. Therefore usually you'll want the parameter values to -be part of the description. Google Mock lets you do that by -referencing the matcher parameters in the description string -expression. - -For example, -``` - using ::testing::PrintToString; - MATCHER_P2(InClosedRange, low, hi, - std::string(negation ? "isn't" : "is") + " in range [" + - PrintToString(low) + ", " + PrintToString(hi) + "]") { - return low <= arg && arg <= hi; - } - ... - EXPECT_THAT(3, InClosedRange(4, 6)); -``` -would generate a failure that contains the message: -``` - Expected: is in range [4, 6] -``` - -If you specify `""` as the description, the failure message will -contain the sequence of words in the matcher name followed by the -parameter values printed as a tuple. For example, -``` - MATCHER_P2(InClosedRange, low, hi, "") { ... } - ... - EXPECT_THAT(3, InClosedRange(4, 6)); -``` -would generate a failure that contains the text: -``` - Expected: in closed range (4, 6) -``` - -For the purpose of typing, you can view -``` -MATCHER_Pk(Foo, p1, ..., pk, description_string) { ... } -``` -as shorthand for -``` -template <typename p1_type, ..., typename pk_type> -FooMatcherPk<p1_type, ..., pk_type> -Foo(p1_type p1, ..., pk_type pk) { ... } -``` - -When you write `Foo(v1, ..., vk)`, the compiler infers the types of -the parameters `v1`, ..., and `vk` for you. If you are not happy with -the result of the type inference, you can specify the types by -explicitly instantiating the template, as in `Foo<long, bool>(5, false)`. -As said earlier, you don't get to (or need to) specify -`arg_type` as that's determined by the context in which the matcher -is used. - -You can assign the result of expression `Foo(p1, ..., pk)` to a -variable of type `FooMatcherPk<p1_type, ..., pk_type>`. This can be -useful when composing matchers. Matchers that don't have a parameter -or have only one parameter have special types: you can assign `Foo()` -to a `FooMatcher`-typed variable, and assign `Foo(p)` to a -`FooMatcherP<p_type>`-typed variable. - -While you can instantiate a matcher template with reference types, -passing the parameters by pointer usually makes your code more -readable. If, however, you still want to pass a parameter by -reference, be aware that in the failure message generated by the -matcher you will see the value of the referenced object but not its -address. - -You can overload matchers with different numbers of parameters: -``` -MATCHER_P(Blah, a, description_string_1) { ... } -MATCHER_P2(Blah, a, b, description_string_2) { ... } -``` - -While it's tempting to always use the `MATCHER*` macros when defining -a new matcher, you should also consider implementing -`MatcherInterface` or using `MakePolymorphicMatcher()` instead (see -the recipes that follow), especially if you need to use the matcher a -lot. While these approaches require more work, they give you more -control on the types of the value being matched and the matcher -parameters, which in general leads to better compiler error messages -that pay off in the long run. They also allow overloading matchers -based on parameter types (as opposed to just based on the number of -parameters). - -## Writing New Monomorphic Matchers ## - -A matcher of argument type `T` implements -`::testing::MatcherInterface<T>` and does two things: it tests whether a -value of type `T` matches the matcher, and can describe what kind of -values it matches. The latter ability is used for generating readable -error messages when expectations are violated. - -The interface looks like this: - -``` -class MatchResultListener { - public: - ... - // Streams x to the underlying ostream; does nothing if the ostream - // is NULL. - template <typename T> - MatchResultListener& operator<<(const T& x); - - // Returns the underlying ostream. - ::std::ostream* stream(); -}; - -template <typename T> -class MatcherInterface { - public: - virtual ~MatcherInterface(); - - // Returns true iff the matcher matches x; also explains the match - // result to 'listener'. - virtual bool MatchAndExplain(T x, MatchResultListener* listener) const = 0; - - // Describes this matcher to an ostream. - virtual void DescribeTo(::std::ostream* os) const = 0; - - // Describes the negation of this matcher to an ostream. - virtual void DescribeNegationTo(::std::ostream* os) const; -}; -``` - -If you need a custom matcher but `Truly()` is not a good option (for -example, you may not be happy with the way `Truly(predicate)` -describes itself, or you may want your matcher to be polymorphic as -`Eq(value)` is), you can define a matcher to do whatever you want in -two steps: first implement the matcher interface, and then define a -factory function to create a matcher instance. The second step is not -strictly needed but it makes the syntax of using the matcher nicer. - -For example, you can define a matcher to test whether an `int` is -divisible by 7 and then use it like this: -``` -using ::testing::MakeMatcher; -using ::testing::Matcher; -using ::testing::MatcherInterface; -using ::testing::MatchResultListener; - -class DivisibleBy7Matcher : public MatcherInterface<int> { - public: - virtual bool MatchAndExplain(int n, MatchResultListener* listener) const { - return (n % 7) == 0; - } - - virtual void DescribeTo(::std::ostream* os) const { - *os << "is divisible by 7"; - } - - virtual void DescribeNegationTo(::std::ostream* os) const { - *os << "is not divisible by 7"; - } -}; - -inline Matcher<int> DivisibleBy7() { - return MakeMatcher(new DivisibleBy7Matcher); -} -... - - EXPECT_CALL(foo, Bar(DivisibleBy7())); -``` - -You may improve the matcher message by streaming additional -information to the `listener` argument in `MatchAndExplain()`: - -``` -class DivisibleBy7Matcher : public MatcherInterface<int> { - public: - virtual bool MatchAndExplain(int n, - MatchResultListener* listener) const { - const int remainder = n % 7; - if (remainder != 0) { - *listener << "the remainder is " << remainder; - } - return remainder == 0; - } - ... -}; -``` - -Then, `EXPECT_THAT(x, DivisibleBy7());` may general a message like this: -``` -Value of: x -Expected: is divisible by 7 - Actual: 23 (the remainder is 2) -``` - -## Writing New Polymorphic Matchers ## - -You've learned how to write your own matchers in the previous -recipe. Just one problem: a matcher created using `MakeMatcher()` only -works for one particular type of arguments. If you want a -_polymorphic_ matcher that works with arguments of several types (for -instance, `Eq(x)` can be used to match a `value` as long as `value` == -`x` compiles -- `value` and `x` don't have to share the same type), -you can learn the trick from `"gmock/gmock-matchers.h"` but it's a bit -involved. - -Fortunately, most of the time you can define a polymorphic matcher -easily with the help of `MakePolymorphicMatcher()`. Here's how you can -define `NotNull()` as an example: - -``` -using ::testing::MakePolymorphicMatcher; -using ::testing::MatchResultListener; -using ::testing::NotNull; -using ::testing::PolymorphicMatcher; - -class NotNullMatcher { - public: - // To implement a polymorphic matcher, first define a COPYABLE class - // that has three members MatchAndExplain(), DescribeTo(), and - // DescribeNegationTo(), like the following. - - // In this example, we want to use NotNull() with any pointer, so - // MatchAndExplain() accepts a pointer of any type as its first argument. - // In general, you can define MatchAndExplain() as an ordinary method or - // a method template, or even overload it. - template <typename T> - bool MatchAndExplain(T* p, - MatchResultListener* /* listener */) const { - return p != NULL; - } - - // Describes the property of a value matching this matcher. - void DescribeTo(::std::ostream* os) const { *os << "is not NULL"; } - - // Describes the property of a value NOT matching this matcher. - void DescribeNegationTo(::std::ostream* os) const { *os << "is NULL"; } -}; - -// To construct a polymorphic matcher, pass an instance of the class -// to MakePolymorphicMatcher(). Note the return type. -inline PolymorphicMatcher<NotNullMatcher> NotNull() { - return MakePolymorphicMatcher(NotNullMatcher()); -} -... - - EXPECT_CALL(foo, Bar(NotNull())); // The argument must be a non-NULL pointer. -``` - -**Note:** Your polymorphic matcher class does **not** need to inherit from -`MatcherInterface` or any other class, and its methods do **not** need -to be virtual. - -Like in a monomorphic matcher, you may explain the match result by -streaming additional information to the `listener` argument in -`MatchAndExplain()`. - -## Writing New Cardinalities ## - -A cardinality is used in `Times()` to tell Google Mock how many times -you expect a call to occur. It doesn't have to be exact. For example, -you can say `AtLeast(5)` or `Between(2, 4)`. - -If the built-in set of cardinalities doesn't suit you, you are free to -define your own by implementing the following interface (in namespace -`testing`): - -``` -class CardinalityInterface { - public: - virtual ~CardinalityInterface(); - - // Returns true iff call_count calls will satisfy this cardinality. - virtual bool IsSatisfiedByCallCount(int call_count) const = 0; - - // Returns true iff call_count calls will saturate this cardinality. - virtual bool IsSaturatedByCallCount(int call_count) const = 0; - - // Describes self to an ostream. - virtual void DescribeTo(::std::ostream* os) const = 0; -}; -``` - -For example, to specify that a call must occur even number of times, -you can write - -``` -using ::testing::Cardinality; -using ::testing::CardinalityInterface; -using ::testing::MakeCardinality; - -class EvenNumberCardinality : public CardinalityInterface { - public: - virtual bool IsSatisfiedByCallCount(int call_count) const { - return (call_count % 2) == 0; - } - - virtual bool IsSaturatedByCallCount(int call_count) const { - return false; - } - - virtual void DescribeTo(::std::ostream* os) const { - *os << "called even number of times"; - } -}; - -Cardinality EvenNumber() { - return MakeCardinality(new EvenNumberCardinality); -} -... - - EXPECT_CALL(foo, Bar(3)) - .Times(EvenNumber()); -``` - -## Writing New Actions Quickly ## - -If the built-in actions don't work for you, and you find it -inconvenient to use `Invoke()`, you can use a macro from the `ACTION*` -family to quickly define a new action that can be used in your code as -if it's a built-in action. - -By writing -``` -ACTION(name) { statements; } -``` -in a namespace scope (i.e. not inside a class or function), you will -define an action with the given name that executes the statements. -The value returned by `statements` will be used as the return value of -the action. Inside the statements, you can refer to the K-th -(0-based) argument of the mock function as `argK`. For example: -``` -ACTION(IncrementArg1) { return ++(*arg1); } -``` -allows you to write -``` -... WillOnce(IncrementArg1()); -``` - -Note that you don't need to specify the types of the mock function -arguments. Rest assured that your code is type-safe though: -you'll get a compiler error if `*arg1` doesn't support the `++` -operator, or if the type of `++(*arg1)` isn't compatible with the mock -function's return type. - -Another example: -``` -ACTION(Foo) { - (*arg2)(5); - Blah(); - *arg1 = 0; - return arg0; -} -``` -defines an action `Foo()` that invokes argument #2 (a function pointer) -with 5, calls function `Blah()`, sets the value pointed to by argument -#1 to 0, and returns argument #0. - -For more convenience and flexibility, you can also use the following -pre-defined symbols in the body of `ACTION`: - -| `argK_type` | The type of the K-th (0-based) argument of the mock function | -|:------------|:-------------------------------------------------------------| -| `args` | All arguments of the mock function as a tuple | -| `args_type` | The type of all arguments of the mock function as a tuple | -| `return_type` | The return type of the mock function | -| `function_type` | The type of the mock function | - -For example, when using an `ACTION` as a stub action for mock function: -``` -int DoSomething(bool flag, int* ptr); -``` -we have: -| **Pre-defined Symbol** | **Is Bound To** | -|:-----------------------|:----------------| -| `arg0` | the value of `flag` | -| `arg0_type` | the type `bool` | -| `arg1` | the value of `ptr` | -| `arg1_type` | the type `int*` | -| `args` | the tuple `(flag, ptr)` | -| `args_type` | the type `std::tr1::tuple<bool, int*>` | -| `return_type` | the type `int` | -| `function_type` | the type `int(bool, int*)` | - -## Writing New Parameterized Actions Quickly ## - -Sometimes you'll want to parameterize an action you define. For that -we have another macro -``` -ACTION_P(name, param) { statements; } -``` - -For example, -``` -ACTION_P(Add, n) { return arg0 + n; } -``` -will allow you to write -``` -// Returns argument #0 + 5. -... WillOnce(Add(5)); -``` - -For convenience, we use the term _arguments_ for the values used to -invoke the mock function, and the term _parameters_ for the values -used to instantiate an action. - -Note that you don't need to provide the type of the parameter either. -Suppose the parameter is named `param`, you can also use the -Google-Mock-defined symbol `param_type` to refer to the type of the -parameter as inferred by the compiler. For example, in the body of -`ACTION_P(Add, n)` above, you can write `n_type` for the type of `n`. - -Google Mock also provides `ACTION_P2`, `ACTION_P3`, and etc to support -multi-parameter actions. For example, -``` -ACTION_P2(ReturnDistanceTo, x, y) { - double dx = arg0 - x; - double dy = arg1 - y; - return sqrt(dx*dx + dy*dy); -} -``` -lets you write -``` -... WillOnce(ReturnDistanceTo(5.0, 26.5)); -``` - -You can view `ACTION` as a degenerated parameterized action where the -number of parameters is 0. - -You can also easily define actions overloaded on the number of parameters: -``` -ACTION_P(Plus, a) { ... } -ACTION_P2(Plus, a, b) { ... } -``` - -## Restricting the Type of an Argument or Parameter in an ACTION ## - -For maximum brevity and reusability, the `ACTION*` macros don't ask -you to provide the types of the mock function arguments and the action -parameters. Instead, we let the compiler infer the types for us. - -Sometimes, however, we may want to be more explicit about the types. -There are several tricks to do that. For example: -``` -ACTION(Foo) { - // Makes sure arg0 can be converted to int. - int n = arg0; - ... use n instead of arg0 here ... -} - -ACTION_P(Bar, param) { - // Makes sure the type of arg1 is const char*. - ::testing::StaticAssertTypeEq<const char*, arg1_type>(); - - // Makes sure param can be converted to bool. - bool flag = param; -} -``` -where `StaticAssertTypeEq` is a compile-time assertion in Google Test -that verifies two types are the same. - -## Writing New Action Templates Quickly ## - -Sometimes you want to give an action explicit template parameters that -cannot be inferred from its value parameters. `ACTION_TEMPLATE()` -supports that and can be viewed as an extension to `ACTION()` and -`ACTION_P*()`. - -The syntax: -``` -ACTION_TEMPLATE(ActionName, - HAS_m_TEMPLATE_PARAMS(kind1, name1, ..., kind_m, name_m), - AND_n_VALUE_PARAMS(p1, ..., p_n)) { statements; } -``` - -defines an action template that takes _m_ explicit template parameters -and _n_ value parameters, where _m_ is between 1 and 10, and _n_ is -between 0 and 10. `name_i` is the name of the i-th template -parameter, and `kind_i` specifies whether it's a `typename`, an -integral constant, or a template. `p_i` is the name of the i-th value -parameter. - -Example: -``` -// DuplicateArg<k, T>(output) converts the k-th argument of the mock -// function to type T and copies it to *output. -ACTION_TEMPLATE(DuplicateArg, - // Note the comma between int and k: - HAS_2_TEMPLATE_PARAMS(int, k, typename, T), - AND_1_VALUE_PARAMS(output)) { - *output = T(std::tr1::get<k>(args)); -} -``` - -To create an instance of an action template, write: -``` - ActionName<t1, ..., t_m>(v1, ..., v_n) -``` -where the `t`s are the template arguments and the -`v`s are the value arguments. The value argument -types are inferred by the compiler. For example: -``` -using ::testing::_; -... - int n; - EXPECT_CALL(mock, Foo(_, _)) - .WillOnce(DuplicateArg<1, unsigned char>(&n)); -``` - -If you want to explicitly specify the value argument types, you can -provide additional template arguments: -``` - ActionName<t1, ..., t_m, u1, ..., u_k>(v1, ..., v_n) -``` -where `u_i` is the desired type of `v_i`. - -`ACTION_TEMPLATE` and `ACTION`/`ACTION_P*` can be overloaded on the -number of value parameters, but not on the number of template -parameters. Without the restriction, the meaning of the following is -unclear: - -``` - OverloadedAction<int, bool>(x); -``` - -Are we using a single-template-parameter action where `bool` refers to -the type of `x`, or a two-template-parameter action where the compiler -is asked to infer the type of `x`? - -## Using the ACTION Object's Type ## - -If you are writing a function that returns an `ACTION` object, you'll -need to know its type. The type depends on the macro used to define -the action and the parameter types. The rule is relatively simple: -| **Given Definition** | **Expression** | **Has Type** | -|:---------------------|:---------------|:-------------| -| `ACTION(Foo)` | `Foo()` | `FooAction` | -| `ACTION_TEMPLATE(Foo, HAS_m_TEMPLATE_PARAMS(...), AND_0_VALUE_PARAMS())` | `Foo<t1, ..., t_m>()` | `FooAction<t1, ..., t_m>` | -| `ACTION_P(Bar, param)` | `Bar(int_value)` | `BarActionP<int>` | -| `ACTION_TEMPLATE(Bar, HAS_m_TEMPLATE_PARAMS(...), AND_1_VALUE_PARAMS(p1))` | `Bar<t1, ..., t_m>(int_value)` | `FooActionP<t1, ..., t_m, int>` | -| `ACTION_P2(Baz, p1, p2)` | `Baz(bool_value, int_value)` | `BazActionP2<bool, int>` | -| `ACTION_TEMPLATE(Baz, HAS_m_TEMPLATE_PARAMS(...), AND_2_VALUE_PARAMS(p1, p2))` | `Baz<t1, ..., t_m>(bool_value, int_value)` | `FooActionP2<t1, ..., t_m, bool, int>` | -| ... | ... | ... | - -Note that we have to pick different suffixes (`Action`, `ActionP`, -`ActionP2`, and etc) for actions with different numbers of value -parameters, or the action definitions cannot be overloaded on the -number of them. - -## Writing New Monomorphic Actions ## - -While the `ACTION*` macros are very convenient, sometimes they are -inappropriate. For example, despite the tricks shown in the previous -recipes, they don't let you directly specify the types of the mock -function arguments and the action parameters, which in general leads -to unoptimized compiler error messages that can baffle unfamiliar -users. They also don't allow overloading actions based on parameter -types without jumping through some hoops. - -An alternative to the `ACTION*` macros is to implement -`::testing::ActionInterface<F>`, where `F` is the type of the mock -function in which the action will be used. For example: - -``` -template <typename F>class ActionInterface { - public: - virtual ~ActionInterface(); - - // Performs the action. Result is the return type of function type - // F, and ArgumentTuple is the tuple of arguments of F. - // - // For example, if F is int(bool, const string&), then Result would - // be int, and ArgumentTuple would be tr1::tuple<bool, const string&>. - virtual Result Perform(const ArgumentTuple& args) = 0; -}; - -using ::testing::_; -using ::testing::Action; -using ::testing::ActionInterface; -using ::testing::MakeAction; - -typedef int IncrementMethod(int*); - -class IncrementArgumentAction : public ActionInterface<IncrementMethod> { - public: - virtual int Perform(const tr1::tuple<int*>& args) { - int* p = tr1::get<0>(args); // Grabs the first argument. - return *p++; - } -}; - -Action<IncrementMethod> IncrementArgument() { - return MakeAction(new IncrementArgumentAction); -} -... - - EXPECT_CALL(foo, Baz(_)) - .WillOnce(IncrementArgument()); - - int n = 5; - foo.Baz(&n); // Should return 5 and change n to 6. -``` - -## Writing New Polymorphic Actions ## - -The previous recipe showed you how to define your own action. This is -all good, except that you need to know the type of the function in -which the action will be used. Sometimes that can be a problem. For -example, if you want to use the action in functions with _different_ -types (e.g. like `Return()` and `SetArgPointee()`). - -If an action can be used in several types of mock functions, we say -it's _polymorphic_. The `MakePolymorphicAction()` function template -makes it easy to define such an action: - -``` -namespace testing { - -template <typename Impl> -PolymorphicAction<Impl> MakePolymorphicAction(const Impl& impl); - -} // namespace testing -``` - -As an example, let's define an action that returns the second argument -in the mock function's argument list. The first step is to define an -implementation class: - -``` -class ReturnSecondArgumentAction { - public: - template <typename Result, typename ArgumentTuple> - Result Perform(const ArgumentTuple& args) const { - // To get the i-th (0-based) argument, use tr1::get<i>(args). - return tr1::get<1>(args); - } -}; -``` - -This implementation class does _not_ need to inherit from any -particular class. What matters is that it must have a `Perform()` -method template. This method template takes the mock function's -arguments as a tuple in a **single** argument, and returns the result of -the action. It can be either `const` or not, but must be invokable -with exactly one template argument, which is the result type. In other -words, you must be able to call `Perform<R>(args)` where `R` is the -mock function's return type and `args` is its arguments in a tuple. - -Next, we use `MakePolymorphicAction()` to turn an instance of the -implementation class into the polymorphic action we need. It will be -convenient to have a wrapper for this: - -``` -using ::testing::MakePolymorphicAction; -using ::testing::PolymorphicAction; - -PolymorphicAction<ReturnSecondArgumentAction> ReturnSecondArgument() { - return MakePolymorphicAction(ReturnSecondArgumentAction()); -} -``` - -Now, you can use this polymorphic action the same way you use the -built-in ones: - -``` -using ::testing::_; - -class MockFoo : public Foo { - public: - MOCK_METHOD2(DoThis, int(bool flag, int n)); - MOCK_METHOD3(DoThat, string(int x, const char* str1, const char* str2)); -}; -... - - MockFoo foo; - EXPECT_CALL(foo, DoThis(_, _)) - .WillOnce(ReturnSecondArgument()); - EXPECT_CALL(foo, DoThat(_, _, _)) - .WillOnce(ReturnSecondArgument()); - ... - foo.DoThis(true, 5); // Will return 5. - foo.DoThat(1, "Hi", "Bye"); // Will return "Hi". -``` - -## Teaching Google Mock How to Print Your Values ## - -When an uninteresting or unexpected call occurs, Google Mock prints the -argument values and the stack trace to help you debug. Assertion -macros like `EXPECT_THAT` and `EXPECT_EQ` also print the values in -question when the assertion fails. Google Mock and Google Test do this using -Google Test's user-extensible value printer. - -This printer knows how to print built-in C++ types, native arrays, STL -containers, and any type that supports the `<<` operator. For other -types, it prints the raw bytes in the value and hopes that you the -user can figure it out. -[Google Test's advanced guide](http://code.google.com/p/googletest/wiki/V1_6_AdvancedGuide#Teaching_Google_Test_How_to_Print_Your_Values) -explains how to extend the printer to do a better job at -printing your particular type than to dump the bytes.
\ No newline at end of file diff --git a/googlemock/docs/v1_6/Documentation.md b/googlemock/docs/v1_6/Documentation.md deleted file mode 100644 index dcc9156..0000000 --- a/googlemock/docs/v1_6/Documentation.md +++ /dev/null @@ -1,12 +0,0 @@ -This page lists all documentation wiki pages for Google Mock **1.6** -- **if you use a released version of Google Mock, please read the documentation for that specific version instead.** - - * [ForDummies](V1_6_ForDummies.md) -- start here if you are new to Google Mock. - * [CheatSheet](V1_6_CheatSheet.md) -- a quick reference. - * [CookBook](V1_6_CookBook.md) -- recipes for doing various tasks using Google Mock. - * [FrequentlyAskedQuestions](V1_6_FrequentlyAskedQuestions.md) -- check here before asking a question on the mailing list. - -To contribute code to Google Mock, read: - - * [DevGuide](DevGuide.md) -- read this _before_ writing your first patch. - * [Pump Manual](http://code.google.com/p/googletest/wiki/V1_6_PumpManual) -- how we generate some of Google Mock's source files.
\ No newline at end of file diff --git a/googlemock/docs/v1_6/ForDummies.md b/googlemock/docs/v1_6/ForDummies.md deleted file mode 100644 index 19ee63a..0000000 --- a/googlemock/docs/v1_6/ForDummies.md +++ /dev/null @@ -1,439 +0,0 @@ - - -(**Note:** If you get compiler errors that you don't understand, be sure to consult [Google Mock Doctor](http://code.google.com/p/googlemock/wiki/V1_6_FrequentlyAskedQuestions#How_am_I_supposed_to_make_sense_of_these_horrible_template_error).) - -# What Is Google C++ Mocking Framework? # -When you write a prototype or test, often it's not feasible or wise to rely on real objects entirely. A **mock object** implements the same interface as a real object (so it can be used as one), but lets you specify at run time how it will be used and what it should do (which methods will be called? in which order? how many times? with what arguments? what will they return? etc). - -**Note:** It is easy to confuse the term _fake objects_ with mock objects. Fakes and mocks actually mean very different things in the Test-Driven Development (TDD) community: - - * **Fake** objects have working implementations, but usually take some shortcut (perhaps to make the operations less expensive), which makes them not suitable for production. An in-memory file system would be an example of a fake. - * **Mocks** are objects pre-programmed with _expectations_, which form a specification of the calls they are expected to receive. - -If all this seems too abstract for you, don't worry - the most important thing to remember is that a mock allows you to check the _interaction_ between itself and code that uses it. The difference between fakes and mocks will become much clearer once you start to use mocks. - -**Google C++ Mocking Framework** (or **Google Mock** for short) is a library (sometimes we also call it a "framework" to make it sound cool) for creating mock classes and using them. It does to C++ what [jMock](http://www.jmock.org/) and [EasyMock](http://www.easymock.org/) do to Java. - -Using Google Mock involves three basic steps: - - 1. Use some simple macros to describe the interface you want to mock, and they will expand to the implementation of your mock class; - 1. Create some mock objects and specify its expectations and behavior using an intuitive syntax; - 1. Exercise code that uses the mock objects. Google Mock will catch any violation of the expectations as soon as it arises. - -# Why Google Mock? # -While mock objects help you remove unnecessary dependencies in tests and make them fast and reliable, using mocks manually in C++ is _hard_: - - * Someone has to implement the mocks. The job is usually tedious and error-prone. No wonder people go great distance to avoid it. - * The quality of those manually written mocks is a bit, uh, unpredictable. You may see some really polished ones, but you may also see some that were hacked up in a hurry and have all sorts of ad hoc restrictions. - * The knowledge you gained from using one mock doesn't transfer to the next. - -In contrast, Java and Python programmers have some fine mock frameworks, which automate the creation of mocks. As a result, mocking is a proven effective technique and widely adopted practice in those communities. Having the right tool absolutely makes the difference. - -Google Mock was built to help C++ programmers. It was inspired by [jMock](http://www.jmock.org/) and [EasyMock](http://www.easymock.org/), but designed with C++'s specifics in mind. It is your friend if any of the following problems is bothering you: - - * You are stuck with a sub-optimal design and wish you had done more prototyping before it was too late, but prototyping in C++ is by no means "rapid". - * Your tests are slow as they depend on too many libraries or use expensive resources (e.g. a database). - * Your tests are brittle as some resources they use are unreliable (e.g. the network). - * You want to test how your code handles a failure (e.g. a file checksum error), but it's not easy to cause one. - * You need to make sure that your module interacts with other modules in the right way, but it's hard to observe the interaction; therefore you resort to observing the side effects at the end of the action, which is awkward at best. - * You want to "mock out" your dependencies, except that they don't have mock implementations yet; and, frankly, you aren't thrilled by some of those hand-written mocks. - -We encourage you to use Google Mock as: - - * a _design_ tool, for it lets you experiment with your interface design early and often. More iterations lead to better designs! - * a _testing_ tool to cut your tests' outbound dependencies and probe the interaction between your module and its collaborators. - -# Getting Started # -Using Google Mock is easy! Inside your C++ source file, just `#include` `"gtest/gtest.h"` and `"gmock/gmock.h"`, and you are ready to go. - -# A Case for Mock Turtles # -Let's look at an example. Suppose you are developing a graphics program that relies on a LOGO-like API for drawing. How would you test that it does the right thing? Well, you can run it and compare the screen with a golden screen snapshot, but let's admit it: tests like this are expensive to run and fragile (What if you just upgraded to a shiny new graphics card that has better anti-aliasing? Suddenly you have to update all your golden images.). It would be too painful if all your tests are like this. Fortunately, you learned about Dependency Injection and know the right thing to do: instead of having your application talk to the drawing API directly, wrap the API in an interface (say, `Turtle`) and code to that interface: - -``` -class Turtle { - ... - virtual ~Turtle() {} - virtual void PenUp() = 0; - virtual void PenDown() = 0; - virtual void Forward(int distance) = 0; - virtual void Turn(int degrees) = 0; - virtual void GoTo(int x, int y) = 0; - virtual int GetX() const = 0; - virtual int GetY() const = 0; -}; -``` - -(Note that the destructor of `Turtle` **must** be virtual, as is the case for **all** classes you intend to inherit from - otherwise the destructor of the derived class will not be called when you delete an object through a base pointer, and you'll get corrupted program states like memory leaks.) - -You can control whether the turtle's movement will leave a trace using `PenUp()` and `PenDown()`, and control its movement using `Forward()`, `Turn()`, and `GoTo()`. Finally, `GetX()` and `GetY()` tell you the current position of the turtle. - -Your program will normally use a real implementation of this interface. In tests, you can use a mock implementation instead. This allows you to easily check what drawing primitives your program is calling, with what arguments, and in which order. Tests written this way are much more robust (they won't break because your new machine does anti-aliasing differently), easier to read and maintain (the intent of a test is expressed in the code, not in some binary images), and run _much, much faster_. - -# Writing the Mock Class # -If you are lucky, the mocks you need to use have already been implemented by some nice people. If, however, you find yourself in the position to write a mock class, relax - Google Mock turns this task into a fun game! (Well, almost.) - -## How to Define It ## -Using the `Turtle` interface as example, here are the simple steps you need to follow: - - 1. Derive a class `MockTurtle` from `Turtle`. - 1. Take a _virtual_ function of `Turtle` (while it's possible to [mock non-virtual methods using templates](http://code.google.com/p/googlemock/wiki/V1_6_CookBook#Mocking_Nonvirtual_Methods), it's much more involved). Count how many arguments it has. - 1. In the `public:` section of the child class, write `MOCK_METHODn();` (or `MOCK_CONST_METHODn();` if you are mocking a `const` method), where `n` is the number of the arguments; if you counted wrong, shame on you, and a compiler error will tell you so. - 1. Now comes the fun part: you take the function signature, cut-and-paste the _function name_ as the _first_ argument to the macro, and leave what's left as the _second_ argument (in case you're curious, this is the _type of the function_). - 1. Repeat until all virtual functions you want to mock are done. - -After the process, you should have something like: - -``` -#include "gmock/gmock.h" // Brings in Google Mock. -class MockTurtle : public Turtle { - public: - ... - MOCK_METHOD0(PenUp, void()); - MOCK_METHOD0(PenDown, void()); - MOCK_METHOD1(Forward, void(int distance)); - MOCK_METHOD1(Turn, void(int degrees)); - MOCK_METHOD2(GoTo, void(int x, int y)); - MOCK_CONST_METHOD0(GetX, int()); - MOCK_CONST_METHOD0(GetY, int()); -}; -``` - -You don't need to define these mock methods somewhere else - the `MOCK_METHOD*` macros will generate the definitions for you. It's that simple! Once you get the hang of it, you can pump out mock classes faster than your source-control system can handle your check-ins. - -**Tip:** If even this is too much work for you, you'll find the -`gmock_gen.py` tool in Google Mock's `scripts/generator/` directory (courtesy of the [cppclean](http://code.google.com/p/cppclean/) project) useful. This command-line -tool requires that you have Python 2.4 installed. You give it a C++ file and the name of an abstract class defined in it, -and it will print the definition of the mock class for you. Due to the -complexity of the C++ language, this script may not always work, but -it can be quite handy when it does. For more details, read the [user documentation](http://code.google.com/p/googlemock/source/browse/trunk/scripts/generator/README). - -## Where to Put It ## -When you define a mock class, you need to decide where to put its definition. Some people put it in a `*_test.cc`. This is fine when the interface being mocked (say, `Foo`) is owned by the same person or team. Otherwise, when the owner of `Foo` changes it, your test could break. (You can't really expect `Foo`'s maintainer to fix every test that uses `Foo`, can you?) - -So, the rule of thumb is: if you need to mock `Foo` and it's owned by others, define the mock class in `Foo`'s package (better, in a `testing` sub-package such that you can clearly separate production code and testing utilities), and put it in a `mock_foo.h`. Then everyone can reference `mock_foo.h` from their tests. If `Foo` ever changes, there is only one copy of `MockFoo` to change, and only tests that depend on the changed methods need to be fixed. - -Another way to do it: you can introduce a thin layer `FooAdaptor` on top of `Foo` and code to this new interface. Since you own `FooAdaptor`, you can absorb changes in `Foo` much more easily. While this is more work initially, carefully choosing the adaptor interface can make your code easier to write and more readable (a net win in the long run), as you can choose `FooAdaptor` to fit your specific domain much better than `Foo` does. - -# Using Mocks in Tests # -Once you have a mock class, using it is easy. The typical work flow is: - - 1. Import the Google Mock names from the `testing` namespace such that you can use them unqualified (You only have to do it once per file. Remember that namespaces are a good idea and good for your health.). - 1. Create some mock objects. - 1. Specify your expectations on them (How many times will a method be called? With what arguments? What should it do? etc.). - 1. Exercise some code that uses the mocks; optionally, check the result using Google Test assertions. If a mock method is called more than expected or with wrong arguments, you'll get an error immediately. - 1. When a mock is destructed, Google Mock will automatically check whether all expectations on it have been satisfied. - -Here's an example: - -``` -#include "path/to/mock-turtle.h" -#include "gmock/gmock.h" -#include "gtest/gtest.h" -using ::testing::AtLeast; // #1 - -TEST(PainterTest, CanDrawSomething) { - MockTurtle turtle; // #2 - EXPECT_CALL(turtle, PenDown()) // #3 - .Times(AtLeast(1)); - - Painter painter(&turtle); // #4 - - EXPECT_TRUE(painter.DrawCircle(0, 0, 10)); -} // #5 - -int main(int argc, char** argv) { - // The following line must be executed to initialize Google Mock - // (and Google Test) before running the tests. - ::testing::InitGoogleMock(&argc, argv); - return RUN_ALL_TESTS(); -} -``` - -As you might have guessed, this test checks that `PenDown()` is called at least once. If the `painter` object didn't call this method, your test will fail with a message like this: - -``` -path/to/my_test.cc:119: Failure -Actual function call count doesn't match this expectation: -Actually: never called; -Expected: called at least once. -``` - -**Tip 1:** If you run the test from an Emacs buffer, you can hit `<Enter>` on the line number displayed in the error message to jump right to the failed expectation. - -**Tip 2:** If your mock objects are never deleted, the final verification won't happen. Therefore it's a good idea to use a heap leak checker in your tests when you allocate mocks on the heap. - -**Important note:** Google Mock requires expectations to be set **before** the mock functions are called, otherwise the behavior is **undefined**. In particular, you mustn't interleave `EXPECT_CALL()`s and calls to the mock functions. - -This means `EXPECT_CALL()` should be read as expecting that a call will occur _in the future_, not that a call has occurred. Why does Google Mock work like that? Well, specifying the expectation beforehand allows Google Mock to report a violation as soon as it arises, when the context (stack trace, etc) is still available. This makes debugging much easier. - -Admittedly, this test is contrived and doesn't do much. You can easily achieve the same effect without using Google Mock. However, as we shall reveal soon, Google Mock allows you to do _much more_ with the mocks. - -## Using Google Mock with Any Testing Framework ## -If you want to use something other than Google Test (e.g. [CppUnit](http://apps.sourceforge.net/mediawiki/cppunit/index.php?title=Main_Page) or -[CxxTest](http://cxxtest.tigris.org/)) as your testing framework, just change the `main()` function in the previous section to: -``` -int main(int argc, char** argv) { - // The following line causes Google Mock to throw an exception on failure, - // which will be interpreted by your testing framework as a test failure. - ::testing::GTEST_FLAG(throw_on_failure) = true; - ::testing::InitGoogleMock(&argc, argv); - ... whatever your testing framework requires ... -} -``` - -This approach has a catch: it makes Google Mock throw an exception -from a mock object's destructor sometimes. With some compilers, this -sometimes causes the test program to crash. You'll still be able to -notice that the test has failed, but it's not a graceful failure. - -A better solution is to use Google Test's -[event listener API](http://code.google.com/p/googletest/wiki/V1_6_AdvancedGuide#Extending_Google_Test_by_Handling_Test_Events) -to report a test failure to your testing framework properly. You'll need to -implement the `OnTestPartResult()` method of the event listener interface, but it -should be straightforward. - -If this turns out to be too much work, we suggest that you stick with -Google Test, which works with Google Mock seamlessly (in fact, it is -technically part of Google Mock.). If there is a reason that you -cannot use Google Test, please let us know. - -# Setting Expectations # -The key to using a mock object successfully is to set the _right expectations_ on it. If you set the expectations too strict, your test will fail as the result of unrelated changes. If you set them too loose, bugs can slip through. You want to do it just right such that your test can catch exactly the kind of bugs you intend it to catch. Google Mock provides the necessary means for you to do it "just right." - -## General Syntax ## -In Google Mock we use the `EXPECT_CALL()` macro to set an expectation on a mock method. The general syntax is: - -``` -EXPECT_CALL(mock_object, method(matchers)) - .Times(cardinality) - .WillOnce(action) - .WillRepeatedly(action); -``` - -The macro has two arguments: first the mock object, and then the method and its arguments. Note that the two are separated by a comma (`,`), not a period (`.`). (Why using a comma? The answer is that it was necessary for technical reasons.) - -The macro can be followed by some optional _clauses_ that provide more information about the expectation. We'll discuss how each clause works in the coming sections. - -This syntax is designed to make an expectation read like English. For example, you can probably guess that - -``` -using ::testing::Return;... -EXPECT_CALL(turtle, GetX()) - .Times(5) - .WillOnce(Return(100)) - .WillOnce(Return(150)) - .WillRepeatedly(Return(200)); -``` - -says that the `turtle` object's `GetX()` method will be called five times, it will return 100 the first time, 150 the second time, and then 200 every time. Some people like to call this style of syntax a Domain-Specific Language (DSL). - -**Note:** Why do we use a macro to do this? It serves two purposes: first it makes expectations easily identifiable (either by `grep` or by a human reader), and second it allows Google Mock to include the source file location of a failed expectation in messages, making debugging easier. - -## Matchers: What Arguments Do We Expect? ## -When a mock function takes arguments, we must specify what arguments we are expecting; for example: - -``` -// Expects the turtle to move forward by 100 units. -EXPECT_CALL(turtle, Forward(100)); -``` - -Sometimes you may not want to be too specific (Remember that talk about tests being too rigid? Over specification leads to brittle tests and obscures the intent of tests. Therefore we encourage you to specify only what's necessary - no more, no less.). If you care to check that `Forward()` will be called but aren't interested in its actual argument, write `_` as the argument, which means "anything goes": - -``` -using ::testing::_; -... -// Expects the turtle to move forward. -EXPECT_CALL(turtle, Forward(_)); -``` - -`_` is an instance of what we call **matchers**. A matcher is like a predicate and can test whether an argument is what we'd expect. You can use a matcher inside `EXPECT_CALL()` wherever a function argument is expected. - -A list of built-in matchers can be found in the [CheatSheet](V1_6_CheatSheet.md). For example, here's the `Ge` (greater than or equal) matcher: - -``` -using ::testing::Ge;... -EXPECT_CALL(turtle, Forward(Ge(100))); -``` - -This checks that the turtle will be told to go forward by at least 100 units. - -## Cardinalities: How Many Times Will It Be Called? ## -The first clause we can specify following an `EXPECT_CALL()` is `Times()`. We call its argument a **cardinality** as it tells _how many times_ the call should occur. It allows us to repeat an expectation many times without actually writing it as many times. More importantly, a cardinality can be "fuzzy", just like a matcher can be. This allows a user to express the intent of a test exactly. - -An interesting special case is when we say `Times(0)`. You may have guessed - it means that the function shouldn't be called with the given arguments at all, and Google Mock will report a Google Test failure whenever the function is (wrongfully) called. - -We've seen `AtLeast(n)` as an example of fuzzy cardinalities earlier. For the list of built-in cardinalities you can use, see the [CheatSheet](V1_6_CheatSheet.md). - -The `Times()` clause can be omitted. **If you omit `Times()`, Google Mock will infer the cardinality for you.** The rules are easy to remember: - - * If **neither** `WillOnce()` **nor** `WillRepeatedly()` is in the `EXPECT_CALL()`, the inferred cardinality is `Times(1)`. - * If there are `n WillOnce()`'s but **no** `WillRepeatedly()`, where `n` >= 1, the cardinality is `Times(n)`. - * If there are `n WillOnce()`'s and **one** `WillRepeatedly()`, where `n` >= 0, the cardinality is `Times(AtLeast(n))`. - -**Quick quiz:** what do you think will happen if a function is expected to be called twice but actually called four times? - -## Actions: What Should It Do? ## -Remember that a mock object doesn't really have a working implementation? We as users have to tell it what to do when a method is invoked. This is easy in Google Mock. - -First, if the return type of a mock function is a built-in type or a pointer, the function has a **default action** (a `void` function will just return, a `bool` function will return `false`, and other functions will return 0). If you don't say anything, this behavior will be used. - -Second, if a mock function doesn't have a default action, or the default action doesn't suit you, you can specify the action to be taken each time the expectation matches using a series of `WillOnce()` clauses followed by an optional `WillRepeatedly()`. For example, - -``` -using ::testing::Return;... -EXPECT_CALL(turtle, GetX()) - .WillOnce(Return(100)) - .WillOnce(Return(200)) - .WillOnce(Return(300)); -``` - -This says that `turtle.GetX()` will be called _exactly three times_ (Google Mock inferred this from how many `WillOnce()` clauses we've written, since we didn't explicitly write `Times()`), and will return 100, 200, and 300 respectively. - -``` -using ::testing::Return;... -EXPECT_CALL(turtle, GetY()) - .WillOnce(Return(100)) - .WillOnce(Return(200)) - .WillRepeatedly(Return(300)); -``` - -says that `turtle.GetY()` will be called _at least twice_ (Google Mock knows this as we've written two `WillOnce()` clauses and a `WillRepeatedly()` while having no explicit `Times()`), will return 100 the first time, 200 the second time, and 300 from the third time on. - -Of course, if you explicitly write a `Times()`, Google Mock will not try to infer the cardinality itself. What if the number you specified is larger than there are `WillOnce()` clauses? Well, after all `WillOnce()`s are used up, Google Mock will do the _default_ action for the function every time (unless, of course, you have a `WillRepeatedly()`.). - -What can we do inside `WillOnce()` besides `Return()`? You can return a reference using `ReturnRef(variable)`, or invoke a pre-defined function, among [others](http://code.google.com/p/googlemock/wiki/V1_6_CheatSheet#Actions). - -**Important note:** The `EXPECT_CALL()` statement evaluates the action clause only once, even though the action may be performed many times. Therefore you must be careful about side effects. The following may not do what you want: - -``` -int n = 100; -EXPECT_CALL(turtle, GetX()) -.Times(4) -.WillRepeatedly(Return(n++)); -``` - -Instead of returning 100, 101, 102, ..., consecutively, this mock function will always return 100 as `n++` is only evaluated once. Similarly, `Return(new Foo)` will create a new `Foo` object when the `EXPECT_CALL()` is executed, and will return the same pointer every time. If you want the side effect to happen every time, you need to define a custom action, which we'll teach in the [CookBook](V1_6_CookBook.md). - -Time for another quiz! What do you think the following means? - -``` -using ::testing::Return;... -EXPECT_CALL(turtle, GetY()) -.Times(4) -.WillOnce(Return(100)); -``` - -Obviously `turtle.GetY()` is expected to be called four times. But if you think it will return 100 every time, think twice! Remember that one `WillOnce()` clause will be consumed each time the function is invoked and the default action will be taken afterwards. So the right answer is that `turtle.GetY()` will return 100 the first time, but **return 0 from the second time on**, as returning 0 is the default action for `int` functions. - -## Using Multiple Expectations ## -So far we've only shown examples where you have a single expectation. More realistically, you're going to specify expectations on multiple mock methods, which may be from multiple mock objects. - -By default, when a mock method is invoked, Google Mock will search the expectations in the **reverse order** they are defined, and stop when an active expectation that matches the arguments is found (you can think of it as "newer rules override older ones."). If the matching expectation cannot take any more calls, you will get an upper-bound-violated failure. Here's an example: - -``` -using ::testing::_;... -EXPECT_CALL(turtle, Forward(_)); // #1 -EXPECT_CALL(turtle, Forward(10)) // #2 - .Times(2); -``` - -If `Forward(10)` is called three times in a row, the third time it will be an error, as the last matching expectation (#2) has been saturated. If, however, the third `Forward(10)` call is replaced by `Forward(20)`, then it would be OK, as now #1 will be the matching expectation. - -**Side note:** Why does Google Mock search for a match in the _reverse_ order of the expectations? The reason is that this allows a user to set up the default expectations in a mock object's constructor or the test fixture's set-up phase and then customize the mock by writing more specific expectations in the test body. So, if you have two expectations on the same method, you want to put the one with more specific matchers **after** the other, or the more specific rule would be shadowed by the more general one that comes after it. - -## Ordered vs Unordered Calls ## -By default, an expectation can match a call even though an earlier expectation hasn't been satisfied. In other words, the calls don't have to occur in the order the expectations are specified. - -Sometimes, you may want all the expected calls to occur in a strict order. To say this in Google Mock is easy: - -``` -using ::testing::InSequence;... -TEST(FooTest, DrawsLineSegment) { - ... - { - InSequence dummy; - - EXPECT_CALL(turtle, PenDown()); - EXPECT_CALL(turtle, Forward(100)); - EXPECT_CALL(turtle, PenUp()); - } - Foo(); -} -``` - -By creating an object of type `InSequence`, all expectations in its scope are put into a _sequence_ and have to occur _sequentially_. Since we are just relying on the constructor and destructor of this object to do the actual work, its name is really irrelevant. - -In this example, we test that `Foo()` calls the three expected functions in the order as written. If a call is made out-of-order, it will be an error. - -(What if you care about the relative order of some of the calls, but not all of them? Can you specify an arbitrary partial order? The answer is ... yes! If you are impatient, the details can be found in the [CookBook](V1_6_CookBook.md).) - -## All Expectations Are Sticky (Unless Said Otherwise) ## -Now let's do a quick quiz to see how well you can use this mock stuff already. How would you test that the turtle is asked to go to the origin _exactly twice_ (you want to ignore any other instructions it receives)? - -After you've come up with your answer, take a look at ours and compare notes (solve it yourself first - don't cheat!): - -``` -using ::testing::_;... -EXPECT_CALL(turtle, GoTo(_, _)) // #1 - .Times(AnyNumber()); -EXPECT_CALL(turtle, GoTo(0, 0)) // #2 - .Times(2); -``` - -Suppose `turtle.GoTo(0, 0)` is called three times. In the third time, Google Mock will see that the arguments match expectation #2 (remember that we always pick the last matching expectation). Now, since we said that there should be only two such calls, Google Mock will report an error immediately. This is basically what we've told you in the "Using Multiple Expectations" section above. - -This example shows that **expectations in Google Mock are "sticky" by default**, in the sense that they remain active even after we have reached their invocation upper bounds. This is an important rule to remember, as it affects the meaning of the spec, and is **different** to how it's done in many other mocking frameworks (Why'd we do that? Because we think our rule makes the common cases easier to express and understand.). - -Simple? Let's see if you've really understood it: what does the following code say? - -``` -using ::testing::Return; -... -for (int i = n; i > 0; i--) { - EXPECT_CALL(turtle, GetX()) - .WillOnce(Return(10*i)); -} -``` - -If you think it says that `turtle.GetX()` will be called `n` times and will return 10, 20, 30, ..., consecutively, think twice! The problem is that, as we said, expectations are sticky. So, the second time `turtle.GetX()` is called, the last (latest) `EXPECT_CALL()` statement will match, and will immediately lead to an "upper bound exceeded" error - this piece of code is not very useful! - -One correct way of saying that `turtle.GetX()` will return 10, 20, 30, ..., is to explicitly say that the expectations are _not_ sticky. In other words, they should _retire_ as soon as they are saturated: - -``` -using ::testing::Return; -... -for (int i = n; i > 0; i--) { - EXPECT_CALL(turtle, GetX()) - .WillOnce(Return(10*i)) - .RetiresOnSaturation(); -} -``` - -And, there's a better way to do it: in this case, we expect the calls to occur in a specific order, and we line up the actions to match the order. Since the order is important here, we should make it explicit using a sequence: - -``` -using ::testing::InSequence; -using ::testing::Return; -... -{ - InSequence s; - - for (int i = 1; i <= n; i++) { - EXPECT_CALL(turtle, GetX()) - .WillOnce(Return(10*i)) - .RetiresOnSaturation(); - } -} -``` - -By the way, the other situation where an expectation may _not_ be sticky is when it's in a sequence - as soon as another expectation that comes after it in the sequence has been used, it automatically retires (and will never be used to match any call). - -## Uninteresting Calls ## -A mock object may have many methods, and not all of them are that interesting. For example, in some tests we may not care about how many times `GetX()` and `GetY()` get called. - -In Google Mock, if you are not interested in a method, just don't say anything about it. If a call to this method occurs, you'll see a warning in the test output, but it won't be a failure. - -# What Now? # -Congratulations! You've learned enough about Google Mock to start using it. Now, you might want to join the [googlemock](http://groups.google.com/group/googlemock) discussion group and actually write some tests using Google Mock - it will be fun. Hey, it may even be addictive - you've been warned. - -Then, if you feel like increasing your mock quotient, you should move on to the [CookBook](V1_6_CookBook.md). You can learn many advanced features of Google Mock there -- and advance your level of enjoyment and testing bliss.
\ No newline at end of file diff --git a/googlemock/docs/v1_6/FrequentlyAskedQuestions.md b/googlemock/docs/v1_6/FrequentlyAskedQuestions.md deleted file mode 100644 index f74715d..0000000 --- a/googlemock/docs/v1_6/FrequentlyAskedQuestions.md +++ /dev/null @@ -1,628 +0,0 @@ - - -Please send your questions to the -[googlemock](http://groups.google.com/group/googlemock) discussion -group. If you need help with compiler errors, make sure you have -tried [Google Mock Doctor](#How_am_I_supposed_to_make_sense_of_these_horrible_template_error.md) first. - -## When I call a method on my mock object, the method for the real object is invoked instead. What's the problem? ## - -In order for a method to be mocked, it must be _virtual_, unless you use the [high-perf dependency injection technique](http://code.google.com/p/googlemock/wiki/V1_6_CookBook#Mocking_Nonvirtual_Methods). - -## I wrote some matchers. After I upgraded to a new version of Google Mock, they no longer compile. What's going on? ## - -After version 1.4.0 of Google Mock was released, we had an idea on how -to make it easier to write matchers that can generate informative -messages efficiently. We experimented with this idea and liked what -we saw. Therefore we decided to implement it. - -Unfortunately, this means that if you have defined your own matchers -by implementing `MatcherInterface` or using `MakePolymorphicMatcher()`, -your definitions will no longer compile. Matchers defined using the -`MATCHER*` family of macros are not affected. - -Sorry for the hassle if your matchers are affected. We believe it's -in everyone's long-term interest to make this change sooner than -later. Fortunately, it's usually not hard to migrate an existing -matcher to the new API. Here's what you need to do: - -If you wrote your matcher like this: -``` -// Old matcher definition that doesn't work with the latest -// Google Mock. -using ::testing::MatcherInterface; -... -class MyWonderfulMatcher : public MatcherInterface<MyType> { - public: - ... - virtual bool Matches(MyType value) const { - // Returns true if value matches. - return value.GetFoo() > 5; - } - ... -}; -``` - -you'll need to change it to: -``` -// New matcher definition that works with the latest Google Mock. -using ::testing::MatcherInterface; -using ::testing::MatchResultListener; -... -class MyWonderfulMatcher : public MatcherInterface<MyType> { - public: - ... - virtual bool MatchAndExplain(MyType value, - MatchResultListener* listener) const { - // Returns true if value matches. - return value.GetFoo() > 5; - } - ... -}; -``` -(i.e. rename `Matches()` to `MatchAndExplain()` and give it a second -argument of type `MatchResultListener*`.) - -If you were also using `ExplainMatchResultTo()` to improve the matcher -message: -``` -// Old matcher definition that doesn't work with the lastest -// Google Mock. -using ::testing::MatcherInterface; -... -class MyWonderfulMatcher : public MatcherInterface<MyType> { - public: - ... - virtual bool Matches(MyType value) const { - // Returns true if value matches. - return value.GetFoo() > 5; - } - - virtual void ExplainMatchResultTo(MyType value, - ::std::ostream* os) const { - // Prints some helpful information to os to help - // a user understand why value matches (or doesn't match). - *os << "the Foo property is " << value.GetFoo(); - } - ... -}; -``` - -you should move the logic of `ExplainMatchResultTo()` into -`MatchAndExplain()`, using the `MatchResultListener` argument where -the `::std::ostream` was used: -``` -// New matcher definition that works with the latest Google Mock. -using ::testing::MatcherInterface; -using ::testing::MatchResultListener; -... -class MyWonderfulMatcher : public MatcherInterface<MyType> { - public: - ... - virtual bool MatchAndExplain(MyType value, - MatchResultListener* listener) const { - // Returns true if value matches. - *listener << "the Foo property is " << value.GetFoo(); - return value.GetFoo() > 5; - } - ... -}; -``` - -If your matcher is defined using `MakePolymorphicMatcher()`: -``` -// Old matcher definition that doesn't work with the latest -// Google Mock. -using ::testing::MakePolymorphicMatcher; -... -class MyGreatMatcher { - public: - ... - bool Matches(MyType value) const { - // Returns true if value matches. - return value.GetBar() < 42; - } - ... -}; -... MakePolymorphicMatcher(MyGreatMatcher()) ... -``` - -you should rename the `Matches()` method to `MatchAndExplain()` and -add a `MatchResultListener*` argument (the same as what you need to do -for matchers defined by implementing `MatcherInterface`): -``` -// New matcher definition that works with the latest Google Mock. -using ::testing::MakePolymorphicMatcher; -using ::testing::MatchResultListener; -... -class MyGreatMatcher { - public: - ... - bool MatchAndExplain(MyType value, - MatchResultListener* listener) const { - // Returns true if value matches. - return value.GetBar() < 42; - } - ... -}; -... MakePolymorphicMatcher(MyGreatMatcher()) ... -``` - -If your polymorphic matcher uses `ExplainMatchResultTo()` for better -failure messages: -``` -// Old matcher definition that doesn't work with the latest -// Google Mock. -using ::testing::MakePolymorphicMatcher; -... -class MyGreatMatcher { - public: - ... - bool Matches(MyType value) const { - // Returns true if value matches. - return value.GetBar() < 42; - } - ... -}; -void ExplainMatchResultTo(const MyGreatMatcher& matcher, - MyType value, - ::std::ostream* os) { - // Prints some helpful information to os to help - // a user understand why value matches (or doesn't match). - *os << "the Bar property is " << value.GetBar(); -} -... MakePolymorphicMatcher(MyGreatMatcher()) ... -``` - -you'll need to move the logic inside `ExplainMatchResultTo()` to -`MatchAndExplain()`: -``` -// New matcher definition that works with the latest Google Mock. -using ::testing::MakePolymorphicMatcher; -using ::testing::MatchResultListener; -... -class MyGreatMatcher { - public: - ... - bool MatchAndExplain(MyType value, - MatchResultListener* listener) const { - // Returns true if value matches. - *listener << "the Bar property is " << value.GetBar(); - return value.GetBar() < 42; - } - ... -}; -... MakePolymorphicMatcher(MyGreatMatcher()) ... -``` - -For more information, you can read these -[two](http://code.google.com/p/googlemock/wiki/V1_6_CookBook#Writing_New_Monomorphic_Matchers) -[recipes](http://code.google.com/p/googlemock/wiki/V1_6_CookBook#Writing_New_Polymorphic_Matchers) -from the cookbook. As always, you -are welcome to post questions on `googlemock@googlegroups.com` if you -need any help. - -## When using Google Mock, do I have to use Google Test as the testing framework? I have my favorite testing framework and don't want to switch. ## - -Google Mock works out of the box with Google Test. However, it's easy -to configure it to work with any testing framework of your choice. -[Here](http://code.google.com/p/googlemock/wiki/V1_6_ForDummies#Using_Google_Mock_with_Any_Testing_Framework) is how. - -## How am I supposed to make sense of these horrible template errors? ## - -If you are confused by the compiler errors gcc threw at you, -try consulting the _Google Mock Doctor_ tool first. What it does is to -scan stdin for gcc error messages, and spit out diagnoses on the -problems (we call them diseases) your code has. - -To "install", run command: -``` -alias gmd='<path to googlemock>/scripts/gmock_doctor.py' -``` - -To use it, do: -``` -<your-favorite-build-command> <your-test> 2>&1 | gmd -``` - -For example: -``` -make my_test 2>&1 | gmd -``` - -Or you can run `gmd` and copy-n-paste gcc's error messages to it. - -## Can I mock a variadic function? ## - -You cannot mock a variadic function (i.e. a function taking ellipsis -(`...`) arguments) directly in Google Mock. - -The problem is that in general, there is _no way_ for a mock object to -know how many arguments are passed to the variadic method, and what -the arguments' types are. Only the _author of the base class_ knows -the protocol, and we cannot look into his head. - -Therefore, to mock such a function, the _user_ must teach the mock -object how to figure out the number of arguments and their types. One -way to do it is to provide overloaded versions of the function. - -Ellipsis arguments are inherited from C and not really a C++ feature. -They are unsafe to use and don't work with arguments that have -constructors or destructors. Therefore we recommend to avoid them in -C++ as much as possible. - -## MSVC gives me warning C4301 or C4373 when I define a mock method with a const parameter. Why? ## - -If you compile this using Microsoft Visual C++ 2005 SP1: -``` -class Foo { - ... - virtual void Bar(const int i) = 0; -}; - -class MockFoo : public Foo { - ... - MOCK_METHOD1(Bar, void(const int i)); -}; -``` -You may get the following warning: -``` -warning C4301: 'MockFoo::Bar': overriding virtual function only differs from 'Foo::Bar' by const/volatile qualifier -``` - -This is a MSVC bug. The same code compiles fine with gcc ,for -example. If you use Visual C++ 2008 SP1, you would get the warning: -``` -warning C4373: 'MockFoo::Bar': virtual function overrides 'Foo::Bar', previous versions of the compiler did not override when parameters only differed by const/volatile qualifiers -``` - -In C++, if you _declare_ a function with a `const` parameter, the -`const` modifier is _ignored_. Therefore, the `Foo` base class above -is equivalent to: -``` -class Foo { - ... - virtual void Bar(int i) = 0; // int or const int? Makes no difference. -}; -``` - -In fact, you can _declare_ Bar() with an `int` parameter, and _define_ -it with a `const int` parameter. The compiler will still match them -up. - -Since making a parameter `const` is meaningless in the method -_declaration_, we recommend to remove it in both `Foo` and `MockFoo`. -That should workaround the VC bug. - -Note that we are talking about the _top-level_ `const` modifier here. -If the function parameter is passed by pointer or reference, declaring -the _pointee_ or _referee_ as `const` is still meaningful. For -example, the following two declarations are _not_ equivalent: -``` -void Bar(int* p); // Neither p nor *p is const. -void Bar(const int* p); // p is not const, but *p is. -``` - -## I have a huge mock class, and Microsoft Visual C++ runs out of memory when compiling it. What can I do? ## - -We've noticed that when the `/clr` compiler flag is used, Visual C++ -uses 5~6 times as much memory when compiling a mock class. We suggest -to avoid `/clr` when compiling native C++ mocks. - -## I can't figure out why Google Mock thinks my expectations are not satisfied. What should I do? ## - -You might want to run your test with -`--gmock_verbose=info`. This flag lets Google Mock print a trace -of every mock function call it receives. By studying the trace, -you'll gain insights on why the expectations you set are not met. - -## How can I assert that a function is NEVER called? ## - -``` -EXPECT_CALL(foo, Bar(_)) - .Times(0); -``` - -## I have a failed test where Google Mock tells me TWICE that a particular expectation is not satisfied. Isn't this redundant? ## - -When Google Mock detects a failure, it prints relevant information -(the mock function arguments, the state of relevant expectations, and -etc) to help the user debug. If another failure is detected, Google -Mock will do the same, including printing the state of relevant -expectations. - -Sometimes an expectation's state didn't change between two failures, -and you'll see the same description of the state twice. They are -however _not_ redundant, as they refer to _different points in time_. -The fact they are the same _is_ interesting information. - -## I get a heap check failure when using a mock object, but using a real object is fine. What can be wrong? ## - -Does the class (hopefully a pure interface) you are mocking have a -virtual destructor? - -Whenever you derive from a base class, make sure its destructor is -virtual. Otherwise Bad Things will happen. Consider the following -code: - -``` -class Base { - public: - // Not virtual, but should be. - ~Base() { ... } - ... -}; - -class Derived : public Base { - public: - ... - private: - std::string value_; -}; - -... - Base* p = new Derived; - ... - delete p; // Surprise! ~Base() will be called, but ~Derived() will not - // - value_ is leaked. -``` - -By changing `~Base()` to virtual, `~Derived()` will be correctly -called when `delete p` is executed, and the heap checker -will be happy. - -## The "newer expectations override older ones" rule makes writing expectations awkward. Why does Google Mock do that? ## - -When people complain about this, often they are referring to code like: - -``` -// foo.Bar() should be called twice, return 1 the first time, and return -// 2 the second time. However, I have to write the expectations in the -// reverse order. This sucks big time!!! -EXPECT_CALL(foo, Bar()) - .WillOnce(Return(2)) - .RetiresOnSaturation(); -EXPECT_CALL(foo, Bar()) - .WillOnce(Return(1)) - .RetiresOnSaturation(); -``` - -The problem is that they didn't pick the **best** way to express the test's -intent. - -By default, expectations don't have to be matched in _any_ particular -order. If you want them to match in a certain order, you need to be -explicit. This is Google Mock's (and jMock's) fundamental philosophy: it's -easy to accidentally over-specify your tests, and we want to make it -harder to do so. - -There are two better ways to write the test spec. You could either -put the expectations in sequence: - -``` -// foo.Bar() should be called twice, return 1 the first time, and return -// 2 the second time. Using a sequence, we can write the expectations -// in their natural order. -{ - InSequence s; - EXPECT_CALL(foo, Bar()) - .WillOnce(Return(1)) - .RetiresOnSaturation(); - EXPECT_CALL(foo, Bar()) - .WillOnce(Return(2)) - .RetiresOnSaturation(); -} -``` - -or you can put the sequence of actions in the same expectation: - -``` -// foo.Bar() should be called twice, return 1 the first time, and return -// 2 the second time. -EXPECT_CALL(foo, Bar()) - .WillOnce(Return(1)) - .WillOnce(Return(2)) - .RetiresOnSaturation(); -``` - -Back to the original questions: why does Google Mock search the -expectations (and `ON_CALL`s) from back to front? Because this -allows a user to set up a mock's behavior for the common case early -(e.g. in the mock's constructor or the test fixture's set-up phase) -and customize it with more specific rules later. If Google Mock -searches from front to back, this very useful pattern won't be -possible. - -## Google Mock prints a warning when a function without EXPECT\_CALL is called, even if I have set its behavior using ON\_CALL. Would it be reasonable not to show the warning in this case? ## - -When choosing between being neat and being safe, we lean toward the -latter. So the answer is that we think it's better to show the -warning. - -Often people write `ON_CALL`s in the mock object's -constructor or `SetUp()`, as the default behavior rarely changes from -test to test. Then in the test body they set the expectations, which -are often different for each test. Having an `ON_CALL` in the set-up -part of a test doesn't mean that the calls are expected. If there's -no `EXPECT_CALL` and the method is called, it's possibly an error. If -we quietly let the call go through without notifying the user, bugs -may creep in unnoticed. - -If, however, you are sure that the calls are OK, you can write - -``` -EXPECT_CALL(foo, Bar(_)) - .WillRepeatedly(...); -``` - -instead of - -``` -ON_CALL(foo, Bar(_)) - .WillByDefault(...); -``` - -This tells Google Mock that you do expect the calls and no warning should be -printed. - -Also, you can control the verbosity using the `--gmock_verbose` flag. -If you find the output too noisy when debugging, just choose a less -verbose level. - -## How can I delete the mock function's argument in an action? ## - -If you find yourself needing to perform some action that's not -supported by Google Mock directly, remember that you can define your own -actions using -[MakeAction()](http://code.google.com/p/googlemock/wiki/V1_6_CookBook#Writing_New_Actions) or -[MakePolymorphicAction()](http://code.google.com/p/googlemock/wiki/V1_6_CookBook#Writing_New_Polymorphic_Actions), -or you can write a stub function and invoke it using -[Invoke()](http://code.google.com/p/googlemock/wiki/V1_6_CookBook#Using_Functions_Methods_Functors). - -## MOCK\_METHODn()'s second argument looks funny. Why don't you use the MOCK\_METHODn(Method, return\_type, arg\_1, ..., arg\_n) syntax? ## - -What?! I think it's beautiful. :-) - -While which syntax looks more natural is a subjective matter to some -extent, Google Mock's syntax was chosen for several practical advantages it -has. - -Try to mock a function that takes a map as an argument: -``` -virtual int GetSize(const map<int, std::string>& m); -``` - -Using the proposed syntax, it would be: -``` -MOCK_METHOD1(GetSize, int, const map<int, std::string>& m); -``` - -Guess what? You'll get a compiler error as the compiler thinks that -`const map<int, std::string>& m` are **two**, not one, arguments. To work -around this you can use `typedef` to give the map type a name, but -that gets in the way of your work. Google Mock's syntax avoids this -problem as the function's argument types are protected inside a pair -of parentheses: -``` -// This compiles fine. -MOCK_METHOD1(GetSize, int(const map<int, std::string>& m)); -``` - -You still need a `typedef` if the return type contains an unprotected -comma, but that's much rarer. - -Other advantages include: - 1. `MOCK_METHOD1(Foo, int, bool)` can leave a reader wonder whether the method returns `int` or `bool`, while there won't be such confusion using Google Mock's syntax. - 1. The way Google Mock describes a function type is nothing new, although many people may not be familiar with it. The same syntax was used in C, and the `function` library in `tr1` uses this syntax extensively. Since `tr1` will become a part of the new version of STL, we feel very comfortable to be consistent with it. - 1. The function type syntax is also used in other parts of Google Mock's API (e.g. the action interface) in order to make the implementation tractable. A user needs to learn it anyway in order to utilize Google Mock's more advanced features. We'd as well stick to the same syntax in `MOCK_METHOD*`! - -## My code calls a static/global function. Can I mock it? ## - -You can, but you need to make some changes. - -In general, if you find yourself needing to mock a static function, -it's a sign that your modules are too tightly coupled (and less -flexible, less reusable, less testable, etc). You are probably better -off defining a small interface and call the function through that -interface, which then can be easily mocked. It's a bit of work -initially, but usually pays for itself quickly. - -This Google Testing Blog -[post](http://googletesting.blogspot.com/2008/06/defeat-static-cling.html) -says it excellently. Check it out. - -## My mock object needs to do complex stuff. It's a lot of pain to specify the actions. Google Mock sucks! ## - -I know it's not a question, but you get an answer for free any way. :-) - -With Google Mock, you can create mocks in C++ easily. And people might be -tempted to use them everywhere. Sometimes they work great, and -sometimes you may find them, well, a pain to use. So, what's wrong in -the latter case? - -When you write a test without using mocks, you exercise the code and -assert that it returns the correct value or that the system is in an -expected state. This is sometimes called "state-based testing". - -Mocks are great for what some call "interaction-based" testing: -instead of checking the system state at the very end, mock objects -verify that they are invoked the right way and report an error as soon -as it arises, giving you a handle on the precise context in which the -error was triggered. This is often more effective and economical to -do than state-based testing. - -If you are doing state-based testing and using a test double just to -simulate the real object, you are probably better off using a fake. -Using a mock in this case causes pain, as it's not a strong point for -mocks to perform complex actions. If you experience this and think -that mocks suck, you are just not using the right tool for your -problem. Or, you might be trying to solve the wrong problem. :-) - -## I got a warning "Uninteresting function call encountered - default action taken.." Should I panic? ## - -By all means, NO! It's just an FYI. - -What it means is that you have a mock function, you haven't set any -expectations on it (by Google Mock's rule this means that you are not -interested in calls to this function and therefore it can be called -any number of times), and it is called. That's OK - you didn't say -it's not OK to call the function! - -What if you actually meant to disallow this function to be called, but -forgot to write `EXPECT_CALL(foo, Bar()).Times(0)`? While -one can argue that it's the user's fault, Google Mock tries to be nice and -prints you a note. - -So, when you see the message and believe that there shouldn't be any -uninteresting calls, you should investigate what's going on. To make -your life easier, Google Mock prints the function name and arguments -when an uninteresting call is encountered. - -## I want to define a custom action. Should I use Invoke() or implement the action interface? ## - -Either way is fine - you want to choose the one that's more convenient -for your circumstance. - -Usually, if your action is for a particular function type, defining it -using `Invoke()` should be easier; if your action can be used in -functions of different types (e.g. if you are defining -`Return(value)`), `MakePolymorphicAction()` is -easiest. Sometimes you want precise control on what types of -functions the action can be used in, and implementing -`ActionInterface` is the way to go here. See the implementation of -`Return()` in `include/gmock/gmock-actions.h` for an example. - -## I'm using the set-argument-pointee action, and the compiler complains about "conflicting return type specified". What does it mean? ## - -You got this error as Google Mock has no idea what value it should return -when the mock method is called. `SetArgPointee()` says what the -side effect is, but doesn't say what the return value should be. You -need `DoAll()` to chain a `SetArgPointee()` with a `Return()`. - -See this [recipe](http://code.google.com/p/googlemock/wiki/V1_6_CookBook#Mocking_Side_Effects) for more details and an example. - - -## My question is not in your FAQ! ## - -If you cannot find the answer to your question in this FAQ, there are -some other resources you can use: - - 1. read other [wiki pages](http://code.google.com/p/googlemock/w/list), - 1. search the mailing list [archive](http://groups.google.com/group/googlemock/topics), - 1. ask it on [googlemock@googlegroups.com](mailto:googlemock@googlegroups.com) and someone will answer it (to prevent spam, we require you to join the [discussion group](http://groups.google.com/group/googlemock) before you can post.). - -Please note that creating an issue in the -[issue tracker](http://code.google.com/p/googlemock/issues/list) is _not_ -a good way to get your answer, as it is monitored infrequently by a -very small number of people. - -When asking a question, it's helpful to provide as much of the -following information as possible (people cannot help you if there's -not enough information in your question): - - * the version (or the revision number if you check out from SVN directly) of Google Mock you use (Google Mock is under active development, so it's possible that your problem has been solved in a later version), - * your operating system, - * the name and version of your compiler, - * the complete command line flags you give to your compiler, - * the complete compiler error messages (if the question is about compilation), - * the _actual_ code (ideally, a minimal but complete program) that has the problem you encounter.
\ No newline at end of file diff --git a/googlemock/docs/v1_7/CheatSheet.md b/googlemock/docs/v1_7/CheatSheet.md deleted file mode 100644 index db421e5..0000000 --- a/googlemock/docs/v1_7/CheatSheet.md +++ /dev/null @@ -1,556 +0,0 @@ - - -# Defining a Mock Class # - -## Mocking a Normal Class ## - -Given -``` -class Foo { - ... - virtual ~Foo(); - virtual int GetSize() const = 0; - virtual string Describe(const char* name) = 0; - virtual string Describe(int type) = 0; - virtual bool Process(Bar elem, int count) = 0; -}; -``` -(note that `~Foo()` **must** be virtual) we can define its mock as -``` -#include "gmock/gmock.h" - -class MockFoo : public Foo { - MOCK_CONST_METHOD0(GetSize, int()); - MOCK_METHOD1(Describe, string(const char* name)); - MOCK_METHOD1(Describe, string(int type)); - MOCK_METHOD2(Process, bool(Bar elem, int count)); -}; -``` - -To create a "nice" mock object which ignores all uninteresting calls, -or a "strict" mock object, which treats them as failures: -``` -NiceMock<MockFoo> nice_foo; // The type is a subclass of MockFoo. -StrictMock<MockFoo> strict_foo; // The type is a subclass of MockFoo. -``` - -## Mocking a Class Template ## - -To mock -``` -template <typename Elem> -class StackInterface { - public: - ... - virtual ~StackInterface(); - virtual int GetSize() const = 0; - virtual void Push(const Elem& x) = 0; -}; -``` -(note that `~StackInterface()` **must** be virtual) just append `_T` to the `MOCK_*` macros: -``` -template <typename Elem> -class MockStack : public StackInterface<Elem> { - public: - ... - MOCK_CONST_METHOD0_T(GetSize, int()); - MOCK_METHOD1_T(Push, void(const Elem& x)); -}; -``` - -## Specifying Calling Conventions for Mock Functions ## - -If your mock function doesn't use the default calling convention, you -can specify it by appending `_WITH_CALLTYPE` to any of the macros -described in the previous two sections and supplying the calling -convention as the first argument to the macro. For example, -``` - MOCK_METHOD_1_WITH_CALLTYPE(STDMETHODCALLTYPE, Foo, bool(int n)); - MOCK_CONST_METHOD2_WITH_CALLTYPE(STDMETHODCALLTYPE, Bar, int(double x, double y)); -``` -where `STDMETHODCALLTYPE` is defined by `<objbase.h>` on Windows. - -# Using Mocks in Tests # - -The typical flow is: - 1. Import the Google Mock names you need to use. All Google Mock names are in the `testing` namespace unless they are macros or otherwise noted. - 1. Create the mock objects. - 1. Optionally, set the default actions of the mock objects. - 1. Set your expectations on the mock objects (How will they be called? What wil they do?). - 1. Exercise code that uses the mock objects; if necessary, check the result using [Google Test](http://code.google.com/p/googletest/) assertions. - 1. When a mock objects is destructed, Google Mock automatically verifies that all expectations on it have been satisfied. - -Here is an example: -``` -using ::testing::Return; // #1 - -TEST(BarTest, DoesThis) { - MockFoo foo; // #2 - - ON_CALL(foo, GetSize()) // #3 - .WillByDefault(Return(1)); - // ... other default actions ... - - EXPECT_CALL(foo, Describe(5)) // #4 - .Times(3) - .WillRepeatedly(Return("Category 5")); - // ... other expectations ... - - EXPECT_EQ("good", MyProductionFunction(&foo)); // #5 -} // #6 -``` - -# Setting Default Actions # - -Google Mock has a **built-in default action** for any function that -returns `void`, `bool`, a numeric value, or a pointer. - -To customize the default action for functions with return type `T` globally: -``` -using ::testing::DefaultValue; - -DefaultValue<T>::Set(value); // Sets the default value to be returned. -// ... use the mocks ... -DefaultValue<T>::Clear(); // Resets the default value. -``` - -To customize the default action for a particular method, use `ON_CALL()`: -``` -ON_CALL(mock_object, method(matchers)) - .With(multi_argument_matcher) ? - .WillByDefault(action); -``` - -# Setting Expectations # - -`EXPECT_CALL()` sets **expectations** on a mock method (How will it be -called? What will it do?): -``` -EXPECT_CALL(mock_object, method(matchers)) - .With(multi_argument_matcher) ? - .Times(cardinality) ? - .InSequence(sequences) * - .After(expectations) * - .WillOnce(action) * - .WillRepeatedly(action) ? - .RetiresOnSaturation(); ? -``` - -If `Times()` is omitted, the cardinality is assumed to be: - - * `Times(1)` when there is neither `WillOnce()` nor `WillRepeatedly()`; - * `Times(n)` when there are `n WillOnce()`s but no `WillRepeatedly()`, where `n` >= 1; or - * `Times(AtLeast(n))` when there are `n WillOnce()`s and a `WillRepeatedly()`, where `n` >= 0. - -A method with no `EXPECT_CALL()` is free to be invoked _any number of times_, and the default action will be taken each time. - -# Matchers # - -A **matcher** matches a _single_ argument. You can use it inside -`ON_CALL()` or `EXPECT_CALL()`, or use it to validate a value -directly: - -| `EXPECT_THAT(value, matcher)` | Asserts that `value` matches `matcher`. | -|:------------------------------|:----------------------------------------| -| `ASSERT_THAT(value, matcher)` | The same as `EXPECT_THAT(value, matcher)`, except that it generates a **fatal** failure. | - -Built-in matchers (where `argument` is the function argument) are -divided into several categories: - -## Wildcard ## -|`_`|`argument` can be any value of the correct type.| -|:--|:-----------------------------------------------| -|`A<type>()` or `An<type>()`|`argument` can be any value of type `type`. | - -## Generic Comparison ## - -|`Eq(value)` or `value`|`argument == value`| -|:---------------------|:------------------| -|`Ge(value)` |`argument >= value`| -|`Gt(value)` |`argument > value` | -|`Le(value)` |`argument <= value`| -|`Lt(value)` |`argument < value` | -|`Ne(value)` |`argument != value`| -|`IsNull()` |`argument` is a `NULL` pointer (raw or smart).| -|`NotNull()` |`argument` is a non-null pointer (raw or smart).| -|`Ref(variable)` |`argument` is a reference to `variable`.| -|`TypedEq<type>(value)`|`argument` has type `type` and is equal to `value`. You may need to use this instead of `Eq(value)` when the mock function is overloaded.| - -Except `Ref()`, these matchers make a _copy_ of `value` in case it's -modified or destructed later. If the compiler complains that `value` -doesn't have a public copy constructor, try wrap it in `ByRef()`, -e.g. `Eq(ByRef(non_copyable_value))`. If you do that, make sure -`non_copyable_value` is not changed afterwards, or the meaning of your -matcher will be changed. - -## Floating-Point Matchers ## - -|`DoubleEq(a_double)`|`argument` is a `double` value approximately equal to `a_double`, treating two NaNs as unequal.| -|:-------------------|:----------------------------------------------------------------------------------------------| -|`FloatEq(a_float)` |`argument` is a `float` value approximately equal to `a_float`, treating two NaNs as unequal. | -|`NanSensitiveDoubleEq(a_double)`|`argument` is a `double` value approximately equal to `a_double`, treating two NaNs as equal. | -|`NanSensitiveFloatEq(a_float)`|`argument` is a `float` value approximately equal to `a_float`, treating two NaNs as equal. | - -The above matchers use ULP-based comparison (the same as used in -[Google Test](http://code.google.com/p/googletest/)). They -automatically pick a reasonable error bound based on the absolute -value of the expected value. `DoubleEq()` and `FloatEq()` conform to -the IEEE standard, which requires comparing two NaNs for equality to -return false. The `NanSensitive*` version instead treats two NaNs as -equal, which is often what a user wants. - -|`DoubleNear(a_double, max_abs_error)`|`argument` is a `double` value close to `a_double` (absolute error <= `max_abs_error`), treating two NaNs as unequal.| -|:------------------------------------|:--------------------------------------------------------------------------------------------------------------------| -|`FloatNear(a_float, max_abs_error)` |`argument` is a `float` value close to `a_float` (absolute error <= `max_abs_error`), treating two NaNs as unequal. | -|`NanSensitiveDoubleNear(a_double, max_abs_error)`|`argument` is a `double` value close to `a_double` (absolute error <= `max_abs_error`), treating two NaNs as equal. | -|`NanSensitiveFloatNear(a_float, max_abs_error)`|`argument` is a `float` value close to `a_float` (absolute error <= `max_abs_error`), treating two NaNs as equal. | - -## String Matchers ## - -The `argument` can be either a C string or a C++ string object: - -|`ContainsRegex(string)`|`argument` matches the given regular expression.| -|:----------------------|:-----------------------------------------------| -|`EndsWith(suffix)` |`argument` ends with string `suffix`. | -|`HasSubstr(string)` |`argument` contains `string` as a sub-string. | -|`MatchesRegex(string)` |`argument` matches the given regular expression with the match starting at the first character and ending at the last character.| -|`StartsWith(prefix)` |`argument` starts with string `prefix`. | -|`StrCaseEq(string)` |`argument` is equal to `string`, ignoring case. | -|`StrCaseNe(string)` |`argument` is not equal to `string`, ignoring case.| -|`StrEq(string)` |`argument` is equal to `string`. | -|`StrNe(string)` |`argument` is not equal to `string`. | - -`ContainsRegex()` and `MatchesRegex()` use the regular expression -syntax defined -[here](http://code.google.com/p/googletest/wiki/AdvancedGuide#Regular_Expression_Syntax). -`StrCaseEq()`, `StrCaseNe()`, `StrEq()`, and `StrNe()` work for wide -strings as well. - -## Container Matchers ## - -Most STL-style containers support `==`, so you can use -`Eq(expected_container)` or simply `expected_container` to match a -container exactly. If you want to write the elements in-line, -match them more flexibly, or get more informative messages, you can use: - -| `ContainerEq(container)` | The same as `Eq(container)` except that the failure message also includes which elements are in one container but not the other. | -|:-------------------------|:---------------------------------------------------------------------------------------------------------------------------------| -| `Contains(e)` | `argument` contains an element that matches `e`, which can be either a value or a matcher. | -| `Each(e)` | `argument` is a container where _every_ element matches `e`, which can be either a value or a matcher. | -| `ElementsAre(e0, e1, ..., en)` | `argument` has `n + 1` elements, where the i-th element matches `ei`, which can be a value or a matcher. 0 to 10 arguments are allowed. | -| `ElementsAreArray({ e0, e1, ..., en })`, `ElementsAreArray(array)`, or `ElementsAreArray(array, count)` | The same as `ElementsAre()` except that the expected element values/matchers come from an initializer list, vector, or C-style array. | -| `IsEmpty()` | `argument` is an empty container (`container.empty()`). | -| `Pointwise(m, container)` | `argument` contains the same number of elements as in `container`, and for all i, (the i-th element in `argument`, the i-th element in `container`) match `m`, which is a matcher on 2-tuples. E.g. `Pointwise(Le(), upper_bounds)` verifies that each element in `argument` doesn't exceed the corresponding element in `upper_bounds`. See more detail below. | -| `SizeIs(m)` | `argument` is a container whose size matches `m`. E.g. `SizeIs(2)` or `SizeIs(Lt(2))`. | -| `UnorderedElementsAre(e0, e1, ..., en)` | `argument` has `n + 1` elements, and under some permutation each element matches an `ei` (for a different `i`), which can be a value or a matcher. 0 to 10 arguments are allowed. | -| `UnorderedElementsAreArray({ e0, e1, ..., en })`, `UnorderedElementsAreArray(array)`, or `UnorderedElementsAreArray(array, count)` | The same as `UnorderedElementsAre()` except that the expected element values/matchers come from an initializer list, vector, or C-style array. | -| `WhenSorted(m)` | When `argument` is sorted using the `<` operator, it matches container matcher `m`. E.g. `WhenSorted(UnorderedElementsAre(1, 2, 3))` verifies that `argument` contains elements `1`, `2`, and `3`, ignoring order. | -| `WhenSortedBy(comparator, m)` | The same as `WhenSorted(m)`, except that the given comparator instead of `<` is used to sort `argument`. E.g. `WhenSortedBy(std::greater<int>(), ElementsAre(3, 2, 1))`. | - -Notes: - - * These matchers can also match: - 1. a native array passed by reference (e.g. in `Foo(const int (&a)[5])`), and - 1. an array passed as a pointer and a count (e.g. in `Bar(const T* buffer, int len)` -- see [Multi-argument Matchers](#Multiargument_Matchers.md)). - * The array being matched may be multi-dimensional (i.e. its elements can be arrays). - * `m` in `Pointwise(m, ...)` should be a matcher for `std::tr1::tuple<T, U>` where `T` and `U` are the element type of the actual container and the expected container, respectively. For example, to compare two `Foo` containers where `Foo` doesn't support `operator==` but has an `Equals()` method, one might write: - -``` -using ::std::tr1::get; -MATCHER(FooEq, "") { - return get<0>(arg).Equals(get<1>(arg)); -} -... -EXPECT_THAT(actual_foos, Pointwise(FooEq(), expected_foos)); -``` - -## Member Matchers ## - -|`Field(&class::field, m)`|`argument.field` (or `argument->field` when `argument` is a plain pointer) matches matcher `m`, where `argument` is an object of type _class_.| -|:------------------------|:---------------------------------------------------------------------------------------------------------------------------------------------| -|`Key(e)` |`argument.first` matches `e`, which can be either a value or a matcher. E.g. `Contains(Key(Le(5)))` can verify that a `map` contains a key `<= 5`.| -|`Pair(m1, m2)` |`argument` is an `std::pair` whose `first` field matches `m1` and `second` field matches `m2`. | -|`Property(&class::property, m)`|`argument.property()` (or `argument->property()` when `argument` is a plain pointer) matches matcher `m`, where `argument` is an object of type _class_.| - -## Matching the Result of a Function or Functor ## - -|`ResultOf(f, m)`|`f(argument)` matches matcher `m`, where `f` is a function or functor.| -|:---------------|:---------------------------------------------------------------------| - -## Pointer Matchers ## - -|`Pointee(m)`|`argument` (either a smart pointer or a raw pointer) points to a value that matches matcher `m`.| -|:-----------|:-----------------------------------------------------------------------------------------------| - -## Multiargument Matchers ## - -Technically, all matchers match a _single_ value. A "multi-argument" -matcher is just one that matches a _tuple_. The following matchers can -be used to match a tuple `(x, y)`: - -|`Eq()`|`x == y`| -|:-----|:-------| -|`Ge()`|`x >= y`| -|`Gt()`|`x > y` | -|`Le()`|`x <= y`| -|`Lt()`|`x < y` | -|`Ne()`|`x != y`| - -You can use the following selectors to pick a subset of the arguments -(or reorder them) to participate in the matching: - -|`AllArgs(m)`|Equivalent to `m`. Useful as syntactic sugar in `.With(AllArgs(m))`.| -|:-----------|:-------------------------------------------------------------------| -|`Args<N1, N2, ..., Nk>(m)`|The tuple of the `k` selected (using 0-based indices) arguments matches `m`, e.g. `Args<1, 2>(Eq())`.| - -## Composite Matchers ## - -You can make a matcher from one or more other matchers: - -|`AllOf(m1, m2, ..., mn)`|`argument` matches all of the matchers `m1` to `mn`.| -|:-----------------------|:---------------------------------------------------| -|`AnyOf(m1, m2, ..., mn)`|`argument` matches at least one of the matchers `m1` to `mn`.| -|`Not(m)` |`argument` doesn't match matcher `m`. | - -## Adapters for Matchers ## - -|`MatcherCast<T>(m)`|casts matcher `m` to type `Matcher<T>`.| -|:------------------|:--------------------------------------| -|`SafeMatcherCast<T>(m)`| [safely casts](http://code.google.com/p/googlemock/wiki/V1_7_CookBook#Casting_Matchers) matcher `m` to type `Matcher<T>`. | -|`Truly(predicate)` |`predicate(argument)` returns something considered by C++ to be true, where `predicate` is a function or functor.| - -## Matchers as Predicates ## - -|`Matches(m)(value)`|evaluates to `true` if `value` matches `m`. You can use `Matches(m)` alone as a unary functor.| -|:------------------|:---------------------------------------------------------------------------------------------| -|`ExplainMatchResult(m, value, result_listener)`|evaluates to `true` if `value` matches `m`, explaining the result to `result_listener`. | -|`Value(value, m)` |evaluates to `true` if `value` matches `m`. | - -## Defining Matchers ## - -| `MATCHER(IsEven, "") { return (arg % 2) == 0; }` | Defines a matcher `IsEven()` to match an even number. | -|:-------------------------------------------------|:------------------------------------------------------| -| `MATCHER_P(IsDivisibleBy, n, "") { *result_listener << "where the remainder is " << (arg % n); return (arg % n) == 0; }` | Defines a macher `IsDivisibleBy(n)` to match a number divisible by `n`. | -| `MATCHER_P2(IsBetween, a, b, std::string(negation ? "isn't" : "is") + " between " + PrintToString(a) + " and " + PrintToString(b)) { return a <= arg && arg <= b; }` | Defines a matcher `IsBetween(a, b)` to match a value in the range [`a`, `b`]. | - -**Notes:** - - 1. The `MATCHER*` macros cannot be used inside a function or class. - 1. The matcher body must be _purely functional_ (i.e. it cannot have any side effect, and the result must not depend on anything other than the value being matched and the matcher parameters). - 1. You can use `PrintToString(x)` to convert a value `x` of any type to a string. - -## Matchers as Test Assertions ## - -|`ASSERT_THAT(expression, m)`|Generates a [fatal failure](http://code.google.com/p/googletest/wiki/Primer#Assertions) if the value of `expression` doesn't match matcher `m`.| -|:---------------------------|:----------------------------------------------------------------------------------------------------------------------------------------------| -|`EXPECT_THAT(expression, m)`|Generates a non-fatal failure if the value of `expression` doesn't match matcher `m`. | - -# Actions # - -**Actions** specify what a mock function should do when invoked. - -## Returning a Value ## - -|`Return()`|Return from a `void` mock function.| -|:---------|:----------------------------------| -|`Return(value)`|Return `value`. If the type of `value` is different to the mock function's return type, `value` is converted to the latter type <i>at the time the expectation is set</i>, not when the action is executed.| -|`ReturnArg<N>()`|Return the `N`-th (0-based) argument.| -|`ReturnNew<T>(a1, ..., ak)`|Return `new T(a1, ..., ak)`; a different object is created each time.| -|`ReturnNull()`|Return a null pointer. | -|`ReturnPointee(ptr)`|Return the value pointed to by `ptr`.| -|`ReturnRef(variable)`|Return a reference to `variable`. | -|`ReturnRefOfCopy(value)`|Return a reference to a copy of `value`; the copy lives as long as the action.| - -## Side Effects ## - -|`Assign(&variable, value)`|Assign `value` to variable.| -|:-------------------------|:--------------------------| -| `DeleteArg<N>()` | Delete the `N`-th (0-based) argument, which must be a pointer. | -| `SaveArg<N>(pointer)` | Save the `N`-th (0-based) argument to `*pointer`. | -| `SaveArgPointee<N>(pointer)` | Save the value pointed to by the `N`-th (0-based) argument to `*pointer`. | -| `SetArgReferee<N>(value)` | Assign value to the variable referenced by the `N`-th (0-based) argument. | -|`SetArgPointee<N>(value)` |Assign `value` to the variable pointed by the `N`-th (0-based) argument.| -|`SetArgumentPointee<N>(value)`|Same as `SetArgPointee<N>(value)`. Deprecated. Will be removed in v1.7.0.| -|`SetArrayArgument<N>(first, last)`|Copies the elements in source range [`first`, `last`) to the array pointed to by the `N`-th (0-based) argument, which can be either a pointer or an iterator. The action does not take ownership of the elements in the source range.| -|`SetErrnoAndReturn(error, value)`|Set `errno` to `error` and return `value`.| -|`Throw(exception)` |Throws the given exception, which can be any copyable value. Available since v1.1.0.| - -## Using a Function or a Functor as an Action ## - -|`Invoke(f)`|Invoke `f` with the arguments passed to the mock function, where `f` can be a global/static function or a functor.| -|:----------|:-----------------------------------------------------------------------------------------------------------------| -|`Invoke(object_pointer, &class::method)`|Invoke the {method on the object with the arguments passed to the mock function. | -|`InvokeWithoutArgs(f)`|Invoke `f`, which can be a global/static function or a functor. `f` must take no arguments. | -|`InvokeWithoutArgs(object_pointer, &class::method)`|Invoke the method on the object, which takes no arguments. | -|`InvokeArgument<N>(arg1, arg2, ..., argk)`|Invoke the mock function's `N`-th (0-based) argument, which must be a function or a functor, with the `k` arguments.| - -The return value of the invoked function is used as the return value -of the action. - -When defining a function or functor to be used with `Invoke*()`, you can declare any unused parameters as `Unused`: -``` - double Distance(Unused, double x, double y) { return sqrt(x*x + y*y); } - ... - EXPECT_CALL(mock, Foo("Hi", _, _)).WillOnce(Invoke(Distance)); -``` - -In `InvokeArgument<N>(...)`, if an argument needs to be passed by reference, wrap it inside `ByRef()`. For example, -``` - InvokeArgument<2>(5, string("Hi"), ByRef(foo)) -``` -calls the mock function's #2 argument, passing to it `5` and `string("Hi")` by value, and `foo` by reference. - -## Default Action ## - -|`DoDefault()`|Do the default action (specified by `ON_CALL()` or the built-in one).| -|:------------|:--------------------------------------------------------------------| - -**Note:** due to technical reasons, `DoDefault()` cannot be used inside a composite action - trying to do so will result in a run-time error. - -## Composite Actions ## - -|`DoAll(a1, a2, ..., an)`|Do all actions `a1` to `an` and return the result of `an` in each invocation. The first `n - 1` sub-actions must return void. | -|:-----------------------|:-----------------------------------------------------------------------------------------------------------------------------| -|`IgnoreResult(a)` |Perform action `a` and ignore its result. `a` must not return void. | -|`WithArg<N>(a)` |Pass the `N`-th (0-based) argument of the mock function to action `a` and perform it. | -|`WithArgs<N1, N2, ..., Nk>(a)`|Pass the selected (0-based) arguments of the mock function to action `a` and perform it. | -|`WithoutArgs(a)` |Perform action `a` without any arguments. | - -## Defining Actions ## - -| `ACTION(Sum) { return arg0 + arg1; }` | Defines an action `Sum()` to return the sum of the mock function's argument #0 and #1. | -|:--------------------------------------|:---------------------------------------------------------------------------------------| -| `ACTION_P(Plus, n) { return arg0 + n; }` | Defines an action `Plus(n)` to return the sum of the mock function's argument #0 and `n`. | -| `ACTION_Pk(Foo, p1, ..., pk) { statements; }` | Defines a parameterized action `Foo(p1, ..., pk)` to execute the given `statements`. | - -The `ACTION*` macros cannot be used inside a function or class. - -# Cardinalities # - -These are used in `Times()` to specify how many times a mock function will be called: - -|`AnyNumber()`|The function can be called any number of times.| -|:------------|:----------------------------------------------| -|`AtLeast(n)` |The call is expected at least `n` times. | -|`AtMost(n)` |The call is expected at most `n` times. | -|`Between(m, n)`|The call is expected between `m` and `n` (inclusive) times.| -|`Exactly(n) or n`|The call is expected exactly `n` times. In particular, the call should never happen when `n` is 0.| - -# Expectation Order # - -By default, the expectations can be matched in _any_ order. If some -or all expectations must be matched in a given order, there are two -ways to specify it. They can be used either independently or -together. - -## The After Clause ## - -``` -using ::testing::Expectation; -... -Expectation init_x = EXPECT_CALL(foo, InitX()); -Expectation init_y = EXPECT_CALL(foo, InitY()); -EXPECT_CALL(foo, Bar()) - .After(init_x, init_y); -``` -says that `Bar()` can be called only after both `InitX()` and -`InitY()` have been called. - -If you don't know how many pre-requisites an expectation has when you -write it, you can use an `ExpectationSet` to collect them: - -``` -using ::testing::ExpectationSet; -... -ExpectationSet all_inits; -for (int i = 0; i < element_count; i++) { - all_inits += EXPECT_CALL(foo, InitElement(i)); -} -EXPECT_CALL(foo, Bar()) - .After(all_inits); -``` -says that `Bar()` can be called only after all elements have been -initialized (but we don't care about which elements get initialized -before the others). - -Modifying an `ExpectationSet` after using it in an `.After()` doesn't -affect the meaning of the `.After()`. - -## Sequences ## - -When you have a long chain of sequential expectations, it's easier to -specify the order using **sequences**, which don't require you to given -each expectation in the chain a different name. <i>All expected<br> -calls</i> in the same sequence must occur in the order they are -specified. - -``` -using ::testing::Sequence; -Sequence s1, s2; -... -EXPECT_CALL(foo, Reset()) - .InSequence(s1, s2) - .WillOnce(Return(true)); -EXPECT_CALL(foo, GetSize()) - .InSequence(s1) - .WillOnce(Return(1)); -EXPECT_CALL(foo, Describe(A<const char*>())) - .InSequence(s2) - .WillOnce(Return("dummy")); -``` -says that `Reset()` must be called before _both_ `GetSize()` _and_ -`Describe()`, and the latter two can occur in any order. - -To put many expectations in a sequence conveniently: -``` -using ::testing::InSequence; -{ - InSequence dummy; - - EXPECT_CALL(...)...; - EXPECT_CALL(...)...; - ... - EXPECT_CALL(...)...; -} -``` -says that all expected calls in the scope of `dummy` must occur in -strict order. The name `dummy` is irrelevant.) - -# Verifying and Resetting a Mock # - -Google Mock will verify the expectations on a mock object when it is destructed, or you can do it earlier: -``` -using ::testing::Mock; -... -// Verifies and removes the expectations on mock_obj; -// returns true iff successful. -Mock::VerifyAndClearExpectations(&mock_obj); -... -// Verifies and removes the expectations on mock_obj; -// also removes the default actions set by ON_CALL(); -// returns true iff successful. -Mock::VerifyAndClear(&mock_obj); -``` - -You can also tell Google Mock that a mock object can be leaked and doesn't -need to be verified: -``` -Mock::AllowLeak(&mock_obj); -``` - -# Mock Classes # - -Google Mock defines a convenient mock class template -``` -class MockFunction<R(A1, ..., An)> { - public: - MOCK_METHODn(Call, R(A1, ..., An)); -}; -``` -See this [recipe](http://code.google.com/p/googlemock/wiki/V1_7_CookBook#Using_Check_Points) for one application of it. - -# Flags # - -| `--gmock_catch_leaked_mocks=0` | Don't report leaked mock objects as failures. | -|:-------------------------------|:----------------------------------------------| -| `--gmock_verbose=LEVEL` | Sets the default verbosity level (`info`, `warning`, or `error`) of Google Mock messages. |
\ No newline at end of file diff --git a/googlemock/docs/v1_7/CookBook.md b/googlemock/docs/v1_7/CookBook.md deleted file mode 100644 index 419a001..0000000 --- a/googlemock/docs/v1_7/CookBook.md +++ /dev/null @@ -1,3432 +0,0 @@ - - -You can find recipes for using Google Mock here. If you haven't yet, -please read the [ForDummies](V1_7_ForDummies.md) document first to make sure you understand -the basics. - -**Note:** Google Mock lives in the `testing` name space. For -readability, it is recommended to write `using ::testing::Foo;` once in -your file before using the name `Foo` defined by Google Mock. We omit -such `using` statements in this page for brevity, but you should do it -in your own code. - -# Creating Mock Classes # - -## Mocking Private or Protected Methods ## - -You must always put a mock method definition (`MOCK_METHOD*`) in a -`public:` section of the mock class, regardless of the method being -mocked being `public`, `protected`, or `private` in the base class. -This allows `ON_CALL` and `EXPECT_CALL` to reference the mock function -from outside of the mock class. (Yes, C++ allows a subclass to change -the access level of a virtual function in the base class.) Example: - -``` -class Foo { - public: - ... - virtual bool Transform(Gadget* g) = 0; - - protected: - virtual void Resume(); - - private: - virtual int GetTimeOut(); -}; - -class MockFoo : public Foo { - public: - ... - MOCK_METHOD1(Transform, bool(Gadget* g)); - - // The following must be in the public section, even though the - // methods are protected or private in the base class. - MOCK_METHOD0(Resume, void()); - MOCK_METHOD0(GetTimeOut, int()); -}; -``` - -## Mocking Overloaded Methods ## - -You can mock overloaded functions as usual. No special attention is required: - -``` -class Foo { - ... - - // Must be virtual as we'll inherit from Foo. - virtual ~Foo(); - - // Overloaded on the types and/or numbers of arguments. - virtual int Add(Element x); - virtual int Add(int times, Element x); - - // Overloaded on the const-ness of this object. - virtual Bar& GetBar(); - virtual const Bar& GetBar() const; -}; - -class MockFoo : public Foo { - ... - MOCK_METHOD1(Add, int(Element x)); - MOCK_METHOD2(Add, int(int times, Element x); - - MOCK_METHOD0(GetBar, Bar&()); - MOCK_CONST_METHOD0(GetBar, const Bar&()); -}; -``` - -**Note:** if you don't mock all versions of the overloaded method, the -compiler will give you a warning about some methods in the base class -being hidden. To fix that, use `using` to bring them in scope: - -``` -class MockFoo : public Foo { - ... - using Foo::Add; - MOCK_METHOD1(Add, int(Element x)); - // We don't want to mock int Add(int times, Element x); - ... -}; -``` - -## Mocking Class Templates ## - -To mock a class template, append `_T` to the `MOCK_*` macros: - -``` -template <typename Elem> -class StackInterface { - ... - // Must be virtual as we'll inherit from StackInterface. - virtual ~StackInterface(); - - virtual int GetSize() const = 0; - virtual void Push(const Elem& x) = 0; -}; - -template <typename Elem> -class MockStack : public StackInterface<Elem> { - ... - MOCK_CONST_METHOD0_T(GetSize, int()); - MOCK_METHOD1_T(Push, void(const Elem& x)); -}; -``` - -## Mocking Nonvirtual Methods ## - -Google Mock can mock non-virtual functions to be used in what we call _hi-perf -dependency injection_. - -In this case, instead of sharing a common base class with the real -class, your mock class will be _unrelated_ to the real class, but -contain methods with the same signatures. The syntax for mocking -non-virtual methods is the _same_ as mocking virtual methods: - -``` -// A simple packet stream class. None of its members is virtual. -class ConcretePacketStream { - public: - void AppendPacket(Packet* new_packet); - const Packet* GetPacket(size_t packet_number) const; - size_t NumberOfPackets() const; - ... -}; - -// A mock packet stream class. It inherits from no other, but defines -// GetPacket() and NumberOfPackets(). -class MockPacketStream { - public: - MOCK_CONST_METHOD1(GetPacket, const Packet*(size_t packet_number)); - MOCK_CONST_METHOD0(NumberOfPackets, size_t()); - ... -}; -``` - -Note that the mock class doesn't define `AppendPacket()`, unlike the -real class. That's fine as long as the test doesn't need to call it. - -Next, you need a way to say that you want to use -`ConcretePacketStream` in production code, and use `MockPacketStream` -in tests. Since the functions are not virtual and the two classes are -unrelated, you must specify your choice at _compile time_ (as opposed -to run time). - -One way to do it is to templatize your code that needs to use a packet -stream. More specifically, you will give your code a template type -argument for the type of the packet stream. In production, you will -instantiate your template with `ConcretePacketStream` as the type -argument. In tests, you will instantiate the same template with -`MockPacketStream`. For example, you may write: - -``` -template <class PacketStream> -void CreateConnection(PacketStream* stream) { ... } - -template <class PacketStream> -class PacketReader { - public: - void ReadPackets(PacketStream* stream, size_t packet_num); -}; -``` - -Then you can use `CreateConnection<ConcretePacketStream>()` and -`PacketReader<ConcretePacketStream>` in production code, and use -`CreateConnection<MockPacketStream>()` and -`PacketReader<MockPacketStream>` in tests. - -``` - MockPacketStream mock_stream; - EXPECT_CALL(mock_stream, ...)...; - .. set more expectations on mock_stream ... - PacketReader<MockPacketStream> reader(&mock_stream); - ... exercise reader ... -``` - -## Mocking Free Functions ## - -It's possible to use Google Mock to mock a free function (i.e. a -C-style function or a static method). You just need to rewrite your -code to use an interface (abstract class). - -Instead of calling a free function (say, `OpenFile`) directly, -introduce an interface for it and have a concrete subclass that calls -the free function: - -``` -class FileInterface { - public: - ... - virtual bool Open(const char* path, const char* mode) = 0; -}; - -class File : public FileInterface { - public: - ... - virtual bool Open(const char* path, const char* mode) { - return OpenFile(path, mode); - } -}; -``` - -Your code should talk to `FileInterface` to open a file. Now it's -easy to mock out the function. - -This may seem much hassle, but in practice you often have multiple -related functions that you can put in the same interface, so the -per-function syntactic overhead will be much lower. - -If you are concerned about the performance overhead incurred by -virtual functions, and profiling confirms your concern, you can -combine this with the recipe for [mocking non-virtual methods](#Mocking_Nonvirtual_Methods.md). - -## The Nice, the Strict, and the Naggy ## - -If a mock method has no `EXPECT_CALL` spec but is called, Google Mock -will print a warning about the "uninteresting call". The rationale is: - - * New methods may be added to an interface after a test is written. We shouldn't fail a test just because a method it doesn't know about is called. - * However, this may also mean there's a bug in the test, so Google Mock shouldn't be silent either. If the user believes these calls are harmless, he can add an `EXPECT_CALL()` to suppress the warning. - -However, sometimes you may want to suppress all "uninteresting call" -warnings, while sometimes you may want the opposite, i.e. to treat all -of them as errors. Google Mock lets you make the decision on a -per-mock-object basis. - -Suppose your test uses a mock class `MockFoo`: - -``` -TEST(...) { - MockFoo mock_foo; - EXPECT_CALL(mock_foo, DoThis()); - ... code that uses mock_foo ... -} -``` - -If a method of `mock_foo` other than `DoThis()` is called, it will be -reported by Google Mock as a warning. However, if you rewrite your -test to use `NiceMock<MockFoo>` instead, the warning will be gone, -resulting in a cleaner test output: - -``` -using ::testing::NiceMock; - -TEST(...) { - NiceMock<MockFoo> mock_foo; - EXPECT_CALL(mock_foo, DoThis()); - ... code that uses mock_foo ... -} -``` - -`NiceMock<MockFoo>` is a subclass of `MockFoo`, so it can be used -wherever `MockFoo` is accepted. - -It also works if `MockFoo`'s constructor takes some arguments, as -`NiceMock<MockFoo>` "inherits" `MockFoo`'s constructors: - -``` -using ::testing::NiceMock; - -TEST(...) { - NiceMock<MockFoo> mock_foo(5, "hi"); // Calls MockFoo(5, "hi"). - EXPECT_CALL(mock_foo, DoThis()); - ... code that uses mock_foo ... -} -``` - -The usage of `StrictMock` is similar, except that it makes all -uninteresting calls failures: - -``` -using ::testing::StrictMock; - -TEST(...) { - StrictMock<MockFoo> mock_foo; - EXPECT_CALL(mock_foo, DoThis()); - ... code that uses mock_foo ... - - // The test will fail if a method of mock_foo other than DoThis() - // is called. -} -``` - -There are some caveats though (I don't like them just as much as the -next guy, but sadly they are side effects of C++'s limitations): - - 1. `NiceMock<MockFoo>` and `StrictMock<MockFoo>` only work for mock methods defined using the `MOCK_METHOD*` family of macros **directly** in the `MockFoo` class. If a mock method is defined in a **base class** of `MockFoo`, the "nice" or "strict" modifier may not affect it, depending on the compiler. In particular, nesting `NiceMock` and `StrictMock` (e.g. `NiceMock<StrictMock<MockFoo> >`) is **not** supported. - 1. The constructors of the base mock (`MockFoo`) cannot have arguments passed by non-const reference, which happens to be banned by the [Google C++ style guide](http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml). - 1. During the constructor or destructor of `MockFoo`, the mock object is _not_ nice or strict. This may cause surprises if the constructor or destructor calls a mock method on `this` object. (This behavior, however, is consistent with C++'s general rule: if a constructor or destructor calls a virtual method of `this` object, that method is treated as non-virtual. In other words, to the base class's constructor or destructor, `this` object behaves like an instance of the base class, not the derived class. This rule is required for safety. Otherwise a base constructor may use members of a derived class before they are initialized, or a base destructor may use members of a derived class after they have been destroyed.) - -Finally, you should be **very cautious** about when to use naggy or strict mocks, as they tend to make tests more brittle and harder to maintain. When you refactor your code without changing its externally visible behavior, ideally you should't need to update any tests. If your code interacts with a naggy mock, however, you may start to get spammed with warnings as the result of your change. Worse, if your code interacts with a strict mock, your tests may start to fail and you'll be forced to fix them. Our general recommendation is to use nice mocks (not yet the default) most of the time, use naggy mocks (the current default) when developing or debugging tests, and use strict mocks only as the last resort. - -## Simplifying the Interface without Breaking Existing Code ## - -Sometimes a method has a long list of arguments that is mostly -uninteresting. For example, - -``` -class LogSink { - public: - ... - virtual void send(LogSeverity severity, const char* full_filename, - const char* base_filename, int line, - const struct tm* tm_time, - const char* message, size_t message_len) = 0; -}; -``` - -This method's argument list is lengthy and hard to work with (let's -say that the `message` argument is not even 0-terminated). If we mock -it as is, using the mock will be awkward. If, however, we try to -simplify this interface, we'll need to fix all clients depending on -it, which is often infeasible. - -The trick is to re-dispatch the method in the mock class: - -``` -class ScopedMockLog : public LogSink { - public: - ... - virtual void send(LogSeverity severity, const char* full_filename, - const char* base_filename, int line, const tm* tm_time, - const char* message, size_t message_len) { - // We are only interested in the log severity, full file name, and - // log message. - Log(severity, full_filename, std::string(message, message_len)); - } - - // Implements the mock method: - // - // void Log(LogSeverity severity, - // const string& file_path, - // const string& message); - MOCK_METHOD3(Log, void(LogSeverity severity, const string& file_path, - const string& message)); -}; -``` - -By defining a new mock method with a trimmed argument list, we make -the mock class much more user-friendly. - -## Alternative to Mocking Concrete Classes ## - -Often you may find yourself using classes that don't implement -interfaces. In order to test your code that uses such a class (let's -call it `Concrete`), you may be tempted to make the methods of -`Concrete` virtual and then mock it. - -Try not to do that. - -Making a non-virtual function virtual is a big decision. It creates an -extension point where subclasses can tweak your class' behavior. This -weakens your control on the class because now it's harder to maintain -the class' invariants. You should make a function virtual only when -there is a valid reason for a subclass to override it. - -Mocking concrete classes directly is problematic as it creates a tight -coupling between the class and the tests - any small change in the -class may invalidate your tests and make test maintenance a pain. - -To avoid such problems, many programmers have been practicing "coding -to interfaces": instead of talking to the `Concrete` class, your code -would define an interface and talk to it. Then you implement that -interface as an adaptor on top of `Concrete`. In tests, you can easily -mock that interface to observe how your code is doing. - -This technique incurs some overhead: - - * You pay the cost of virtual function calls (usually not a problem). - * There is more abstraction for the programmers to learn. - -However, it can also bring significant benefits in addition to better -testability: - - * `Concrete`'s API may not fit your problem domain very well, as you may not be the only client it tries to serve. By designing your own interface, you have a chance to tailor it to your need - you may add higher-level functionalities, rename stuff, etc instead of just trimming the class. This allows you to write your code (user of the interface) in a more natural way, which means it will be more readable, more maintainable, and you'll be more productive. - * If `Concrete`'s implementation ever has to change, you don't have to rewrite everywhere it is used. Instead, you can absorb the change in your implementation of the interface, and your other code and tests will be insulated from this change. - -Some people worry that if everyone is practicing this technique, they -will end up writing lots of redundant code. This concern is totally -understandable. However, there are two reasons why it may not be the -case: - - * Different projects may need to use `Concrete` in different ways, so the best interfaces for them will be different. Therefore, each of them will have its own domain-specific interface on top of `Concrete`, and they will not be the same code. - * If enough projects want to use the same interface, they can always share it, just like they have been sharing `Concrete`. You can check in the interface and the adaptor somewhere near `Concrete` (perhaps in a `contrib` sub-directory) and let many projects use it. - -You need to weigh the pros and cons carefully for your particular -problem, but I'd like to assure you that the Java community has been -practicing this for a long time and it's a proven effective technique -applicable in a wide variety of situations. :-) - -## Delegating Calls to a Fake ## - -Some times you have a non-trivial fake implementation of an -interface. For example: - -``` -class Foo { - public: - virtual ~Foo() {} - virtual char DoThis(int n) = 0; - virtual void DoThat(const char* s, int* p) = 0; -}; - -class FakeFoo : public Foo { - public: - virtual char DoThis(int n) { - return (n > 0) ? '+' : - (n < 0) ? '-' : '0'; - } - - virtual void DoThat(const char* s, int* p) { - *p = strlen(s); - } -}; -``` - -Now you want to mock this interface such that you can set expectations -on it. However, you also want to use `FakeFoo` for the default -behavior, as duplicating it in the mock object is, well, a lot of -work. - -When you define the mock class using Google Mock, you can have it -delegate its default action to a fake class you already have, using -this pattern: - -``` -using ::testing::_; -using ::testing::Invoke; - -class MockFoo : public Foo { - public: - // Normal mock method definitions using Google Mock. - MOCK_METHOD1(DoThis, char(int n)); - MOCK_METHOD2(DoThat, void(const char* s, int* p)); - - // Delegates the default actions of the methods to a FakeFoo object. - // This must be called *before* the custom ON_CALL() statements. - void DelegateToFake() { - ON_CALL(*this, DoThis(_)) - .WillByDefault(Invoke(&fake_, &FakeFoo::DoThis)); - ON_CALL(*this, DoThat(_, _)) - .WillByDefault(Invoke(&fake_, &FakeFoo::DoThat)); - } - private: - FakeFoo fake_; // Keeps an instance of the fake in the mock. -}; -``` - -With that, you can use `MockFoo` in your tests as usual. Just remember -that if you don't explicitly set an action in an `ON_CALL()` or -`EXPECT_CALL()`, the fake will be called upon to do it: - -``` -using ::testing::_; - -TEST(AbcTest, Xyz) { - MockFoo foo; - foo.DelegateToFake(); // Enables the fake for delegation. - - // Put your ON_CALL(foo, ...)s here, if any. - - // No action specified, meaning to use the default action. - EXPECT_CALL(foo, DoThis(5)); - EXPECT_CALL(foo, DoThat(_, _)); - - int n = 0; - EXPECT_EQ('+', foo.DoThis(5)); // FakeFoo::DoThis() is invoked. - foo.DoThat("Hi", &n); // FakeFoo::DoThat() is invoked. - EXPECT_EQ(2, n); -} -``` - -**Some tips:** - - * If you want, you can still override the default action by providing your own `ON_CALL()` or using `.WillOnce()` / `.WillRepeatedly()` in `EXPECT_CALL()`. - * In `DelegateToFake()`, you only need to delegate the methods whose fake implementation you intend to use. - * The general technique discussed here works for overloaded methods, but you'll need to tell the compiler which version you mean. To disambiguate a mock function (the one you specify inside the parentheses of `ON_CALL()`), see the "Selecting Between Overloaded Functions" section on this page; to disambiguate a fake function (the one you place inside `Invoke()`), use a `static_cast` to specify the function's type. For instance, if class `Foo` has methods `char DoThis(int n)` and `bool DoThis(double x) const`, and you want to invoke the latter, you need to write `Invoke(&fake_, static_cast<bool (FakeFoo::*)(double) const>(&FakeFoo::DoThis))` instead of `Invoke(&fake_, &FakeFoo::DoThis)` (The strange-looking thing inside the angled brackets of `static_cast` is the type of a function pointer to the second `DoThis()` method.). - * Having to mix a mock and a fake is often a sign of something gone wrong. Perhaps you haven't got used to the interaction-based way of testing yet. Or perhaps your interface is taking on too many roles and should be split up. Therefore, **don't abuse this**. We would only recommend to do it as an intermediate step when you are refactoring your code. - -Regarding the tip on mixing a mock and a fake, here's an example on -why it may be a bad sign: Suppose you have a class `System` for -low-level system operations. In particular, it does file and I/O -operations. And suppose you want to test how your code uses `System` -to do I/O, and you just want the file operations to work normally. If -you mock out the entire `System` class, you'll have to provide a fake -implementation for the file operation part, which suggests that -`System` is taking on too many roles. - -Instead, you can define a `FileOps` interface and an `IOOps` interface -and split `System`'s functionalities into the two. Then you can mock -`IOOps` without mocking `FileOps`. - -## Delegating Calls to a Real Object ## - -When using testing doubles (mocks, fakes, stubs, and etc), sometimes -their behaviors will differ from those of the real objects. This -difference could be either intentional (as in simulating an error such -that you can test the error handling code) or unintentional. If your -mocks have different behaviors than the real objects by mistake, you -could end up with code that passes the tests but fails in production. - -You can use the _delegating-to-real_ technique to ensure that your -mock has the same behavior as the real object while retaining the -ability to validate calls. This technique is very similar to the -delegating-to-fake technique, the difference being that we use a real -object instead of a fake. Here's an example: - -``` -using ::testing::_; -using ::testing::AtLeast; -using ::testing::Invoke; - -class MockFoo : public Foo { - public: - MockFoo() { - // By default, all calls are delegated to the real object. - ON_CALL(*this, DoThis()) - .WillByDefault(Invoke(&real_, &Foo::DoThis)); - ON_CALL(*this, DoThat(_)) - .WillByDefault(Invoke(&real_, &Foo::DoThat)); - ... - } - MOCK_METHOD0(DoThis, ...); - MOCK_METHOD1(DoThat, ...); - ... - private: - Foo real_; -}; -... - - MockFoo mock; - - EXPECT_CALL(mock, DoThis()) - .Times(3); - EXPECT_CALL(mock, DoThat("Hi")) - .Times(AtLeast(1)); - ... use mock in test ... -``` - -With this, Google Mock will verify that your code made the right calls -(with the right arguments, in the right order, called the right number -of times, etc), and a real object will answer the calls (so the -behavior will be the same as in production). This gives you the best -of both worlds. - -## Delegating Calls to a Parent Class ## - -Ideally, you should code to interfaces, whose methods are all pure -virtual. In reality, sometimes you do need to mock a virtual method -that is not pure (i.e, it already has an implementation). For example: - -``` -class Foo { - public: - virtual ~Foo(); - - virtual void Pure(int n) = 0; - virtual int Concrete(const char* str) { ... } -}; - -class MockFoo : public Foo { - public: - // Mocking a pure method. - MOCK_METHOD1(Pure, void(int n)); - // Mocking a concrete method. Foo::Concrete() is shadowed. - MOCK_METHOD1(Concrete, int(const char* str)); -}; -``` - -Sometimes you may want to call `Foo::Concrete()` instead of -`MockFoo::Concrete()`. Perhaps you want to do it as part of a stub -action, or perhaps your test doesn't need to mock `Concrete()` at all -(but it would be oh-so painful to have to define a new mock class -whenever you don't need to mock one of its methods). - -The trick is to leave a back door in your mock class for accessing the -real methods in the base class: - -``` -class MockFoo : public Foo { - public: - // Mocking a pure method. - MOCK_METHOD1(Pure, void(int n)); - // Mocking a concrete method. Foo::Concrete() is shadowed. - MOCK_METHOD1(Concrete, int(const char* str)); - - // Use this to call Concrete() defined in Foo. - int FooConcrete(const char* str) { return Foo::Concrete(str); } -}; -``` - -Now, you can call `Foo::Concrete()` inside an action by: - -``` -using ::testing::_; -using ::testing::Invoke; -... - EXPECT_CALL(foo, Concrete(_)) - .WillOnce(Invoke(&foo, &MockFoo::FooConcrete)); -``` - -or tell the mock object that you don't want to mock `Concrete()`: - -``` -using ::testing::Invoke; -... - ON_CALL(foo, Concrete(_)) - .WillByDefault(Invoke(&foo, &MockFoo::FooConcrete)); -``` - -(Why don't we just write `Invoke(&foo, &Foo::Concrete)`? If you do -that, `MockFoo::Concrete()` will be called (and cause an infinite -recursion) since `Foo::Concrete()` is virtual. That's just how C++ -works.) - -# Using Matchers # - -## Matching Argument Values Exactly ## - -You can specify exactly which arguments a mock method is expecting: - -``` -using ::testing::Return; -... - EXPECT_CALL(foo, DoThis(5)) - .WillOnce(Return('a')); - EXPECT_CALL(foo, DoThat("Hello", bar)); -``` - -## Using Simple Matchers ## - -You can use matchers to match arguments that have a certain property: - -``` -using ::testing::Ge; -using ::testing::NotNull; -using ::testing::Return; -... - EXPECT_CALL(foo, DoThis(Ge(5))) // The argument must be >= 5. - .WillOnce(Return('a')); - EXPECT_CALL(foo, DoThat("Hello", NotNull())); - // The second argument must not be NULL. -``` - -A frequently used matcher is `_`, which matches anything: - -``` -using ::testing::_; -using ::testing::NotNull; -... - EXPECT_CALL(foo, DoThat(_, NotNull())); -``` - -## Combining Matchers ## - -You can build complex matchers from existing ones using `AllOf()`, -`AnyOf()`, and `Not()`: - -``` -using ::testing::AllOf; -using ::testing::Gt; -using ::testing::HasSubstr; -using ::testing::Ne; -using ::testing::Not; -... - // The argument must be > 5 and != 10. - EXPECT_CALL(foo, DoThis(AllOf(Gt(5), - Ne(10)))); - - // The first argument must not contain sub-string "blah". - EXPECT_CALL(foo, DoThat(Not(HasSubstr("blah")), - NULL)); -``` - -## Casting Matchers ## - -Google Mock matchers are statically typed, meaning that the compiler -can catch your mistake if you use a matcher of the wrong type (for -example, if you use `Eq(5)` to match a `string` argument). Good for -you! - -Sometimes, however, you know what you're doing and want the compiler -to give you some slack. One example is that you have a matcher for -`long` and the argument you want to match is `int`. While the two -types aren't exactly the same, there is nothing really wrong with -using a `Matcher<long>` to match an `int` - after all, we can first -convert the `int` argument to a `long` before giving it to the -matcher. - -To support this need, Google Mock gives you the -`SafeMatcherCast<T>(m)` function. It casts a matcher `m` to type -`Matcher<T>`. To ensure safety, Google Mock checks that (let `U` be the -type `m` accepts): - - 1. Type `T` can be implicitly cast to type `U`; - 1. When both `T` and `U` are built-in arithmetic types (`bool`, integers, and floating-point numbers), the conversion from `T` to `U` is not lossy (in other words, any value representable by `T` can also be represented by `U`); and - 1. When `U` is a reference, `T` must also be a reference (as the underlying matcher may be interested in the address of the `U` value). - -The code won't compile if any of these conditions isn't met. - -Here's one example: - -``` -using ::testing::SafeMatcherCast; - -// A base class and a child class. -class Base { ... }; -class Derived : public Base { ... }; - -class MockFoo : public Foo { - public: - MOCK_METHOD1(DoThis, void(Derived* derived)); -}; -... - - MockFoo foo; - // m is a Matcher<Base*> we got from somewhere. - EXPECT_CALL(foo, DoThis(SafeMatcherCast<Derived*>(m))); -``` - -If you find `SafeMatcherCast<T>(m)` too limiting, you can use a similar -function `MatcherCast<T>(m)`. The difference is that `MatcherCast` works -as long as you can `static_cast` type `T` to type `U`. - -`MatcherCast` essentially lets you bypass C++'s type system -(`static_cast` isn't always safe as it could throw away information, -for example), so be careful not to misuse/abuse it. - -## Selecting Between Overloaded Functions ## - -If you expect an overloaded function to be called, the compiler may -need some help on which overloaded version it is. - -To disambiguate functions overloaded on the const-ness of this object, -use the `Const()` argument wrapper. - -``` -using ::testing::ReturnRef; - -class MockFoo : public Foo { - ... - MOCK_METHOD0(GetBar, Bar&()); - MOCK_CONST_METHOD0(GetBar, const Bar&()); -}; -... - - MockFoo foo; - Bar bar1, bar2; - EXPECT_CALL(foo, GetBar()) // The non-const GetBar(). - .WillOnce(ReturnRef(bar1)); - EXPECT_CALL(Const(foo), GetBar()) // The const GetBar(). - .WillOnce(ReturnRef(bar2)); -``` - -(`Const()` is defined by Google Mock and returns a `const` reference -to its argument.) - -To disambiguate overloaded functions with the same number of arguments -but different argument types, you may need to specify the exact type -of a matcher, either by wrapping your matcher in `Matcher<type>()`, or -using a matcher whose type is fixed (`TypedEq<type>`, `An<type>()`, -etc): - -``` -using ::testing::An; -using ::testing::Lt; -using ::testing::Matcher; -using ::testing::TypedEq; - -class MockPrinter : public Printer { - public: - MOCK_METHOD1(Print, void(int n)); - MOCK_METHOD1(Print, void(char c)); -}; - -TEST(PrinterTest, Print) { - MockPrinter printer; - - EXPECT_CALL(printer, Print(An<int>())); // void Print(int); - EXPECT_CALL(printer, Print(Matcher<int>(Lt(5)))); // void Print(int); - EXPECT_CALL(printer, Print(TypedEq<char>('a'))); // void Print(char); - - printer.Print(3); - printer.Print(6); - printer.Print('a'); -} -``` - -## Performing Different Actions Based on the Arguments ## - -When a mock method is called, the _last_ matching expectation that's -still active will be selected (think "newer overrides older"). So, you -can make a method do different things depending on its argument values -like this: - -``` -using ::testing::_; -using ::testing::Lt; -using ::testing::Return; -... - // The default case. - EXPECT_CALL(foo, DoThis(_)) - .WillRepeatedly(Return('b')); - - // The more specific case. - EXPECT_CALL(foo, DoThis(Lt(5))) - .WillRepeatedly(Return('a')); -``` - -Now, if `foo.DoThis()` is called with a value less than 5, `'a'` will -be returned; otherwise `'b'` will be returned. - -## Matching Multiple Arguments as a Whole ## - -Sometimes it's not enough to match the arguments individually. For -example, we may want to say that the first argument must be less than -the second argument. The `With()` clause allows us to match -all arguments of a mock function as a whole. For example, - -``` -using ::testing::_; -using ::testing::Lt; -using ::testing::Ne; -... - EXPECT_CALL(foo, InRange(Ne(0), _)) - .With(Lt()); -``` - -says that the first argument of `InRange()` must not be 0, and must be -less than the second argument. - -The expression inside `With()` must be a matcher of type -`Matcher<tr1::tuple<A1, ..., An> >`, where `A1`, ..., `An` are the -types of the function arguments. - -You can also write `AllArgs(m)` instead of `m` inside `.With()`. The -two forms are equivalent, but `.With(AllArgs(Lt()))` is more readable -than `.With(Lt())`. - -You can use `Args<k1, ..., kn>(m)` to match the `n` selected arguments -(as a tuple) against `m`. For example, - -``` -using ::testing::_; -using ::testing::AllOf; -using ::testing::Args; -using ::testing::Lt; -... - EXPECT_CALL(foo, Blah(_, _, _)) - .With(AllOf(Args<0, 1>(Lt()), Args<1, 2>(Lt()))); -``` - -says that `Blah()` will be called with arguments `x`, `y`, and `z` where -`x < y < z`. - -As a convenience and example, Google Mock provides some matchers for -2-tuples, including the `Lt()` matcher above. See the [CheatSheet](V1_7_CheatSheet.md) for -the complete list. - -Note that if you want to pass the arguments to a predicate of your own -(e.g. `.With(Args<0, 1>(Truly(&MyPredicate)))`), that predicate MUST be -written to take a `tr1::tuple` as its argument; Google Mock will pass the `n` -selected arguments as _one_ single tuple to the predicate. - -## Using Matchers as Predicates ## - -Have you noticed that a matcher is just a fancy predicate that also -knows how to describe itself? Many existing algorithms take predicates -as arguments (e.g. those defined in STL's `<algorithm>` header), and -it would be a shame if Google Mock matchers are not allowed to -participate. - -Luckily, you can use a matcher where a unary predicate functor is -expected by wrapping it inside the `Matches()` function. For example, - -``` -#include <algorithm> -#include <vector> - -std::vector<int> v; -... -// How many elements in v are >= 10? -const int count = count_if(v.begin(), v.end(), Matches(Ge(10))); -``` - -Since you can build complex matchers from simpler ones easily using -Google Mock, this gives you a way to conveniently construct composite -predicates (doing the same using STL's `<functional>` header is just -painful). For example, here's a predicate that's satisfied by any -number that is >= 0, <= 100, and != 50: - -``` -Matches(AllOf(Ge(0), Le(100), Ne(50))) -``` - -## Using Matchers in Google Test Assertions ## - -Since matchers are basically predicates that also know how to describe -themselves, there is a way to take advantage of them in -[Google Test](http://code.google.com/p/googletest/) assertions. It's -called `ASSERT_THAT` and `EXPECT_THAT`: - -``` - ASSERT_THAT(value, matcher); // Asserts that value matches matcher. - EXPECT_THAT(value, matcher); // The non-fatal version. -``` - -For example, in a Google Test test you can write: - -``` -#include "gmock/gmock.h" - -using ::testing::AllOf; -using ::testing::Ge; -using ::testing::Le; -using ::testing::MatchesRegex; -using ::testing::StartsWith; -... - - EXPECT_THAT(Foo(), StartsWith("Hello")); - EXPECT_THAT(Bar(), MatchesRegex("Line \\d+")); - ASSERT_THAT(Baz(), AllOf(Ge(5), Le(10))); -``` - -which (as you can probably guess) executes `Foo()`, `Bar()`, and -`Baz()`, and verifies that: - - * `Foo()` returns a string that starts with `"Hello"`. - * `Bar()` returns a string that matches regular expression `"Line \\d+"`. - * `Baz()` returns a number in the range [5, 10]. - -The nice thing about these macros is that _they read like -English_. They generate informative messages too. For example, if the -first `EXPECT_THAT()` above fails, the message will be something like: - -``` -Value of: Foo() - Actual: "Hi, world!" -Expected: starts with "Hello" -``` - -**Credit:** The idea of `(ASSERT|EXPECT)_THAT` was stolen from the -[Hamcrest](http://code.google.com/p/hamcrest/) project, which adds -`assertThat()` to JUnit. - -## Using Predicates as Matchers ## - -Google Mock provides a built-in set of matchers. In case you find them -lacking, you can use an arbitray unary predicate function or functor -as a matcher - as long as the predicate accepts a value of the type -you want. You do this by wrapping the predicate inside the `Truly()` -function, for example: - -``` -using ::testing::Truly; - -int IsEven(int n) { return (n % 2) == 0 ? 1 : 0; } -... - - // Bar() must be called with an even number. - EXPECT_CALL(foo, Bar(Truly(IsEven))); -``` - -Note that the predicate function / functor doesn't have to return -`bool`. It works as long as the return value can be used as the -condition in statement `if (condition) ...`. - -## Matching Arguments that Are Not Copyable ## - -When you do an `EXPECT_CALL(mock_obj, Foo(bar))`, Google Mock saves -away a copy of `bar`. When `Foo()` is called later, Google Mock -compares the argument to `Foo()` with the saved copy of `bar`. This -way, you don't need to worry about `bar` being modified or destroyed -after the `EXPECT_CALL()` is executed. The same is true when you use -matchers like `Eq(bar)`, `Le(bar)`, and so on. - -But what if `bar` cannot be copied (i.e. has no copy constructor)? You -could define your own matcher function and use it with `Truly()`, as -the previous couple of recipes have shown. Or, you may be able to get -away from it if you can guarantee that `bar` won't be changed after -the `EXPECT_CALL()` is executed. Just tell Google Mock that it should -save a reference to `bar`, instead of a copy of it. Here's how: - -``` -using ::testing::Eq; -using ::testing::ByRef; -using ::testing::Lt; -... - // Expects that Foo()'s argument == bar. - EXPECT_CALL(mock_obj, Foo(Eq(ByRef(bar)))); - - // Expects that Foo()'s argument < bar. - EXPECT_CALL(mock_obj, Foo(Lt(ByRef(bar)))); -``` - -Remember: if you do this, don't change `bar` after the -`EXPECT_CALL()`, or the result is undefined. - -## Validating a Member of an Object ## - -Often a mock function takes a reference to object as an argument. When -matching the argument, you may not want to compare the entire object -against a fixed object, as that may be over-specification. Instead, -you may need to validate a certain member variable or the result of a -certain getter method of the object. You can do this with `Field()` -and `Property()`. More specifically, - -``` -Field(&Foo::bar, m) -``` - -is a matcher that matches a `Foo` object whose `bar` member variable -satisfies matcher `m`. - -``` -Property(&Foo::baz, m) -``` - -is a matcher that matches a `Foo` object whose `baz()` method returns -a value that satisfies matcher `m`. - -For example: - -> | `Field(&Foo::number, Ge(3))` | Matches `x` where `x.number >= 3`. | -|:-----------------------------|:-----------------------------------| -> | `Property(&Foo::name, StartsWith("John "))` | Matches `x` where `x.name()` starts with `"John "`. | - -Note that in `Property(&Foo::baz, ...)`, method `baz()` must take no -argument and be declared as `const`. - -BTW, `Field()` and `Property()` can also match plain pointers to -objects. For instance, - -``` -Field(&Foo::number, Ge(3)) -``` - -matches a plain pointer `p` where `p->number >= 3`. If `p` is `NULL`, -the match will always fail regardless of the inner matcher. - -What if you want to validate more than one members at the same time? -Remember that there is `AllOf()`. - -## Validating the Value Pointed to by a Pointer Argument ## - -C++ functions often take pointers as arguments. You can use matchers -like `IsNull()`, `NotNull()`, and other comparison matchers to match a -pointer, but what if you want to make sure the value _pointed to_ by -the pointer, instead of the pointer itself, has a certain property? -Well, you can use the `Pointee(m)` matcher. - -`Pointee(m)` matches a pointer iff `m` matches the value the pointer -points to. For example: - -``` -using ::testing::Ge; -using ::testing::Pointee; -... - EXPECT_CALL(foo, Bar(Pointee(Ge(3)))); -``` - -expects `foo.Bar()` to be called with a pointer that points to a value -greater than or equal to 3. - -One nice thing about `Pointee()` is that it treats a `NULL` pointer as -a match failure, so you can write `Pointee(m)` instead of - -``` - AllOf(NotNull(), Pointee(m)) -``` - -without worrying that a `NULL` pointer will crash your test. - -Also, did we tell you that `Pointee()` works with both raw pointers -**and** smart pointers (`linked_ptr`, `shared_ptr`, `scoped_ptr`, and -etc)? - -What if you have a pointer to pointer? You guessed it - you can use -nested `Pointee()` to probe deeper inside the value. For example, -`Pointee(Pointee(Lt(3)))` matches a pointer that points to a pointer -that points to a number less than 3 (what a mouthful...). - -## Testing a Certain Property of an Object ## - -Sometimes you want to specify that an object argument has a certain -property, but there is no existing matcher that does this. If you want -good error messages, you should define a matcher. If you want to do it -quick and dirty, you could get away with writing an ordinary function. - -Let's say you have a mock function that takes an object of type `Foo`, -which has an `int bar()` method and an `int baz()` method, and you -want to constrain that the argument's `bar()` value plus its `baz()` -value is a given number. Here's how you can define a matcher to do it: - -``` -using ::testing::MatcherInterface; -using ::testing::MatchResultListener; - -class BarPlusBazEqMatcher : public MatcherInterface<const Foo&> { - public: - explicit BarPlusBazEqMatcher(int expected_sum) - : expected_sum_(expected_sum) {} - - virtual bool MatchAndExplain(const Foo& foo, - MatchResultListener* listener) const { - return (foo.bar() + foo.baz()) == expected_sum_; - } - - virtual void DescribeTo(::std::ostream* os) const { - *os << "bar() + baz() equals " << expected_sum_; - } - - virtual void DescribeNegationTo(::std::ostream* os) const { - *os << "bar() + baz() does not equal " << expected_sum_; - } - private: - const int expected_sum_; -}; - -inline Matcher<const Foo&> BarPlusBazEq(int expected_sum) { - return MakeMatcher(new BarPlusBazEqMatcher(expected_sum)); -} - -... - - EXPECT_CALL(..., DoThis(BarPlusBazEq(5)))...; -``` - -## Matching Containers ## - -Sometimes an STL container (e.g. list, vector, map, ...) is passed to -a mock function and you may want to validate it. Since most STL -containers support the `==` operator, you can write -`Eq(expected_container)` or simply `expected_container` to match a -container exactly. - -Sometimes, though, you may want to be more flexible (for example, the -first element must be an exact match, but the second element can be -any positive number, and so on). Also, containers used in tests often -have a small number of elements, and having to define the expected -container out-of-line is a bit of a hassle. - -You can use the `ElementsAre()` or `UnorderedElementsAre()` matcher in -such cases: - -``` -using ::testing::_; -using ::testing::ElementsAre; -using ::testing::Gt; -... - - MOCK_METHOD1(Foo, void(const vector<int>& numbers)); -... - - EXPECT_CALL(mock, Foo(ElementsAre(1, Gt(0), _, 5))); -``` - -The above matcher says that the container must have 4 elements, which -must be 1, greater than 0, anything, and 5 respectively. - -If you instead write: - -``` -using ::testing::_; -using ::testing::Gt; -using ::testing::UnorderedElementsAre; -... - - MOCK_METHOD1(Foo, void(const vector<int>& numbers)); -... - - EXPECT_CALL(mock, Foo(UnorderedElementsAre(1, Gt(0), _, 5))); -``` - -It means that the container must have 4 elements, which under some -permutation must be 1, greater than 0, anything, and 5 respectively. - -`ElementsAre()` and `UnorderedElementsAre()` are overloaded to take 0 -to 10 arguments. If more are needed, you can place them in a C-style -array and use `ElementsAreArray()` or `UnorderedElementsAreArray()` -instead: - -``` -using ::testing::ElementsAreArray; -... - - // ElementsAreArray accepts an array of element values. - const int expected_vector1[] = { 1, 5, 2, 4, ... }; - EXPECT_CALL(mock, Foo(ElementsAreArray(expected_vector1))); - - // Or, an array of element matchers. - Matcher<int> expected_vector2 = { 1, Gt(2), _, 3, ... }; - EXPECT_CALL(mock, Foo(ElementsAreArray(expected_vector2))); -``` - -In case the array needs to be dynamically created (and therefore the -array size cannot be inferred by the compiler), you can give -`ElementsAreArray()` an additional argument to specify the array size: - -``` -using ::testing::ElementsAreArray; -... - int* const expected_vector3 = new int[count]; - ... fill expected_vector3 with values ... - EXPECT_CALL(mock, Foo(ElementsAreArray(expected_vector3, count))); -``` - -**Tips:** - - * `ElementsAre*()` can be used to match _any_ container that implements the STL iterator pattern (i.e. it has a `const_iterator` type and supports `begin()/end()`), not just the ones defined in STL. It will even work with container types yet to be written - as long as they follows the above pattern. - * You can use nested `ElementsAre*()` to match nested (multi-dimensional) containers. - * If the container is passed by pointer instead of by reference, just write `Pointee(ElementsAre*(...))`. - * The order of elements _matters_ for `ElementsAre*()`. Therefore don't use it with containers whose element order is undefined (e.g. `hash_map`). - -## Sharing Matchers ## - -Under the hood, a Google Mock matcher object consists of a pointer to -a ref-counted implementation object. Copying matchers is allowed and -very efficient, as only the pointer is copied. When the last matcher -that references the implementation object dies, the implementation -object will be deleted. - -Therefore, if you have some complex matcher that you want to use again -and again, there is no need to build it everytime. Just assign it to a -matcher variable and use that variable repeatedly! For example, - -``` - Matcher<int> in_range = AllOf(Gt(5), Le(10)); - ... use in_range as a matcher in multiple EXPECT_CALLs ... -``` - -# Setting Expectations # - -## Knowing When to Expect ## - -`ON_CALL` is likely the single most under-utilized construct in Google Mock. - -There are basically two constructs for defining the behavior of a mock object: `ON_CALL` and `EXPECT_CALL`. The difference? `ON_CALL` defines what happens when a mock method is called, but _doesn't imply any expectation on the method being called._ `EXPECT_CALL` not only defines the behavior, but also sets an expectation that _the method will be called with the given arguments, for the given number of times_ (and _in the given order_ when you specify the order too). - -Since `EXPECT_CALL` does more, isn't it better than `ON_CALL`? Not really. Every `EXPECT_CALL` adds a constraint on the behavior of the code under test. Having more constraints than necessary is _baaad_ - even worse than not having enough constraints. - -This may be counter-intuitive. How could tests that verify more be worse than tests that verify less? Isn't verification the whole point of tests? - -The answer, lies in _what_ a test should verify. **A good test verifies the contract of the code.** If a test over-specifies, it doesn't leave enough freedom to the implementation. As a result, changing the implementation without breaking the contract (e.g. refactoring and optimization), which should be perfectly fine to do, can break such tests. Then you have to spend time fixing them, only to see them broken again the next time the implementation is changed. - -Keep in mind that one doesn't have to verify more than one property in one test. In fact, **it's a good style to verify only one thing in one test.** If you do that, a bug will likely break only one or two tests instead of dozens (which case would you rather debug?). If you are also in the habit of giving tests descriptive names that tell what they verify, you can often easily guess what's wrong just from the test log itself. - -So use `ON_CALL` by default, and only use `EXPECT_CALL` when you actually intend to verify that the call is made. For example, you may have a bunch of `ON_CALL`s in your test fixture to set the common mock behavior shared by all tests in the same group, and write (scarcely) different `EXPECT_CALL`s in different `TEST_F`s to verify different aspects of the code's behavior. Compared with the style where each `TEST` has many `EXPECT_CALL`s, this leads to tests that are more resilient to implementational changes (and thus less likely to require maintenance) and makes the intent of the tests more obvious (so they are easier to maintain when you do need to maintain them). - -## Ignoring Uninteresting Calls ## - -If you are not interested in how a mock method is called, just don't -say anything about it. In this case, if the method is ever called, -Google Mock will perform its default action to allow the test program -to continue. If you are not happy with the default action taken by -Google Mock, you can override it using `DefaultValue<T>::Set()` -(described later in this document) or `ON_CALL()`. - -Please note that once you expressed interest in a particular mock -method (via `EXPECT_CALL()`), all invocations to it must match some -expectation. If this function is called but the arguments don't match -any `EXPECT_CALL()` statement, it will be an error. - -## Disallowing Unexpected Calls ## - -If a mock method shouldn't be called at all, explicitly say so: - -``` -using ::testing::_; -... - EXPECT_CALL(foo, Bar(_)) - .Times(0); -``` - -If some calls to the method are allowed, but the rest are not, just -list all the expected calls: - -``` -using ::testing::AnyNumber; -using ::testing::Gt; -... - EXPECT_CALL(foo, Bar(5)); - EXPECT_CALL(foo, Bar(Gt(10))) - .Times(AnyNumber()); -``` - -A call to `foo.Bar()` that doesn't match any of the `EXPECT_CALL()` -statements will be an error. - -## Expecting Ordered Calls ## - -Although an `EXPECT_CALL()` statement defined earlier takes precedence -when Google Mock tries to match a function call with an expectation, -by default calls don't have to happen in the order `EXPECT_CALL()` -statements are written. For example, if the arguments match the -matchers in the third `EXPECT_CALL()`, but not those in the first two, -then the third expectation will be used. - -If you would rather have all calls occur in the order of the -expectations, put the `EXPECT_CALL()` statements in a block where you -define a variable of type `InSequence`: - -``` - using ::testing::_; - using ::testing::InSequence; - - { - InSequence s; - - EXPECT_CALL(foo, DoThis(5)); - EXPECT_CALL(bar, DoThat(_)) - .Times(2); - EXPECT_CALL(foo, DoThis(6)); - } -``` - -In this example, we expect a call to `foo.DoThis(5)`, followed by two -calls to `bar.DoThat()` where the argument can be anything, which are -in turn followed by a call to `foo.DoThis(6)`. If a call occurred -out-of-order, Google Mock will report an error. - -## Expecting Partially Ordered Calls ## - -Sometimes requiring everything to occur in a predetermined order can -lead to brittle tests. For example, we may care about `A` occurring -before both `B` and `C`, but aren't interested in the relative order -of `B` and `C`. In this case, the test should reflect our real intent, -instead of being overly constraining. - -Google Mock allows you to impose an arbitrary DAG (directed acyclic -graph) on the calls. One way to express the DAG is to use the -[After](http://code.google.com/p/googlemock/wiki/V1_7_CheatSheet#The_After_Clause) clause of `EXPECT_CALL`. - -Another way is via the `InSequence()` clause (not the same as the -`InSequence` class), which we borrowed from jMock 2. It's less -flexible than `After()`, but more convenient when you have long chains -of sequential calls, as it doesn't require you to come up with -different names for the expectations in the chains. Here's how it -works: - -If we view `EXPECT_CALL()` statements as nodes in a graph, and add an -edge from node A to node B wherever A must occur before B, we can get -a DAG. We use the term "sequence" to mean a directed path in this -DAG. Now, if we decompose the DAG into sequences, we just need to know -which sequences each `EXPECT_CALL()` belongs to in order to be able to -reconstruct the orginal DAG. - -So, to specify the partial order on the expectations we need to do two -things: first to define some `Sequence` objects, and then for each -`EXPECT_CALL()` say which `Sequence` objects it is part -of. Expectations in the same sequence must occur in the order they are -written. For example, - -``` - using ::testing::Sequence; - - Sequence s1, s2; - - EXPECT_CALL(foo, A()) - .InSequence(s1, s2); - EXPECT_CALL(bar, B()) - .InSequence(s1); - EXPECT_CALL(bar, C()) - .InSequence(s2); - EXPECT_CALL(foo, D()) - .InSequence(s2); -``` - -specifies the following DAG (where `s1` is `A -> B`, and `s2` is `A -> -C -> D`): - -``` - +---> B - | - A ---| - | - +---> C ---> D -``` - -This means that A must occur before B and C, and C must occur before -D. There's no restriction about the order other than these. - -## Controlling When an Expectation Retires ## - -When a mock method is called, Google Mock only consider expectations -that are still active. An expectation is active when created, and -becomes inactive (aka _retires_) when a call that has to occur later -has occurred. For example, in - -``` - using ::testing::_; - using ::testing::Sequence; - - Sequence s1, s2; - - EXPECT_CALL(log, Log(WARNING, _, "File too large.")) // #1 - .Times(AnyNumber()) - .InSequence(s1, s2); - EXPECT_CALL(log, Log(WARNING, _, "Data set is empty.")) // #2 - .InSequence(s1); - EXPECT_CALL(log, Log(WARNING, _, "User not found.")) // #3 - .InSequence(s2); -``` - -as soon as either #2 or #3 is matched, #1 will retire. If a warning -`"File too large."` is logged after this, it will be an error. - -Note that an expectation doesn't retire automatically when it's -saturated. For example, - -``` -using ::testing::_; -... - EXPECT_CALL(log, Log(WARNING, _, _)); // #1 - EXPECT_CALL(log, Log(WARNING, _, "File too large.")); // #2 -``` - -says that there will be exactly one warning with the message `"File -too large."`. If the second warning contains this message too, #2 will -match again and result in an upper-bound-violated error. - -If this is not what you want, you can ask an expectation to retire as -soon as it becomes saturated: - -``` -using ::testing::_; -... - EXPECT_CALL(log, Log(WARNING, _, _)); // #1 - EXPECT_CALL(log, Log(WARNING, _, "File too large.")) // #2 - .RetiresOnSaturation(); -``` - -Here #2 can be used only once, so if you have two warnings with the -message `"File too large."`, the first will match #2 and the second -will match #1 - there will be no error. - -# Using Actions # - -## Returning References from Mock Methods ## - -If a mock function's return type is a reference, you need to use -`ReturnRef()` instead of `Return()` to return a result: - -``` -using ::testing::ReturnRef; - -class MockFoo : public Foo { - public: - MOCK_METHOD0(GetBar, Bar&()); -}; -... - - MockFoo foo; - Bar bar; - EXPECT_CALL(foo, GetBar()) - .WillOnce(ReturnRef(bar)); -``` - -## Returning Live Values from Mock Methods ## - -The `Return(x)` action saves a copy of `x` when the action is -_created_, and always returns the same value whenever it's -executed. Sometimes you may want to instead return the _live_ value of -`x` (i.e. its value at the time when the action is _executed_.). - -If the mock function's return type is a reference, you can do it using -`ReturnRef(x)`, as shown in the previous recipe ("Returning References -from Mock Methods"). However, Google Mock doesn't let you use -`ReturnRef()` in a mock function whose return type is not a reference, -as doing that usually indicates a user error. So, what shall you do? - -You may be tempted to try `ByRef()`: - -``` -using testing::ByRef; -using testing::Return; - -class MockFoo : public Foo { - public: - MOCK_METHOD0(GetValue, int()); -}; -... - int x = 0; - MockFoo foo; - EXPECT_CALL(foo, GetValue()) - .WillRepeatedly(Return(ByRef(x))); - x = 42; - EXPECT_EQ(42, foo.GetValue()); -``` - -Unfortunately, it doesn't work here. The above code will fail with error: - -``` -Value of: foo.GetValue() - Actual: 0 -Expected: 42 -``` - -The reason is that `Return(value)` converts `value` to the actual -return type of the mock function at the time when the action is -_created_, not when it is _executed_. (This behavior was chosen for -the action to be safe when `value` is a proxy object that references -some temporary objects.) As a result, `ByRef(x)` is converted to an -`int` value (instead of a `const int&`) when the expectation is set, -and `Return(ByRef(x))` will always return 0. - -`ReturnPointee(pointer)` was provided to solve this problem -specifically. It returns the value pointed to by `pointer` at the time -the action is _executed_: - -``` -using testing::ReturnPointee; -... - int x = 0; - MockFoo foo; - EXPECT_CALL(foo, GetValue()) - .WillRepeatedly(ReturnPointee(&x)); // Note the & here. - x = 42; - EXPECT_EQ(42, foo.GetValue()); // This will succeed now. -``` - -## Combining Actions ## - -Want to do more than one thing when a function is called? That's -fine. `DoAll()` allow you to do sequence of actions every time. Only -the return value of the last action in the sequence will be used. - -``` -using ::testing::DoAll; - -class MockFoo : public Foo { - public: - MOCK_METHOD1(Bar, bool(int n)); -}; -... - - EXPECT_CALL(foo, Bar(_)) - .WillOnce(DoAll(action_1, - action_2, - ... - action_n)); -``` - -## Mocking Side Effects ## - -Sometimes a method exhibits its effect not via returning a value but -via side effects. For example, it may change some global state or -modify an output argument. To mock side effects, in general you can -define your own action by implementing `::testing::ActionInterface`. - -If all you need to do is to change an output argument, the built-in -`SetArgPointee()` action is convenient: - -``` -using ::testing::SetArgPointee; - -class MockMutator : public Mutator { - public: - MOCK_METHOD2(Mutate, void(bool mutate, int* value)); - ... -}; -... - - MockMutator mutator; - EXPECT_CALL(mutator, Mutate(true, _)) - .WillOnce(SetArgPointee<1>(5)); -``` - -In this example, when `mutator.Mutate()` is called, we will assign 5 -to the `int` variable pointed to by argument #1 -(0-based). - -`SetArgPointee()` conveniently makes an internal copy of the -value you pass to it, removing the need to keep the value in scope and -alive. The implication however is that the value must have a copy -constructor and assignment operator. - -If the mock method also needs to return a value as well, you can chain -`SetArgPointee()` with `Return()` using `DoAll()`: - -``` -using ::testing::_; -using ::testing::Return; -using ::testing::SetArgPointee; - -class MockMutator : public Mutator { - public: - ... - MOCK_METHOD1(MutateInt, bool(int* value)); -}; -... - - MockMutator mutator; - EXPECT_CALL(mutator, MutateInt(_)) - .WillOnce(DoAll(SetArgPointee<0>(5), - Return(true))); -``` - -If the output argument is an array, use the -`SetArrayArgument<N>(first, last)` action instead. It copies the -elements in source range `[first, last)` to the array pointed to by -the `N`-th (0-based) argument: - -``` -using ::testing::NotNull; -using ::testing::SetArrayArgument; - -class MockArrayMutator : public ArrayMutator { - public: - MOCK_METHOD2(Mutate, void(int* values, int num_values)); - ... -}; -... - - MockArrayMutator mutator; - int values[5] = { 1, 2, 3, 4, 5 }; - EXPECT_CALL(mutator, Mutate(NotNull(), 5)) - .WillOnce(SetArrayArgument<0>(values, values + 5)); -``` - -This also works when the argument is an output iterator: - -``` -using ::testing::_; -using ::testing::SeArrayArgument; - -class MockRolodex : public Rolodex { - public: - MOCK_METHOD1(GetNames, void(std::back_insert_iterator<vector<string> >)); - ... -}; -... - - MockRolodex rolodex; - vector<string> names; - names.push_back("George"); - names.push_back("John"); - names.push_back("Thomas"); - EXPECT_CALL(rolodex, GetNames(_)) - .WillOnce(SetArrayArgument<0>(names.begin(), names.end())); -``` - -## Changing a Mock Object's Behavior Based on the State ## - -If you expect a call to change the behavior of a mock object, you can use `::testing::InSequence` to specify different behaviors before and after the call: - -``` -using ::testing::InSequence; -using ::testing::Return; - -... - { - InSequence seq; - EXPECT_CALL(my_mock, IsDirty()) - .WillRepeatedly(Return(true)); - EXPECT_CALL(my_mock, Flush()); - EXPECT_CALL(my_mock, IsDirty()) - .WillRepeatedly(Return(false)); - } - my_mock.FlushIfDirty(); -``` - -This makes `my_mock.IsDirty()` return `true` before `my_mock.Flush()` is called and return `false` afterwards. - -If the behavior change is more complex, you can store the effects in a variable and make a mock method get its return value from that variable: - -``` -using ::testing::_; -using ::testing::SaveArg; -using ::testing::Return; - -ACTION_P(ReturnPointee, p) { return *p; } -... - int previous_value = 0; - EXPECT_CALL(my_mock, GetPrevValue()) - .WillRepeatedly(ReturnPointee(&previous_value)); - EXPECT_CALL(my_mock, UpdateValue(_)) - .WillRepeatedly(SaveArg<0>(&previous_value)); - my_mock.DoSomethingToUpdateValue(); -``` - -Here `my_mock.GetPrevValue()` will always return the argument of the last `UpdateValue()` call. - -## Setting the Default Value for a Return Type ## - -If a mock method's return type is a built-in C++ type or pointer, by -default it will return 0 when invoked. You only need to specify an -action if this default value doesn't work for you. - -Sometimes, you may want to change this default value, or you may want -to specify a default value for types Google Mock doesn't know -about. You can do this using the `::testing::DefaultValue` class -template: - -``` -class MockFoo : public Foo { - public: - MOCK_METHOD0(CalculateBar, Bar()); -}; -... - - Bar default_bar; - // Sets the default return value for type Bar. - DefaultValue<Bar>::Set(default_bar); - - MockFoo foo; - - // We don't need to specify an action here, as the default - // return value works for us. - EXPECT_CALL(foo, CalculateBar()); - - foo.CalculateBar(); // This should return default_bar. - - // Unsets the default return value. - DefaultValue<Bar>::Clear(); -``` - -Please note that changing the default value for a type can make you -tests hard to understand. We recommend you to use this feature -judiciously. For example, you may want to make sure the `Set()` and -`Clear()` calls are right next to the code that uses your mock. - -## Setting the Default Actions for a Mock Method ## - -You've learned how to change the default value of a given -type. However, this may be too coarse for your purpose: perhaps you -have two mock methods with the same return type and you want them to -have different behaviors. The `ON_CALL()` macro allows you to -customize your mock's behavior at the method level: - -``` -using ::testing::_; -using ::testing::AnyNumber; -using ::testing::Gt; -using ::testing::Return; -... - ON_CALL(foo, Sign(_)) - .WillByDefault(Return(-1)); - ON_CALL(foo, Sign(0)) - .WillByDefault(Return(0)); - ON_CALL(foo, Sign(Gt(0))) - .WillByDefault(Return(1)); - - EXPECT_CALL(foo, Sign(_)) - .Times(AnyNumber()); - - foo.Sign(5); // This should return 1. - foo.Sign(-9); // This should return -1. - foo.Sign(0); // This should return 0. -``` - -As you may have guessed, when there are more than one `ON_CALL()` -statements, the news order take precedence over the older ones. In -other words, the **last** one that matches the function arguments will -be used. This matching order allows you to set up the common behavior -in a mock object's constructor or the test fixture's set-up phase and -specialize the mock's behavior later. - -## Using Functions/Methods/Functors as Actions ## - -If the built-in actions don't suit you, you can easily use an existing -function, method, or functor as an action: - -``` -using ::testing::_; -using ::testing::Invoke; - -class MockFoo : public Foo { - public: - MOCK_METHOD2(Sum, int(int x, int y)); - MOCK_METHOD1(ComplexJob, bool(int x)); -}; - -int CalculateSum(int x, int y) { return x + y; } - -class Helper { - public: - bool ComplexJob(int x); -}; -... - - MockFoo foo; - Helper helper; - EXPECT_CALL(foo, Sum(_, _)) - .WillOnce(Invoke(CalculateSum)); - EXPECT_CALL(foo, ComplexJob(_)) - .WillOnce(Invoke(&helper, &Helper::ComplexJob)); - - foo.Sum(5, 6); // Invokes CalculateSum(5, 6). - foo.ComplexJob(10); // Invokes helper.ComplexJob(10); -``` - -The only requirement is that the type of the function, etc must be -_compatible_ with the signature of the mock function, meaning that the -latter's arguments can be implicitly converted to the corresponding -arguments of the former, and the former's return type can be -implicitly converted to that of the latter. So, you can invoke -something whose type is _not_ exactly the same as the mock function, -as long as it's safe to do so - nice, huh? - -## Invoking a Function/Method/Functor Without Arguments ## - -`Invoke()` is very useful for doing actions that are more complex. It -passes the mock function's arguments to the function or functor being -invoked such that the callee has the full context of the call to work -with. If the invoked function is not interested in some or all of the -arguments, it can simply ignore them. - -Yet, a common pattern is that a test author wants to invoke a function -without the arguments of the mock function. `Invoke()` allows her to -do that using a wrapper function that throws away the arguments before -invoking an underlining nullary function. Needless to say, this can be -tedious and obscures the intent of the test. - -`InvokeWithoutArgs()` solves this problem. It's like `Invoke()` except -that it doesn't pass the mock function's arguments to the -callee. Here's an example: - -``` -using ::testing::_; -using ::testing::InvokeWithoutArgs; - -class MockFoo : public Foo { - public: - MOCK_METHOD1(ComplexJob, bool(int n)); -}; - -bool Job1() { ... } -... - - MockFoo foo; - EXPECT_CALL(foo, ComplexJob(_)) - .WillOnce(InvokeWithoutArgs(Job1)); - - foo.ComplexJob(10); // Invokes Job1(). -``` - -## Invoking an Argument of the Mock Function ## - -Sometimes a mock function will receive a function pointer or a functor -(in other words, a "callable") as an argument, e.g. - -``` -class MockFoo : public Foo { - public: - MOCK_METHOD2(DoThis, bool(int n, bool (*fp)(int))); -}; -``` - -and you may want to invoke this callable argument: - -``` -using ::testing::_; -... - MockFoo foo; - EXPECT_CALL(foo, DoThis(_, _)) - .WillOnce(...); - // Will execute (*fp)(5), where fp is the - // second argument DoThis() receives. -``` - -Arghh, you need to refer to a mock function argument but C++ has no -lambda (yet), so you have to define your own action. :-( Or do you -really? - -Well, Google Mock has an action to solve _exactly_ this problem: - -``` - InvokeArgument<N>(arg_1, arg_2, ..., arg_m) -``` - -will invoke the `N`-th (0-based) argument the mock function receives, -with `arg_1`, `arg_2`, ..., and `arg_m`. No matter if the argument is -a function pointer or a functor, Google Mock handles them both. - -With that, you could write: - -``` -using ::testing::_; -using ::testing::InvokeArgument; -... - EXPECT_CALL(foo, DoThis(_, _)) - .WillOnce(InvokeArgument<1>(5)); - // Will execute (*fp)(5), where fp is the - // second argument DoThis() receives. -``` - -What if the callable takes an argument by reference? No problem - just -wrap it inside `ByRef()`: - -``` -... - MOCK_METHOD1(Bar, bool(bool (*fp)(int, const Helper&))); -... -using ::testing::_; -using ::testing::ByRef; -using ::testing::InvokeArgument; -... - - MockFoo foo; - Helper helper; - ... - EXPECT_CALL(foo, Bar(_)) - .WillOnce(InvokeArgument<0>(5, ByRef(helper))); - // ByRef(helper) guarantees that a reference to helper, not a copy of it, - // will be passed to the callable. -``` - -What if the callable takes an argument by reference and we do **not** -wrap the argument in `ByRef()`? Then `InvokeArgument()` will _make a -copy_ of the argument, and pass a _reference to the copy_, instead of -a reference to the original value, to the callable. This is especially -handy when the argument is a temporary value: - -``` -... - MOCK_METHOD1(DoThat, bool(bool (*f)(const double& x, const string& s))); -... -using ::testing::_; -using ::testing::InvokeArgument; -... - - MockFoo foo; - ... - EXPECT_CALL(foo, DoThat(_)) - .WillOnce(InvokeArgument<0>(5.0, string("Hi"))); - // Will execute (*f)(5.0, string("Hi")), where f is the function pointer - // DoThat() receives. Note that the values 5.0 and string("Hi") are - // temporary and dead once the EXPECT_CALL() statement finishes. Yet - // it's fine to perform this action later, since a copy of the values - // are kept inside the InvokeArgument action. -``` - -## Ignoring an Action's Result ## - -Sometimes you have an action that returns _something_, but you need an -action that returns `void` (perhaps you want to use it in a mock -function that returns `void`, or perhaps it needs to be used in -`DoAll()` and it's not the last in the list). `IgnoreResult()` lets -you do that. For example: - -``` -using ::testing::_; -using ::testing::Invoke; -using ::testing::Return; - -int Process(const MyData& data); -string DoSomething(); - -class MockFoo : public Foo { - public: - MOCK_METHOD1(Abc, void(const MyData& data)); - MOCK_METHOD0(Xyz, bool()); -}; -... - - MockFoo foo; - EXPECT_CALL(foo, Abc(_)) - // .WillOnce(Invoke(Process)); - // The above line won't compile as Process() returns int but Abc() needs - // to return void. - .WillOnce(IgnoreResult(Invoke(Process))); - - EXPECT_CALL(foo, Xyz()) - .WillOnce(DoAll(IgnoreResult(Invoke(DoSomething)), - // Ignores the string DoSomething() returns. - Return(true))); -``` - -Note that you **cannot** use `IgnoreResult()` on an action that already -returns `void`. Doing so will lead to ugly compiler errors. - -## Selecting an Action's Arguments ## - -Say you have a mock function `Foo()` that takes seven arguments, and -you have a custom action that you want to invoke when `Foo()` is -called. Trouble is, the custom action only wants three arguments: - -``` -using ::testing::_; -using ::testing::Invoke; -... - MOCK_METHOD7(Foo, bool(bool visible, const string& name, int x, int y, - const map<pair<int, int>, double>& weight, - double min_weight, double max_wight)); -... - -bool IsVisibleInQuadrant1(bool visible, int x, int y) { - return visible && x >= 0 && y >= 0; -} -... - - EXPECT_CALL(mock, Foo(_, _, _, _, _, _, _)) - .WillOnce(Invoke(IsVisibleInQuadrant1)); // Uh, won't compile. :-( -``` - -To please the compiler God, you can to define an "adaptor" that has -the same signature as `Foo()` and calls the custom action with the -right arguments: - -``` -using ::testing::_; -using ::testing::Invoke; - -bool MyIsVisibleInQuadrant1(bool visible, const string& name, int x, int y, - const map<pair<int, int>, double>& weight, - double min_weight, double max_wight) { - return IsVisibleInQuadrant1(visible, x, y); -} -... - - EXPECT_CALL(mock, Foo(_, _, _, _, _, _, _)) - .WillOnce(Invoke(MyIsVisibleInQuadrant1)); // Now it works. -``` - -But isn't this awkward? - -Google Mock provides a generic _action adaptor_, so you can spend your -time minding more important business than writing your own -adaptors. Here's the syntax: - -``` - WithArgs<N1, N2, ..., Nk>(action) -``` - -creates an action that passes the arguments of the mock function at -the given indices (0-based) to the inner `action` and performs -it. Using `WithArgs`, our original example can be written as: - -``` -using ::testing::_; -using ::testing::Invoke; -using ::testing::WithArgs; -... - EXPECT_CALL(mock, Foo(_, _, _, _, _, _, _)) - .WillOnce(WithArgs<0, 2, 3>(Invoke(IsVisibleInQuadrant1))); - // No need to define your own adaptor. -``` - -For better readability, Google Mock also gives you: - - * `WithoutArgs(action)` when the inner `action` takes _no_ argument, and - * `WithArg<N>(action)` (no `s` after `Arg`) when the inner `action` takes _one_ argument. - -As you may have realized, `InvokeWithoutArgs(...)` is just syntactic -sugar for `WithoutArgs(Inovke(...))`. - -Here are more tips: - - * The inner action used in `WithArgs` and friends does not have to be `Invoke()` -- it can be anything. - * You can repeat an argument in the argument list if necessary, e.g. `WithArgs<2, 3, 3, 5>(...)`. - * You can change the order of the arguments, e.g. `WithArgs<3, 2, 1>(...)`. - * The types of the selected arguments do _not_ have to match the signature of the inner action exactly. It works as long as they can be implicitly converted to the corresponding arguments of the inner action. For example, if the 4-th argument of the mock function is an `int` and `my_action` takes a `double`, `WithArg<4>(my_action)` will work. - -## Ignoring Arguments in Action Functions ## - -The selecting-an-action's-arguments recipe showed us one way to make a -mock function and an action with incompatible argument lists fit -together. The downside is that wrapping the action in -`WithArgs<...>()` can get tedious for people writing the tests. - -If you are defining a function, method, or functor to be used with -`Invoke*()`, and you are not interested in some of its arguments, an -alternative to `WithArgs` is to declare the uninteresting arguments as -`Unused`. This makes the definition less cluttered and less fragile in -case the types of the uninteresting arguments change. It could also -increase the chance the action function can be reused. For example, -given - -``` - MOCK_METHOD3(Foo, double(const string& label, double x, double y)); - MOCK_METHOD3(Bar, double(int index, double x, double y)); -``` - -instead of - -``` -using ::testing::_; -using ::testing::Invoke; - -double DistanceToOriginWithLabel(const string& label, double x, double y) { - return sqrt(x*x + y*y); -} - -double DistanceToOriginWithIndex(int index, double x, double y) { - return sqrt(x*x + y*y); -} -... - - EXEPCT_CALL(mock, Foo("abc", _, _)) - .WillOnce(Invoke(DistanceToOriginWithLabel)); - EXEPCT_CALL(mock, Bar(5, _, _)) - .WillOnce(Invoke(DistanceToOriginWithIndex)); -``` - -you could write - -``` -using ::testing::_; -using ::testing::Invoke; -using ::testing::Unused; - -double DistanceToOrigin(Unused, double x, double y) { - return sqrt(x*x + y*y); -} -... - - EXEPCT_CALL(mock, Foo("abc", _, _)) - .WillOnce(Invoke(DistanceToOrigin)); - EXEPCT_CALL(mock, Bar(5, _, _)) - .WillOnce(Invoke(DistanceToOrigin)); -``` - -## Sharing Actions ## - -Just like matchers, a Google Mock action object consists of a pointer -to a ref-counted implementation object. Therefore copying actions is -also allowed and very efficient. When the last action that references -the implementation object dies, the implementation object will be -deleted. - -If you have some complex action that you want to use again and again, -you may not have to build it from scratch everytime. If the action -doesn't have an internal state (i.e. if it always does the same thing -no matter how many times it has been called), you can assign it to an -action variable and use that variable repeatedly. For example: - -``` - Action<bool(int*)> set_flag = DoAll(SetArgPointee<0>(5), - Return(true)); - ... use set_flag in .WillOnce() and .WillRepeatedly() ... -``` - -However, if the action has its own state, you may be surprised if you -share the action object. Suppose you have an action factory -`IncrementCounter(init)` which creates an action that increments and -returns a counter whose initial value is `init`, using two actions -created from the same expression and using a shared action will -exihibit different behaviors. Example: - -``` - EXPECT_CALL(foo, DoThis()) - .WillRepeatedly(IncrementCounter(0)); - EXPECT_CALL(foo, DoThat()) - .WillRepeatedly(IncrementCounter(0)); - foo.DoThis(); // Returns 1. - foo.DoThis(); // Returns 2. - foo.DoThat(); // Returns 1 - Blah() uses a different - // counter than Bar()'s. -``` - -versus - -``` - Action<int()> increment = IncrementCounter(0); - - EXPECT_CALL(foo, DoThis()) - .WillRepeatedly(increment); - EXPECT_CALL(foo, DoThat()) - .WillRepeatedly(increment); - foo.DoThis(); // Returns 1. - foo.DoThis(); // Returns 2. - foo.DoThat(); // Returns 3 - the counter is shared. -``` - -# Misc Recipes on Using Google Mock # - -## Making the Compilation Faster ## - -Believe it or not, the _vast majority_ of the time spent on compiling -a mock class is in generating its constructor and destructor, as they -perform non-trivial tasks (e.g. verification of the -expectations). What's more, mock methods with different signatures -have different types and thus their constructors/destructors need to -be generated by the compiler separately. As a result, if you mock many -different types of methods, compiling your mock class can get really -slow. - -If you are experiencing slow compilation, you can move the definition -of your mock class' constructor and destructor out of the class body -and into a `.cpp` file. This way, even if you `#include` your mock -class in N files, the compiler only needs to generate its constructor -and destructor once, resulting in a much faster compilation. - -Let's illustrate the idea using an example. Here's the definition of a -mock class before applying this recipe: - -``` -// File mock_foo.h. -... -class MockFoo : public Foo { - public: - // Since we don't declare the constructor or the destructor, - // the compiler will generate them in every translation unit - // where this mock class is used. - - MOCK_METHOD0(DoThis, int()); - MOCK_METHOD1(DoThat, bool(const char* str)); - ... more mock methods ... -}; -``` - -After the change, it would look like: - -``` -// File mock_foo.h. -... -class MockFoo : public Foo { - public: - // The constructor and destructor are declared, but not defined, here. - MockFoo(); - virtual ~MockFoo(); - - MOCK_METHOD0(DoThis, int()); - MOCK_METHOD1(DoThat, bool(const char* str)); - ... more mock methods ... -}; -``` -and -``` -// File mock_foo.cpp. -#include "path/to/mock_foo.h" - -// The definitions may appear trivial, but the functions actually do a -// lot of things through the constructors/destructors of the member -// variables used to implement the mock methods. -MockFoo::MockFoo() {} -MockFoo::~MockFoo() {} -``` - -## Forcing a Verification ## - -When it's being destoyed, your friendly mock object will automatically -verify that all expectations on it have been satisfied, and will -generate [Google Test](http://code.google.com/p/googletest/) failures -if not. This is convenient as it leaves you with one less thing to -worry about. That is, unless you are not sure if your mock object will -be destoyed. - -How could it be that your mock object won't eventually be destroyed? -Well, it might be created on the heap and owned by the code you are -testing. Suppose there's a bug in that code and it doesn't delete the -mock object properly - you could end up with a passing test when -there's actually a bug. - -Using a heap checker is a good idea and can alleviate the concern, but -its implementation may not be 100% reliable. So, sometimes you do want -to _force_ Google Mock to verify a mock object before it is -(hopefully) destructed. You can do this with -`Mock::VerifyAndClearExpectations(&mock_object)`: - -``` -TEST(MyServerTest, ProcessesRequest) { - using ::testing::Mock; - - MockFoo* const foo = new MockFoo; - EXPECT_CALL(*foo, ...)...; - // ... other expectations ... - - // server now owns foo. - MyServer server(foo); - server.ProcessRequest(...); - - // In case that server's destructor will forget to delete foo, - // this will verify the expectations anyway. - Mock::VerifyAndClearExpectations(foo); -} // server is destroyed when it goes out of scope here. -``` - -**Tip:** The `Mock::VerifyAndClearExpectations()` function returns a -`bool` to indicate whether the verification was successful (`true` for -yes), so you can wrap that function call inside a `ASSERT_TRUE()` if -there is no point going further when the verification has failed. - -## Using Check Points ## - -Sometimes you may want to "reset" a mock object at various check -points in your test: at each check point, you verify that all existing -expectations on the mock object have been satisfied, and then you set -some new expectations on it as if it's newly created. This allows you -to work with a mock object in "phases" whose sizes are each -manageable. - -One such scenario is that in your test's `SetUp()` function, you may -want to put the object you are testing into a certain state, with the -help from a mock object. Once in the desired state, you want to clear -all expectations on the mock, such that in the `TEST_F` body you can -set fresh expectations on it. - -As you may have figured out, the `Mock::VerifyAndClearExpectations()` -function we saw in the previous recipe can help you here. Or, if you -are using `ON_CALL()` to set default actions on the mock object and -want to clear the default actions as well, use -`Mock::VerifyAndClear(&mock_object)` instead. This function does what -`Mock::VerifyAndClearExpectations(&mock_object)` does and returns the -same `bool`, **plus** it clears the `ON_CALL()` statements on -`mock_object` too. - -Another trick you can use to achieve the same effect is to put the -expectations in sequences and insert calls to a dummy "check-point" -function at specific places. Then you can verify that the mock -function calls do happen at the right time. For example, if you are -exercising code: - -``` -Foo(1); -Foo(2); -Foo(3); -``` - -and want to verify that `Foo(1)` and `Foo(3)` both invoke -`mock.Bar("a")`, but `Foo(2)` doesn't invoke anything. You can write: - -``` -using ::testing::MockFunction; - -TEST(FooTest, InvokesBarCorrectly) { - MyMock mock; - // Class MockFunction<F> has exactly one mock method. It is named - // Call() and has type F. - MockFunction<void(string check_point_name)> check; - { - InSequence s; - - EXPECT_CALL(mock, Bar("a")); - EXPECT_CALL(check, Call("1")); - EXPECT_CALL(check, Call("2")); - EXPECT_CALL(mock, Bar("a")); - } - Foo(1); - check.Call("1"); - Foo(2); - check.Call("2"); - Foo(3); -} -``` - -The expectation spec says that the first `Bar("a")` must happen before -check point "1", the second `Bar("a")` must happen after check point "2", -and nothing should happen between the two check points. The explicit -check points make it easy to tell which `Bar("a")` is called by which -call to `Foo()`. - -## Mocking Destructors ## - -Sometimes you want to make sure a mock object is destructed at the -right time, e.g. after `bar->A()` is called but before `bar->B()` is -called. We already know that you can specify constraints on the order -of mock function calls, so all we need to do is to mock the destructor -of the mock function. - -This sounds simple, except for one problem: a destructor is a special -function with special syntax and special semantics, and the -`MOCK_METHOD0` macro doesn't work for it: - -``` - MOCK_METHOD0(~MockFoo, void()); // Won't compile! -``` - -The good news is that you can use a simple pattern to achieve the same -effect. First, add a mock function `Die()` to your mock class and call -it in the destructor, like this: - -``` -class MockFoo : public Foo { - ... - // Add the following two lines to the mock class. - MOCK_METHOD0(Die, void()); - virtual ~MockFoo() { Die(); } -}; -``` - -(If the name `Die()` clashes with an existing symbol, choose another -name.) Now, we have translated the problem of testing when a `MockFoo` -object dies to testing when its `Die()` method is called: - -``` - MockFoo* foo = new MockFoo; - MockBar* bar = new MockBar; - ... - { - InSequence s; - - // Expects *foo to die after bar->A() and before bar->B(). - EXPECT_CALL(*bar, A()); - EXPECT_CALL(*foo, Die()); - EXPECT_CALL(*bar, B()); - } -``` - -And that's that. - -## Using Google Mock and Threads ## - -**IMPORTANT NOTE:** What we describe in this recipe is **ONLY** true on -platforms where Google Mock is thread-safe. Currently these are only -platforms that support the pthreads library (this includes Linux and Mac). -To make it thread-safe on other platforms we only need to implement -some synchronization operations in `"gtest/internal/gtest-port.h"`. - -In a **unit** test, it's best if you could isolate and test a piece of -code in a single-threaded context. That avoids race conditions and -dead locks, and makes debugging your test much easier. - -Yet many programs are multi-threaded, and sometimes to test something -we need to pound on it from more than one thread. Google Mock works -for this purpose too. - -Remember the steps for using a mock: - - 1. Create a mock object `foo`. - 1. Set its default actions and expectations using `ON_CALL()` and `EXPECT_CALL()`. - 1. The code under test calls methods of `foo`. - 1. Optionally, verify and reset the mock. - 1. Destroy the mock yourself, or let the code under test destroy it. The destructor will automatically verify it. - -If you follow the following simple rules, your mocks and threads can -live happily togeter: - - * Execute your _test code_ (as opposed to the code being tested) in _one_ thread. This makes your test easy to follow. - * Obviously, you can do step #1 without locking. - * When doing step #2 and #5, make sure no other thread is accessing `foo`. Obvious too, huh? - * #3 and #4 can be done either in one thread or in multiple threads - anyway you want. Google Mock takes care of the locking, so you don't have to do any - unless required by your test logic. - -If you violate the rules (for example, if you set expectations on a -mock while another thread is calling its methods), you get undefined -behavior. That's not fun, so don't do it. - -Google Mock guarantees that the action for a mock function is done in -the same thread that called the mock function. For example, in - -``` - EXPECT_CALL(mock, Foo(1)) - .WillOnce(action1); - EXPECT_CALL(mock, Foo(2)) - .WillOnce(action2); -``` - -if `Foo(1)` is called in thread 1 and `Foo(2)` is called in thread 2, -Google Mock will execute `action1` in thread 1 and `action2` in thread -2. - -Google Mock does _not_ impose a sequence on actions performed in -different threads (doing so may create deadlocks as the actions may -need to cooperate). This means that the execution of `action1` and -`action2` in the above example _may_ interleave. If this is a problem, -you should add proper synchronization logic to `action1` and `action2` -to make the test thread-safe. - - -Also, remember that `DefaultValue<T>` is a global resource that -potentially affects _all_ living mock objects in your -program. Naturally, you won't want to mess with it from multiple -threads or when there still are mocks in action. - -## Controlling How Much Information Google Mock Prints ## - -When Google Mock sees something that has the potential of being an -error (e.g. a mock function with no expectation is called, a.k.a. an -uninteresting call, which is allowed but perhaps you forgot to -explicitly ban the call), it prints some warning messages, including -the arguments of the function and the return value. Hopefully this -will remind you to take a look and see if there is indeed a problem. - -Sometimes you are confident that your tests are correct and may not -appreciate such friendly messages. Some other times, you are debugging -your tests or learning about the behavior of the code you are testing, -and wish you could observe every mock call that happens (including -argument values and the return value). Clearly, one size doesn't fit -all. - -You can control how much Google Mock tells you using the -`--gmock_verbose=LEVEL` command-line flag, where `LEVEL` is a string -with three possible values: - - * `info`: Google Mock will print all informational messages, warnings, and errors (most verbose). At this setting, Google Mock will also log any calls to the `ON_CALL/EXPECT_CALL` macros. - * `warning`: Google Mock will print both warnings and errors (less verbose). This is the default. - * `error`: Google Mock will print errors only (least verbose). - -Alternatively, you can adjust the value of that flag from within your -tests like so: - -``` - ::testing::FLAGS_gmock_verbose = "error"; -``` - -Now, judiciously use the right flag to enable Google Mock serve you better! - -## Gaining Super Vision into Mock Calls ## - -You have a test using Google Mock. It fails: Google Mock tells you -that some expectations aren't satisfied. However, you aren't sure why: -Is there a typo somewhere in the matchers? Did you mess up the order -of the `EXPECT_CALL`s? Or is the code under test doing something -wrong? How can you find out the cause? - -Won't it be nice if you have X-ray vision and can actually see the -trace of all `EXPECT_CALL`s and mock method calls as they are made? -For each call, would you like to see its actual argument values and -which `EXPECT_CALL` Google Mock thinks it matches? - -You can unlock this power by running your test with the -`--gmock_verbose=info` flag. For example, given the test program: - -``` -using testing::_; -using testing::HasSubstr; -using testing::Return; - -class MockFoo { - public: - MOCK_METHOD2(F, void(const string& x, const string& y)); -}; - -TEST(Foo, Bar) { - MockFoo mock; - EXPECT_CALL(mock, F(_, _)).WillRepeatedly(Return()); - EXPECT_CALL(mock, F("a", "b")); - EXPECT_CALL(mock, F("c", HasSubstr("d"))); - - mock.F("a", "good"); - mock.F("a", "b"); -} -``` - -if you run it with `--gmock_verbose=info`, you will see this output: - -``` -[ RUN ] Foo.Bar - -foo_test.cc:14: EXPECT_CALL(mock, F(_, _)) invoked -foo_test.cc:15: EXPECT_CALL(mock, F("a", "b")) invoked -foo_test.cc:16: EXPECT_CALL(mock, F("c", HasSubstr("d"))) invoked -foo_test.cc:14: Mock function call matches EXPECT_CALL(mock, F(_, _))... - Function call: F(@0x7fff7c8dad40"a", @0x7fff7c8dad10"good") -foo_test.cc:15: Mock function call matches EXPECT_CALL(mock, F("a", "b"))... - Function call: F(@0x7fff7c8dada0"a", @0x7fff7c8dad70"b") -foo_test.cc:16: Failure -Actual function call count doesn't match EXPECT_CALL(mock, F("c", HasSubstr("d")))... - Expected: to be called once - Actual: never called - unsatisfied and active -[ FAILED ] Foo.Bar -``` - -Suppose the bug is that the `"c"` in the third `EXPECT_CALL` is a typo -and should actually be `"a"`. With the above message, you should see -that the actual `F("a", "good")` call is matched by the first -`EXPECT_CALL`, not the third as you thought. From that it should be -obvious that the third `EXPECT_CALL` is written wrong. Case solved. - -## Running Tests in Emacs ## - -If you build and run your tests in Emacs, the source file locations of -Google Mock and [Google Test](http://code.google.com/p/googletest/) -errors will be highlighted. Just press `<Enter>` on one of them and -you'll be taken to the offending line. Or, you can just type `C-x `` -to jump to the next error. - -To make it even easier, you can add the following lines to your -`~/.emacs` file: - -``` -(global-set-key "\M-m" 'compile) ; m is for make -(global-set-key [M-down] 'next-error) -(global-set-key [M-up] '(lambda () (interactive) (next-error -1))) -``` - -Then you can type `M-m` to start a build, or `M-up`/`M-down` to move -back and forth between errors. - -## Fusing Google Mock Source Files ## - -Google Mock's implementation consists of dozens of files (excluding -its own tests). Sometimes you may want them to be packaged up in -fewer files instead, such that you can easily copy them to a new -machine and start hacking there. For this we provide an experimental -Python script `fuse_gmock_files.py` in the `scripts/` directory -(starting with release 1.2.0). Assuming you have Python 2.4 or above -installed on your machine, just go to that directory and run -``` -python fuse_gmock_files.py OUTPUT_DIR -``` - -and you should see an `OUTPUT_DIR` directory being created with files -`gtest/gtest.h`, `gmock/gmock.h`, and `gmock-gtest-all.cc` in it. -These three files contain everything you need to use Google Mock (and -Google Test). Just copy them to anywhere you want and you are ready -to write tests and use mocks. You can use the -[scrpts/test/Makefile](http://code.google.com/p/googlemock/source/browse/trunk/scripts/test/Makefile) file as an example on how to compile your tests -against them. - -# Extending Google Mock # - -## Writing New Matchers Quickly ## - -The `MATCHER*` family of macros can be used to define custom matchers -easily. The syntax: - -``` -MATCHER(name, description_string_expression) { statements; } -``` - -will define a matcher with the given name that executes the -statements, which must return a `bool` to indicate if the match -succeeds. Inside the statements, you can refer to the value being -matched by `arg`, and refer to its type by `arg_type`. - -The description string is a `string`-typed expression that documents -what the matcher does, and is used to generate the failure message -when the match fails. It can (and should) reference the special -`bool` variable `negation`, and should evaluate to the description of -the matcher when `negation` is `false`, or that of the matcher's -negation when `negation` is `true`. - -For convenience, we allow the description string to be empty (`""`), -in which case Google Mock will use the sequence of words in the -matcher name as the description. - -For example: -``` -MATCHER(IsDivisibleBy7, "") { return (arg % 7) == 0; } -``` -allows you to write -``` - // Expects mock_foo.Bar(n) to be called where n is divisible by 7. - EXPECT_CALL(mock_foo, Bar(IsDivisibleBy7())); -``` -or, -``` -using ::testing::Not; -... - EXPECT_THAT(some_expression, IsDivisibleBy7()); - EXPECT_THAT(some_other_expression, Not(IsDivisibleBy7())); -``` -If the above assertions fail, they will print something like: -``` - Value of: some_expression - Expected: is divisible by 7 - Actual: 27 -... - Value of: some_other_expression - Expected: not (is divisible by 7) - Actual: 21 -``` -where the descriptions `"is divisible by 7"` and `"not (is divisible -by 7)"` are automatically calculated from the matcher name -`IsDivisibleBy7`. - -As you may have noticed, the auto-generated descriptions (especially -those for the negation) may not be so great. You can always override -them with a string expression of your own: -``` -MATCHER(IsDivisibleBy7, std::string(negation ? "isn't" : "is") + - " divisible by 7") { - return (arg % 7) == 0; -} -``` - -Optionally, you can stream additional information to a hidden argument -named `result_listener` to explain the match result. For example, a -better definition of `IsDivisibleBy7` is: -``` -MATCHER(IsDivisibleBy7, "") { - if ((arg % 7) == 0) - return true; - - *result_listener << "the remainder is " << (arg % 7); - return false; -} -``` - -With this definition, the above assertion will give a better message: -``` - Value of: some_expression - Expected: is divisible by 7 - Actual: 27 (the remainder is 6) -``` - -You should let `MatchAndExplain()` print _any additional information_ -that can help a user understand the match result. Note that it should -explain why the match succeeds in case of a success (unless it's -obvious) - this is useful when the matcher is used inside -`Not()`. There is no need to print the argument value itself, as -Google Mock already prints it for you. - -**Notes:** - - 1. The type of the value being matched (`arg_type`) is determined by the context in which you use the matcher and is supplied to you by the compiler, so you don't need to worry about declaring it (nor can you). This allows the matcher to be polymorphic. For example, `IsDivisibleBy7()` can be used to match any type where the value of `(arg % 7) == 0` can be implicitly converted to a `bool`. In the `Bar(IsDivisibleBy7())` example above, if method `Bar()` takes an `int`, `arg_type` will be `int`; if it takes an `unsigned long`, `arg_type` will be `unsigned long`; and so on. - 1. Google Mock doesn't guarantee when or how many times a matcher will be invoked. Therefore the matcher logic must be _purely functional_ (i.e. it cannot have any side effect, and the result must not depend on anything other than the value being matched and the matcher parameters). This requirement must be satisfied no matter how you define the matcher (e.g. using one of the methods described in the following recipes). In particular, a matcher can never call a mock function, as that will affect the state of the mock object and Google Mock. - -## Writing New Parameterized Matchers Quickly ## - -Sometimes you'll want to define a matcher that has parameters. For that you -can use the macro: -``` -MATCHER_P(name, param_name, description_string) { statements; } -``` -where the description string can be either `""` or a string expression -that references `negation` and `param_name`. - -For example: -``` -MATCHER_P(HasAbsoluteValue, value, "") { return abs(arg) == value; } -``` -will allow you to write: -``` - EXPECT_THAT(Blah("a"), HasAbsoluteValue(n)); -``` -which may lead to this message (assuming `n` is 10): -``` - Value of: Blah("a") - Expected: has absolute value 10 - Actual: -9 -``` - -Note that both the matcher description and its parameter are -printed, making the message human-friendly. - -In the matcher definition body, you can write `foo_type` to -reference the type of a parameter named `foo`. For example, in the -body of `MATCHER_P(HasAbsoluteValue, value)` above, you can write -`value_type` to refer to the type of `value`. - -Google Mock also provides `MATCHER_P2`, `MATCHER_P3`, ..., up to -`MATCHER_P10` to support multi-parameter matchers: -``` -MATCHER_Pk(name, param_1, ..., param_k, description_string) { statements; } -``` - -Please note that the custom description string is for a particular -**instance** of the matcher, where the parameters have been bound to -actual values. Therefore usually you'll want the parameter values to -be part of the description. Google Mock lets you do that by -referencing the matcher parameters in the description string -expression. - -For example, -``` - using ::testing::PrintToString; - MATCHER_P2(InClosedRange, low, hi, - std::string(negation ? "isn't" : "is") + " in range [" + - PrintToString(low) + ", " + PrintToString(hi) + "]") { - return low <= arg && arg <= hi; - } - ... - EXPECT_THAT(3, InClosedRange(4, 6)); -``` -would generate a failure that contains the message: -``` - Expected: is in range [4, 6] -``` - -If you specify `""` as the description, the failure message will -contain the sequence of words in the matcher name followed by the -parameter values printed as a tuple. For example, -``` - MATCHER_P2(InClosedRange, low, hi, "") { ... } - ... - EXPECT_THAT(3, InClosedRange(4, 6)); -``` -would generate a failure that contains the text: -``` - Expected: in closed range (4, 6) -``` - -For the purpose of typing, you can view -``` -MATCHER_Pk(Foo, p1, ..., pk, description_string) { ... } -``` -as shorthand for -``` -template <typename p1_type, ..., typename pk_type> -FooMatcherPk<p1_type, ..., pk_type> -Foo(p1_type p1, ..., pk_type pk) { ... } -``` - -When you write `Foo(v1, ..., vk)`, the compiler infers the types of -the parameters `v1`, ..., and `vk` for you. If you are not happy with -the result of the type inference, you can specify the types by -explicitly instantiating the template, as in `Foo<long, bool>(5, false)`. -As said earlier, you don't get to (or need to) specify -`arg_type` as that's determined by the context in which the matcher -is used. - -You can assign the result of expression `Foo(p1, ..., pk)` to a -variable of type `FooMatcherPk<p1_type, ..., pk_type>`. This can be -useful when composing matchers. Matchers that don't have a parameter -or have only one parameter have special types: you can assign `Foo()` -to a `FooMatcher`-typed variable, and assign `Foo(p)` to a -`FooMatcherP<p_type>`-typed variable. - -While you can instantiate a matcher template with reference types, -passing the parameters by pointer usually makes your code more -readable. If, however, you still want to pass a parameter by -reference, be aware that in the failure message generated by the -matcher you will see the value of the referenced object but not its -address. - -You can overload matchers with different numbers of parameters: -``` -MATCHER_P(Blah, a, description_string_1) { ... } -MATCHER_P2(Blah, a, b, description_string_2) { ... } -``` - -While it's tempting to always use the `MATCHER*` macros when defining -a new matcher, you should also consider implementing -`MatcherInterface` or using `MakePolymorphicMatcher()` instead (see -the recipes that follow), especially if you need to use the matcher a -lot. While these approaches require more work, they give you more -control on the types of the value being matched and the matcher -parameters, which in general leads to better compiler error messages -that pay off in the long run. They also allow overloading matchers -based on parameter types (as opposed to just based on the number of -parameters). - -## Writing New Monomorphic Matchers ## - -A matcher of argument type `T` implements -`::testing::MatcherInterface<T>` and does two things: it tests whether a -value of type `T` matches the matcher, and can describe what kind of -values it matches. The latter ability is used for generating readable -error messages when expectations are violated. - -The interface looks like this: - -``` -class MatchResultListener { - public: - ... - // Streams x to the underlying ostream; does nothing if the ostream - // is NULL. - template <typename T> - MatchResultListener& operator<<(const T& x); - - // Returns the underlying ostream. - ::std::ostream* stream(); -}; - -template <typename T> -class MatcherInterface { - public: - virtual ~MatcherInterface(); - - // Returns true iff the matcher matches x; also explains the match - // result to 'listener'. - virtual bool MatchAndExplain(T x, MatchResultListener* listener) const = 0; - - // Describes this matcher to an ostream. - virtual void DescribeTo(::std::ostream* os) const = 0; - - // Describes the negation of this matcher to an ostream. - virtual void DescribeNegationTo(::std::ostream* os) const; -}; -``` - -If you need a custom matcher but `Truly()` is not a good option (for -example, you may not be happy with the way `Truly(predicate)` -describes itself, or you may want your matcher to be polymorphic as -`Eq(value)` is), you can define a matcher to do whatever you want in -two steps: first implement the matcher interface, and then define a -factory function to create a matcher instance. The second step is not -strictly needed but it makes the syntax of using the matcher nicer. - -For example, you can define a matcher to test whether an `int` is -divisible by 7 and then use it like this: -``` -using ::testing::MakeMatcher; -using ::testing::Matcher; -using ::testing::MatcherInterface; -using ::testing::MatchResultListener; - -class DivisibleBy7Matcher : public MatcherInterface<int> { - public: - virtual bool MatchAndExplain(int n, MatchResultListener* listener) const { - return (n % 7) == 0; - } - - virtual void DescribeTo(::std::ostream* os) const { - *os << "is divisible by 7"; - } - - virtual void DescribeNegationTo(::std::ostream* os) const { - *os << "is not divisible by 7"; - } -}; - -inline Matcher<int> DivisibleBy7() { - return MakeMatcher(new DivisibleBy7Matcher); -} -... - - EXPECT_CALL(foo, Bar(DivisibleBy7())); -``` - -You may improve the matcher message by streaming additional -information to the `listener` argument in `MatchAndExplain()`: - -``` -class DivisibleBy7Matcher : public MatcherInterface<int> { - public: - virtual bool MatchAndExplain(int n, - MatchResultListener* listener) const { - const int remainder = n % 7; - if (remainder != 0) { - *listener << "the remainder is " << remainder; - } - return remainder == 0; - } - ... -}; -``` - -Then, `EXPECT_THAT(x, DivisibleBy7());` may general a message like this: -``` -Value of: x -Expected: is divisible by 7 - Actual: 23 (the remainder is 2) -``` - -## Writing New Polymorphic Matchers ## - -You've learned how to write your own matchers in the previous -recipe. Just one problem: a matcher created using `MakeMatcher()` only -works for one particular type of arguments. If you want a -_polymorphic_ matcher that works with arguments of several types (for -instance, `Eq(x)` can be used to match a `value` as long as `value` == -`x` compiles -- `value` and `x` don't have to share the same type), -you can learn the trick from `"gmock/gmock-matchers.h"` but it's a bit -involved. - -Fortunately, most of the time you can define a polymorphic matcher -easily with the help of `MakePolymorphicMatcher()`. Here's how you can -define `NotNull()` as an example: - -``` -using ::testing::MakePolymorphicMatcher; -using ::testing::MatchResultListener; -using ::testing::NotNull; -using ::testing::PolymorphicMatcher; - -class NotNullMatcher { - public: - // To implement a polymorphic matcher, first define a COPYABLE class - // that has three members MatchAndExplain(), DescribeTo(), and - // DescribeNegationTo(), like the following. - - // In this example, we want to use NotNull() with any pointer, so - // MatchAndExplain() accepts a pointer of any type as its first argument. - // In general, you can define MatchAndExplain() as an ordinary method or - // a method template, or even overload it. - template <typename T> - bool MatchAndExplain(T* p, - MatchResultListener* /* listener */) const { - return p != NULL; - } - - // Describes the property of a value matching this matcher. - void DescribeTo(::std::ostream* os) const { *os << "is not NULL"; } - - // Describes the property of a value NOT matching this matcher. - void DescribeNegationTo(::std::ostream* os) const { *os << "is NULL"; } -}; - -// To construct a polymorphic matcher, pass an instance of the class -// to MakePolymorphicMatcher(). Note the return type. -inline PolymorphicMatcher<NotNullMatcher> NotNull() { - return MakePolymorphicMatcher(NotNullMatcher()); -} -... - - EXPECT_CALL(foo, Bar(NotNull())); // The argument must be a non-NULL pointer. -``` - -**Note:** Your polymorphic matcher class does **not** need to inherit from -`MatcherInterface` or any other class, and its methods do **not** need -to be virtual. - -Like in a monomorphic matcher, you may explain the match result by -streaming additional information to the `listener` argument in -`MatchAndExplain()`. - -## Writing New Cardinalities ## - -A cardinality is used in `Times()` to tell Google Mock how many times -you expect a call to occur. It doesn't have to be exact. For example, -you can say `AtLeast(5)` or `Between(2, 4)`. - -If the built-in set of cardinalities doesn't suit you, you are free to -define your own by implementing the following interface (in namespace -`testing`): - -``` -class CardinalityInterface { - public: - virtual ~CardinalityInterface(); - - // Returns true iff call_count calls will satisfy this cardinality. - virtual bool IsSatisfiedByCallCount(int call_count) const = 0; - - // Returns true iff call_count calls will saturate this cardinality. - virtual bool IsSaturatedByCallCount(int call_count) const = 0; - - // Describes self to an ostream. - virtual void DescribeTo(::std::ostream* os) const = 0; -}; -``` - -For example, to specify that a call must occur even number of times, -you can write - -``` -using ::testing::Cardinality; -using ::testing::CardinalityInterface; -using ::testing::MakeCardinality; - -class EvenNumberCardinality : public CardinalityInterface { - public: - virtual bool IsSatisfiedByCallCount(int call_count) const { - return (call_count % 2) == 0; - } - - virtual bool IsSaturatedByCallCount(int call_count) const { - return false; - } - - virtual void DescribeTo(::std::ostream* os) const { - *os << "called even number of times"; - } -}; - -Cardinality EvenNumber() { - return MakeCardinality(new EvenNumberCardinality); -} -... - - EXPECT_CALL(foo, Bar(3)) - .Times(EvenNumber()); -``` - -## Writing New Actions Quickly ## - -If the built-in actions don't work for you, and you find it -inconvenient to use `Invoke()`, you can use a macro from the `ACTION*` -family to quickly define a new action that can be used in your code as -if it's a built-in action. - -By writing -``` -ACTION(name) { statements; } -``` -in a namespace scope (i.e. not inside a class or function), you will -define an action with the given name that executes the statements. -The value returned by `statements` will be used as the return value of -the action. Inside the statements, you can refer to the K-th -(0-based) argument of the mock function as `argK`. For example: -``` -ACTION(IncrementArg1) { return ++(*arg1); } -``` -allows you to write -``` -... WillOnce(IncrementArg1()); -``` - -Note that you don't need to specify the types of the mock function -arguments. Rest assured that your code is type-safe though: -you'll get a compiler error if `*arg1` doesn't support the `++` -operator, or if the type of `++(*arg1)` isn't compatible with the mock -function's return type. - -Another example: -``` -ACTION(Foo) { - (*arg2)(5); - Blah(); - *arg1 = 0; - return arg0; -} -``` -defines an action `Foo()` that invokes argument #2 (a function pointer) -with 5, calls function `Blah()`, sets the value pointed to by argument -#1 to 0, and returns argument #0. - -For more convenience and flexibility, you can also use the following -pre-defined symbols in the body of `ACTION`: - -| `argK_type` | The type of the K-th (0-based) argument of the mock function | -|:------------|:-------------------------------------------------------------| -| `args` | All arguments of the mock function as a tuple | -| `args_type` | The type of all arguments of the mock function as a tuple | -| `return_type` | The return type of the mock function | -| `function_type` | The type of the mock function | - -For example, when using an `ACTION` as a stub action for mock function: -``` -int DoSomething(bool flag, int* ptr); -``` -we have: -| **Pre-defined Symbol** | **Is Bound To** | -|:-----------------------|:----------------| -| `arg0` | the value of `flag` | -| `arg0_type` | the type `bool` | -| `arg1` | the value of `ptr` | -| `arg1_type` | the type `int*` | -| `args` | the tuple `(flag, ptr)` | -| `args_type` | the type `std::tr1::tuple<bool, int*>` | -| `return_type` | the type `int` | -| `function_type` | the type `int(bool, int*)` | - -## Writing New Parameterized Actions Quickly ## - -Sometimes you'll want to parameterize an action you define. For that -we have another macro -``` -ACTION_P(name, param) { statements; } -``` - -For example, -``` -ACTION_P(Add, n) { return arg0 + n; } -``` -will allow you to write -``` -// Returns argument #0 + 5. -... WillOnce(Add(5)); -``` - -For convenience, we use the term _arguments_ for the values used to -invoke the mock function, and the term _parameters_ for the values -used to instantiate an action. - -Note that you don't need to provide the type of the parameter either. -Suppose the parameter is named `param`, you can also use the -Google-Mock-defined symbol `param_type` to refer to the type of the -parameter as inferred by the compiler. For example, in the body of -`ACTION_P(Add, n)` above, you can write `n_type` for the type of `n`. - -Google Mock also provides `ACTION_P2`, `ACTION_P3`, and etc to support -multi-parameter actions. For example, -``` -ACTION_P2(ReturnDistanceTo, x, y) { - double dx = arg0 - x; - double dy = arg1 - y; - return sqrt(dx*dx + dy*dy); -} -``` -lets you write -``` -... WillOnce(ReturnDistanceTo(5.0, 26.5)); -``` - -You can view `ACTION` as a degenerated parameterized action where the -number of parameters is 0. - -You can also easily define actions overloaded on the number of parameters: -``` -ACTION_P(Plus, a) { ... } -ACTION_P2(Plus, a, b) { ... } -``` - -## Restricting the Type of an Argument or Parameter in an ACTION ## - -For maximum brevity and reusability, the `ACTION*` macros don't ask -you to provide the types of the mock function arguments and the action -parameters. Instead, we let the compiler infer the types for us. - -Sometimes, however, we may want to be more explicit about the types. -There are several tricks to do that. For example: -``` -ACTION(Foo) { - // Makes sure arg0 can be converted to int. - int n = arg0; - ... use n instead of arg0 here ... -} - -ACTION_P(Bar, param) { - // Makes sure the type of arg1 is const char*. - ::testing::StaticAssertTypeEq<const char*, arg1_type>(); - - // Makes sure param can be converted to bool. - bool flag = param; -} -``` -where `StaticAssertTypeEq` is a compile-time assertion in Google Test -that verifies two types are the same. - -## Writing New Action Templates Quickly ## - -Sometimes you want to give an action explicit template parameters that -cannot be inferred from its value parameters. `ACTION_TEMPLATE()` -supports that and can be viewed as an extension to `ACTION()` and -`ACTION_P*()`. - -The syntax: -``` -ACTION_TEMPLATE(ActionName, - HAS_m_TEMPLATE_PARAMS(kind1, name1, ..., kind_m, name_m), - AND_n_VALUE_PARAMS(p1, ..., p_n)) { statements; } -``` - -defines an action template that takes _m_ explicit template parameters -and _n_ value parameters, where _m_ is between 1 and 10, and _n_ is -between 0 and 10. `name_i` is the name of the i-th template -parameter, and `kind_i` specifies whether it's a `typename`, an -integral constant, or a template. `p_i` is the name of the i-th value -parameter. - -Example: -``` -// DuplicateArg<k, T>(output) converts the k-th argument of the mock -// function to type T and copies it to *output. -ACTION_TEMPLATE(DuplicateArg, - // Note the comma between int and k: - HAS_2_TEMPLATE_PARAMS(int, k, typename, T), - AND_1_VALUE_PARAMS(output)) { - *output = T(std::tr1::get<k>(args)); -} -``` - -To create an instance of an action template, write: -``` - ActionName<t1, ..., t_m>(v1, ..., v_n) -``` -where the `t`s are the template arguments and the -`v`s are the value arguments. The value argument -types are inferred by the compiler. For example: -``` -using ::testing::_; -... - int n; - EXPECT_CALL(mock, Foo(_, _)) - .WillOnce(DuplicateArg<1, unsigned char>(&n)); -``` - -If you want to explicitly specify the value argument types, you can -provide additional template arguments: -``` - ActionName<t1, ..., t_m, u1, ..., u_k>(v1, ..., v_n) -``` -where `u_i` is the desired type of `v_i`. - -`ACTION_TEMPLATE` and `ACTION`/`ACTION_P*` can be overloaded on the -number of value parameters, but not on the number of template -parameters. Without the restriction, the meaning of the following is -unclear: - -``` - OverloadedAction<int, bool>(x); -``` - -Are we using a single-template-parameter action where `bool` refers to -the type of `x`, or a two-template-parameter action where the compiler -is asked to infer the type of `x`? - -## Using the ACTION Object's Type ## - -If you are writing a function that returns an `ACTION` object, you'll -need to know its type. The type depends on the macro used to define -the action and the parameter types. The rule is relatively simple: -| **Given Definition** | **Expression** | **Has Type** | -|:---------------------|:---------------|:-------------| -| `ACTION(Foo)` | `Foo()` | `FooAction` | -| `ACTION_TEMPLATE(Foo, HAS_m_TEMPLATE_PARAMS(...), AND_0_VALUE_PARAMS())` | `Foo<t1, ..., t_m>()` | `FooAction<t1, ..., t_m>` | -| `ACTION_P(Bar, param)` | `Bar(int_value)` | `BarActionP<int>` | -| `ACTION_TEMPLATE(Bar, HAS_m_TEMPLATE_PARAMS(...), AND_1_VALUE_PARAMS(p1))` | `Bar<t1, ..., t_m>(int_value)` | `FooActionP<t1, ..., t_m, int>` | -| `ACTION_P2(Baz, p1, p2)` | `Baz(bool_value, int_value)` | `BazActionP2<bool, int>` | -| `ACTION_TEMPLATE(Baz, HAS_m_TEMPLATE_PARAMS(...), AND_2_VALUE_PARAMS(p1, p2))` | `Baz<t1, ..., t_m>(bool_value, int_value)` | `FooActionP2<t1, ..., t_m, bool, int>` | -| ... | ... | ... | - -Note that we have to pick different suffixes (`Action`, `ActionP`, -`ActionP2`, and etc) for actions with different numbers of value -parameters, or the action definitions cannot be overloaded on the -number of them. - -## Writing New Monomorphic Actions ## - -While the `ACTION*` macros are very convenient, sometimes they are -inappropriate. For example, despite the tricks shown in the previous -recipes, they don't let you directly specify the types of the mock -function arguments and the action parameters, which in general leads -to unoptimized compiler error messages that can baffle unfamiliar -users. They also don't allow overloading actions based on parameter -types without jumping through some hoops. - -An alternative to the `ACTION*` macros is to implement -`::testing::ActionInterface<F>`, where `F` is the type of the mock -function in which the action will be used. For example: - -``` -template <typename F>class ActionInterface { - public: - virtual ~ActionInterface(); - - // Performs the action. Result is the return type of function type - // F, and ArgumentTuple is the tuple of arguments of F. - // - // For example, if F is int(bool, const string&), then Result would - // be int, and ArgumentTuple would be tr1::tuple<bool, const string&>. - virtual Result Perform(const ArgumentTuple& args) = 0; -}; - -using ::testing::_; -using ::testing::Action; -using ::testing::ActionInterface; -using ::testing::MakeAction; - -typedef int IncrementMethod(int*); - -class IncrementArgumentAction : public ActionInterface<IncrementMethod> { - public: - virtual int Perform(const tr1::tuple<int*>& args) { - int* p = tr1::get<0>(args); // Grabs the first argument. - return *p++; - } -}; - -Action<IncrementMethod> IncrementArgument() { - return MakeAction(new IncrementArgumentAction); -} -... - - EXPECT_CALL(foo, Baz(_)) - .WillOnce(IncrementArgument()); - - int n = 5; - foo.Baz(&n); // Should return 5 and change n to 6. -``` - -## Writing New Polymorphic Actions ## - -The previous recipe showed you how to define your own action. This is -all good, except that you need to know the type of the function in -which the action will be used. Sometimes that can be a problem. For -example, if you want to use the action in functions with _different_ -types (e.g. like `Return()` and `SetArgPointee()`). - -If an action can be used in several types of mock functions, we say -it's _polymorphic_. The `MakePolymorphicAction()` function template -makes it easy to define such an action: - -``` -namespace testing { - -template <typename Impl> -PolymorphicAction<Impl> MakePolymorphicAction(const Impl& impl); - -} // namespace testing -``` - -As an example, let's define an action that returns the second argument -in the mock function's argument list. The first step is to define an -implementation class: - -``` -class ReturnSecondArgumentAction { - public: - template <typename Result, typename ArgumentTuple> - Result Perform(const ArgumentTuple& args) const { - // To get the i-th (0-based) argument, use tr1::get<i>(args). - return tr1::get<1>(args); - } -}; -``` - -This implementation class does _not_ need to inherit from any -particular class. What matters is that it must have a `Perform()` -method template. This method template takes the mock function's -arguments as a tuple in a **single** argument, and returns the result of -the action. It can be either `const` or not, but must be invokable -with exactly one template argument, which is the result type. In other -words, you must be able to call `Perform<R>(args)` where `R` is the -mock function's return type and `args` is its arguments in a tuple. - -Next, we use `MakePolymorphicAction()` to turn an instance of the -implementation class into the polymorphic action we need. It will be -convenient to have a wrapper for this: - -``` -using ::testing::MakePolymorphicAction; -using ::testing::PolymorphicAction; - -PolymorphicAction<ReturnSecondArgumentAction> ReturnSecondArgument() { - return MakePolymorphicAction(ReturnSecondArgumentAction()); -} -``` - -Now, you can use this polymorphic action the same way you use the -built-in ones: - -``` -using ::testing::_; - -class MockFoo : public Foo { - public: - MOCK_METHOD2(DoThis, int(bool flag, int n)); - MOCK_METHOD3(DoThat, string(int x, const char* str1, const char* str2)); -}; -... - - MockFoo foo; - EXPECT_CALL(foo, DoThis(_, _)) - .WillOnce(ReturnSecondArgument()); - EXPECT_CALL(foo, DoThat(_, _, _)) - .WillOnce(ReturnSecondArgument()); - ... - foo.DoThis(true, 5); // Will return 5. - foo.DoThat(1, "Hi", "Bye"); // Will return "Hi". -``` - -## Teaching Google Mock How to Print Your Values ## - -When an uninteresting or unexpected call occurs, Google Mock prints the -argument values and the stack trace to help you debug. Assertion -macros like `EXPECT_THAT` and `EXPECT_EQ` also print the values in -question when the assertion fails. Google Mock and Google Test do this using -Google Test's user-extensible value printer. - -This printer knows how to print built-in C++ types, native arrays, STL -containers, and any type that supports the `<<` operator. For other -types, it prints the raw bytes in the value and hopes that you the -user can figure it out. -[Google Test's advanced guide](http://code.google.com/p/googletest/wiki/AdvancedGuide#Teaching_Google_Test_How_to_Print_Your_Values) -explains how to extend the printer to do a better job at -printing your particular type than to dump the bytes.
\ No newline at end of file diff --git a/googlemock/docs/v1_7/Documentation.md b/googlemock/docs/v1_7/Documentation.md deleted file mode 100644 index d9181f2..0000000 --- a/googlemock/docs/v1_7/Documentation.md +++ /dev/null @@ -1,12 +0,0 @@ -This page lists all documentation wiki pages for Google Mock **(the SVN trunk version)** -- **if you use a released version of Google Mock, please read the documentation for that specific version instead.** - - * [ForDummies](V1_7_ForDummies.md) -- start here if you are new to Google Mock. - * [CheatSheet](V1_7_CheatSheet.md) -- a quick reference. - * [CookBook](V1_7_CookBook.md) -- recipes for doing various tasks using Google Mock. - * [FrequentlyAskedQuestions](V1_7_FrequentlyAskedQuestions.md) -- check here before asking a question on the mailing list. - -To contribute code to Google Mock, read: - - * [DevGuide](DevGuide.md) -- read this _before_ writing your first patch. - * [Pump Manual](http://code.google.com/p/googletest/wiki/PumpManual) -- how we generate some of Google Mock's source files.
\ No newline at end of file diff --git a/googlemock/docs/v1_7/ForDummies.md b/googlemock/docs/v1_7/ForDummies.md deleted file mode 100644 index ee03c5b..0000000 --- a/googlemock/docs/v1_7/ForDummies.md +++ /dev/null @@ -1,439 +0,0 @@ - - -(**Note:** If you get compiler errors that you don't understand, be sure to consult [Google Mock Doctor](http://code.google.com/p/googlemock/wiki/V1_7_FrequentlyAskedQuestions#How_am_I_supposed_to_make_sense_of_these_horrible_template_error).) - -# What Is Google C++ Mocking Framework? # -When you write a prototype or test, often it's not feasible or wise to rely on real objects entirely. A **mock object** implements the same interface as a real object (so it can be used as one), but lets you specify at run time how it will be used and what it should do (which methods will be called? in which order? how many times? with what arguments? what will they return? etc). - -**Note:** It is easy to confuse the term _fake objects_ with mock objects. Fakes and mocks actually mean very different things in the Test-Driven Development (TDD) community: - - * **Fake** objects have working implementations, but usually take some shortcut (perhaps to make the operations less expensive), which makes them not suitable for production. An in-memory file system would be an example of a fake. - * **Mocks** are objects pre-programmed with _expectations_, which form a specification of the calls they are expected to receive. - -If all this seems too abstract for you, don't worry - the most important thing to remember is that a mock allows you to check the _interaction_ between itself and code that uses it. The difference between fakes and mocks will become much clearer once you start to use mocks. - -**Google C++ Mocking Framework** (or **Google Mock** for short) is a library (sometimes we also call it a "framework" to make it sound cool) for creating mock classes and using them. It does to C++ what [jMock](http://www.jmock.org/) and [EasyMock](http://www.easymock.org/) do to Java. - -Using Google Mock involves three basic steps: - - 1. Use some simple macros to describe the interface you want to mock, and they will expand to the implementation of your mock class; - 1. Create some mock objects and specify its expectations and behavior using an intuitive syntax; - 1. Exercise code that uses the mock objects. Google Mock will catch any violation of the expectations as soon as it arises. - -# Why Google Mock? # -While mock objects help you remove unnecessary dependencies in tests and make them fast and reliable, using mocks manually in C++ is _hard_: - - * Someone has to implement the mocks. The job is usually tedious and error-prone. No wonder people go great distance to avoid it. - * The quality of those manually written mocks is a bit, uh, unpredictable. You may see some really polished ones, but you may also see some that were hacked up in a hurry and have all sorts of ad hoc restrictions. - * The knowledge you gained from using one mock doesn't transfer to the next. - -In contrast, Java and Python programmers have some fine mock frameworks, which automate the creation of mocks. As a result, mocking is a proven effective technique and widely adopted practice in those communities. Having the right tool absolutely makes the difference. - -Google Mock was built to help C++ programmers. It was inspired by [jMock](http://www.jmock.org/) and [EasyMock](http://www.easymock.org/), but designed with C++'s specifics in mind. It is your friend if any of the following problems is bothering you: - - * You are stuck with a sub-optimal design and wish you had done more prototyping before it was too late, but prototyping in C++ is by no means "rapid". - * Your tests are slow as they depend on too many libraries or use expensive resources (e.g. a database). - * Your tests are brittle as some resources they use are unreliable (e.g. the network). - * You want to test how your code handles a failure (e.g. a file checksum error), but it's not easy to cause one. - * You need to make sure that your module interacts with other modules in the right way, but it's hard to observe the interaction; therefore you resort to observing the side effects at the end of the action, which is awkward at best. - * You want to "mock out" your dependencies, except that they don't have mock implementations yet; and, frankly, you aren't thrilled by some of those hand-written mocks. - -We encourage you to use Google Mock as: - - * a _design_ tool, for it lets you experiment with your interface design early and often. More iterations lead to better designs! - * a _testing_ tool to cut your tests' outbound dependencies and probe the interaction between your module and its collaborators. - -# Getting Started # -Using Google Mock is easy! Inside your C++ source file, just `#include` `"gtest/gtest.h"` and `"gmock/gmock.h"`, and you are ready to go. - -# A Case for Mock Turtles # -Let's look at an example. Suppose you are developing a graphics program that relies on a LOGO-like API for drawing. How would you test that it does the right thing? Well, you can run it and compare the screen with a golden screen snapshot, but let's admit it: tests like this are expensive to run and fragile (What if you just upgraded to a shiny new graphics card that has better anti-aliasing? Suddenly you have to update all your golden images.). It would be too painful if all your tests are like this. Fortunately, you learned about Dependency Injection and know the right thing to do: instead of having your application talk to the drawing API directly, wrap the API in an interface (say, `Turtle`) and code to that interface: - -``` -class Turtle { - ... - virtual ~Turtle() {} - virtual void PenUp() = 0; - virtual void PenDown() = 0; - virtual void Forward(int distance) = 0; - virtual void Turn(int degrees) = 0; - virtual void GoTo(int x, int y) = 0; - virtual int GetX() const = 0; - virtual int GetY() const = 0; -}; -``` - -(Note that the destructor of `Turtle` **must** be virtual, as is the case for **all** classes you intend to inherit from - otherwise the destructor of the derived class will not be called when you delete an object through a base pointer, and you'll get corrupted program states like memory leaks.) - -You can control whether the turtle's movement will leave a trace using `PenUp()` and `PenDown()`, and control its movement using `Forward()`, `Turn()`, and `GoTo()`. Finally, `GetX()` and `GetY()` tell you the current position of the turtle. - -Your program will normally use a real implementation of this interface. In tests, you can use a mock implementation instead. This allows you to easily check what drawing primitives your program is calling, with what arguments, and in which order. Tests written this way are much more robust (they won't break because your new machine does anti-aliasing differently), easier to read and maintain (the intent of a test is expressed in the code, not in some binary images), and run _much, much faster_. - -# Writing the Mock Class # -If you are lucky, the mocks you need to use have already been implemented by some nice people. If, however, you find yourself in the position to write a mock class, relax - Google Mock turns this task into a fun game! (Well, almost.) - -## How to Define It ## -Using the `Turtle` interface as example, here are the simple steps you need to follow: - - 1. Derive a class `MockTurtle` from `Turtle`. - 1. Take a _virtual_ function of `Turtle` (while it's possible to [mock non-virtual methods using templates](http://code.google.com/p/googlemock/wiki/V1_7_CookBook#Mocking_Nonvirtual_Methods), it's much more involved). Count how many arguments it has. - 1. In the `public:` section of the child class, write `MOCK_METHODn();` (or `MOCK_CONST_METHODn();` if you are mocking a `const` method), where `n` is the number of the arguments; if you counted wrong, shame on you, and a compiler error will tell you so. - 1. Now comes the fun part: you take the function signature, cut-and-paste the _function name_ as the _first_ argument to the macro, and leave what's left as the _second_ argument (in case you're curious, this is the _type of the function_). - 1. Repeat until all virtual functions you want to mock are done. - -After the process, you should have something like: - -``` -#include "gmock/gmock.h" // Brings in Google Mock. -class MockTurtle : public Turtle { - public: - ... - MOCK_METHOD0(PenUp, void()); - MOCK_METHOD0(PenDown, void()); - MOCK_METHOD1(Forward, void(int distance)); - MOCK_METHOD1(Turn, void(int degrees)); - MOCK_METHOD2(GoTo, void(int x, int y)); - MOCK_CONST_METHOD0(GetX, int()); - MOCK_CONST_METHOD0(GetY, int()); -}; -``` - -You don't need to define these mock methods somewhere else - the `MOCK_METHOD*` macros will generate the definitions for you. It's that simple! Once you get the hang of it, you can pump out mock classes faster than your source-control system can handle your check-ins. - -**Tip:** If even this is too much work for you, you'll find the -`gmock_gen.py` tool in Google Mock's `scripts/generator/` directory (courtesy of the [cppclean](http://code.google.com/p/cppclean/) project) useful. This command-line -tool requires that you have Python 2.4 installed. You give it a C++ file and the name of an abstract class defined in it, -and it will print the definition of the mock class for you. Due to the -complexity of the C++ language, this script may not always work, but -it can be quite handy when it does. For more details, read the [user documentation](http://code.google.com/p/googlemock/source/browse/trunk/scripts/generator/README). - -## Where to Put It ## -When you define a mock class, you need to decide where to put its definition. Some people put it in a `*_test.cc`. This is fine when the interface being mocked (say, `Foo`) is owned by the same person or team. Otherwise, when the owner of `Foo` changes it, your test could break. (You can't really expect `Foo`'s maintainer to fix every test that uses `Foo`, can you?) - -So, the rule of thumb is: if you need to mock `Foo` and it's owned by others, define the mock class in `Foo`'s package (better, in a `testing` sub-package such that you can clearly separate production code and testing utilities), and put it in a `mock_foo.h`. Then everyone can reference `mock_foo.h` from their tests. If `Foo` ever changes, there is only one copy of `MockFoo` to change, and only tests that depend on the changed methods need to be fixed. - -Another way to do it: you can introduce a thin layer `FooAdaptor` on top of `Foo` and code to this new interface. Since you own `FooAdaptor`, you can absorb changes in `Foo` much more easily. While this is more work initially, carefully choosing the adaptor interface can make your code easier to write and more readable (a net win in the long run), as you can choose `FooAdaptor` to fit your specific domain much better than `Foo` does. - -# Using Mocks in Tests # -Once you have a mock class, using it is easy. The typical work flow is: - - 1. Import the Google Mock names from the `testing` namespace such that you can use them unqualified (You only have to do it once per file. Remember that namespaces are a good idea and good for your health.). - 1. Create some mock objects. - 1. Specify your expectations on them (How many times will a method be called? With what arguments? What should it do? etc.). - 1. Exercise some code that uses the mocks; optionally, check the result using Google Test assertions. If a mock method is called more than expected or with wrong arguments, you'll get an error immediately. - 1. When a mock is destructed, Google Mock will automatically check whether all expectations on it have been satisfied. - -Here's an example: - -``` -#include "path/to/mock-turtle.h" -#include "gmock/gmock.h" -#include "gtest/gtest.h" -using ::testing::AtLeast; // #1 - -TEST(PainterTest, CanDrawSomething) { - MockTurtle turtle; // #2 - EXPECT_CALL(turtle, PenDown()) // #3 - .Times(AtLeast(1)); - - Painter painter(&turtle); // #4 - - EXPECT_TRUE(painter.DrawCircle(0, 0, 10)); -} // #5 - -int main(int argc, char** argv) { - // The following line must be executed to initialize Google Mock - // (and Google Test) before running the tests. - ::testing::InitGoogleMock(&argc, argv); - return RUN_ALL_TESTS(); -} -``` - -As you might have guessed, this test checks that `PenDown()` is called at least once. If the `painter` object didn't call this method, your test will fail with a message like this: - -``` -path/to/my_test.cc:119: Failure -Actual function call count doesn't match this expectation: -Actually: never called; -Expected: called at least once. -``` - -**Tip 1:** If you run the test from an Emacs buffer, you can hit `<Enter>` on the line number displayed in the error message to jump right to the failed expectation. - -**Tip 2:** If your mock objects are never deleted, the final verification won't happen. Therefore it's a good idea to use a heap leak checker in your tests when you allocate mocks on the heap. - -**Important note:** Google Mock requires expectations to be set **before** the mock functions are called, otherwise the behavior is **undefined**. In particular, you mustn't interleave `EXPECT_CALL()`s and calls to the mock functions. - -This means `EXPECT_CALL()` should be read as expecting that a call will occur _in the future_, not that a call has occurred. Why does Google Mock work like that? Well, specifying the expectation beforehand allows Google Mock to report a violation as soon as it arises, when the context (stack trace, etc) is still available. This makes debugging much easier. - -Admittedly, this test is contrived and doesn't do much. You can easily achieve the same effect without using Google Mock. However, as we shall reveal soon, Google Mock allows you to do _much more_ with the mocks. - -## Using Google Mock with Any Testing Framework ## -If you want to use something other than Google Test (e.g. [CppUnit](http://apps.sourceforge.net/mediawiki/cppunit/index.php?title=Main_Page) or -[CxxTest](http://cxxtest.tigris.org/)) as your testing framework, just change the `main()` function in the previous section to: -``` -int main(int argc, char** argv) { - // The following line causes Google Mock to throw an exception on failure, - // which will be interpreted by your testing framework as a test failure. - ::testing::GTEST_FLAG(throw_on_failure) = true; - ::testing::InitGoogleMock(&argc, argv); - ... whatever your testing framework requires ... -} -``` - -This approach has a catch: it makes Google Mock throw an exception -from a mock object's destructor sometimes. With some compilers, this -sometimes causes the test program to crash. You'll still be able to -notice that the test has failed, but it's not a graceful failure. - -A better solution is to use Google Test's -[event listener API](http://code.google.com/p/googletest/wiki/AdvancedGuide#Extending_Google_Test_by_Handling_Test_Events) -to report a test failure to your testing framework properly. You'll need to -implement the `OnTestPartResult()` method of the event listener interface, but it -should be straightforward. - -If this turns out to be too much work, we suggest that you stick with -Google Test, which works with Google Mock seamlessly (in fact, it is -technically part of Google Mock.). If there is a reason that you -cannot use Google Test, please let us know. - -# Setting Expectations # -The key to using a mock object successfully is to set the _right expectations_ on it. If you set the expectations too strict, your test will fail as the result of unrelated changes. If you set them too loose, bugs can slip through. You want to do it just right such that your test can catch exactly the kind of bugs you intend it to catch. Google Mock provides the necessary means for you to do it "just right." - -## General Syntax ## -In Google Mock we use the `EXPECT_CALL()` macro to set an expectation on a mock method. The general syntax is: - -``` -EXPECT_CALL(mock_object, method(matchers)) - .Times(cardinality) - .WillOnce(action) - .WillRepeatedly(action); -``` - -The macro has two arguments: first the mock object, and then the method and its arguments. Note that the two are separated by a comma (`,`), not a period (`.`). (Why using a comma? The answer is that it was necessary for technical reasons.) - -The macro can be followed by some optional _clauses_ that provide more information about the expectation. We'll discuss how each clause works in the coming sections. - -This syntax is designed to make an expectation read like English. For example, you can probably guess that - -``` -using ::testing::Return;... -EXPECT_CALL(turtle, GetX()) - .Times(5) - .WillOnce(Return(100)) - .WillOnce(Return(150)) - .WillRepeatedly(Return(200)); -``` - -says that the `turtle` object's `GetX()` method will be called five times, it will return 100 the first time, 150 the second time, and then 200 every time. Some people like to call this style of syntax a Domain-Specific Language (DSL). - -**Note:** Why do we use a macro to do this? It serves two purposes: first it makes expectations easily identifiable (either by `grep` or by a human reader), and second it allows Google Mock to include the source file location of a failed expectation in messages, making debugging easier. - -## Matchers: What Arguments Do We Expect? ## -When a mock function takes arguments, we must specify what arguments we are expecting; for example: - -``` -// Expects the turtle to move forward by 100 units. -EXPECT_CALL(turtle, Forward(100)); -``` - -Sometimes you may not want to be too specific (Remember that talk about tests being too rigid? Over specification leads to brittle tests and obscures the intent of tests. Therefore we encourage you to specify only what's necessary - no more, no less.). If you care to check that `Forward()` will be called but aren't interested in its actual argument, write `_` as the argument, which means "anything goes": - -``` -using ::testing::_; -... -// Expects the turtle to move forward. -EXPECT_CALL(turtle, Forward(_)); -``` - -`_` is an instance of what we call **matchers**. A matcher is like a predicate and can test whether an argument is what we'd expect. You can use a matcher inside `EXPECT_CALL()` wherever a function argument is expected. - -A list of built-in matchers can be found in the [CheatSheet](V1_7_CheatSheet.md). For example, here's the `Ge` (greater than or equal) matcher: - -``` -using ::testing::Ge;... -EXPECT_CALL(turtle, Forward(Ge(100))); -``` - -This checks that the turtle will be told to go forward by at least 100 units. - -## Cardinalities: How Many Times Will It Be Called? ## -The first clause we can specify following an `EXPECT_CALL()` is `Times()`. We call its argument a **cardinality** as it tells _how many times_ the call should occur. It allows us to repeat an expectation many times without actually writing it as many times. More importantly, a cardinality can be "fuzzy", just like a matcher can be. This allows a user to express the intent of a test exactly. - -An interesting special case is when we say `Times(0)`. You may have guessed - it means that the function shouldn't be called with the given arguments at all, and Google Mock will report a Google Test failure whenever the function is (wrongfully) called. - -We've seen `AtLeast(n)` as an example of fuzzy cardinalities earlier. For the list of built-in cardinalities you can use, see the [CheatSheet](V1_7_CheatSheet.md). - -The `Times()` clause can be omitted. **If you omit `Times()`, Google Mock will infer the cardinality for you.** The rules are easy to remember: - - * If **neither** `WillOnce()` **nor** `WillRepeatedly()` is in the `EXPECT_CALL()`, the inferred cardinality is `Times(1)`. - * If there are `n WillOnce()`'s but **no** `WillRepeatedly()`, where `n` >= 1, the cardinality is `Times(n)`. - * If there are `n WillOnce()`'s and **one** `WillRepeatedly()`, where `n` >= 0, the cardinality is `Times(AtLeast(n))`. - -**Quick quiz:** what do you think will happen if a function is expected to be called twice but actually called four times? - -## Actions: What Should It Do? ## -Remember that a mock object doesn't really have a working implementation? We as users have to tell it what to do when a method is invoked. This is easy in Google Mock. - -First, if the return type of a mock function is a built-in type or a pointer, the function has a **default action** (a `void` function will just return, a `bool` function will return `false`, and other functions will return 0). If you don't say anything, this behavior will be used. - -Second, if a mock function doesn't have a default action, or the default action doesn't suit you, you can specify the action to be taken each time the expectation matches using a series of `WillOnce()` clauses followed by an optional `WillRepeatedly()`. For example, - -``` -using ::testing::Return;... -EXPECT_CALL(turtle, GetX()) - .WillOnce(Return(100)) - .WillOnce(Return(200)) - .WillOnce(Return(300)); -``` - -This says that `turtle.GetX()` will be called _exactly three times_ (Google Mock inferred this from how many `WillOnce()` clauses we've written, since we didn't explicitly write `Times()`), and will return 100, 200, and 300 respectively. - -``` -using ::testing::Return;... -EXPECT_CALL(turtle, GetY()) - .WillOnce(Return(100)) - .WillOnce(Return(200)) - .WillRepeatedly(Return(300)); -``` - -says that `turtle.GetY()` will be called _at least twice_ (Google Mock knows this as we've written two `WillOnce()` clauses and a `WillRepeatedly()` while having no explicit `Times()`), will return 100 the first time, 200 the second time, and 300 from the third time on. - -Of course, if you explicitly write a `Times()`, Google Mock will not try to infer the cardinality itself. What if the number you specified is larger than there are `WillOnce()` clauses? Well, after all `WillOnce()`s are used up, Google Mock will do the _default_ action for the function every time (unless, of course, you have a `WillRepeatedly()`.). - -What can we do inside `WillOnce()` besides `Return()`? You can return a reference using `ReturnRef(variable)`, or invoke a pre-defined function, among [others](http://code.google.com/p/googlemock/wiki/V1_7_CheatSheet#Actions). - -**Important note:** The `EXPECT_CALL()` statement evaluates the action clause only once, even though the action may be performed many times. Therefore you must be careful about side effects. The following may not do what you want: - -``` -int n = 100; -EXPECT_CALL(turtle, GetX()) -.Times(4) -.WillRepeatedly(Return(n++)); -``` - -Instead of returning 100, 101, 102, ..., consecutively, this mock function will always return 100 as `n++` is only evaluated once. Similarly, `Return(new Foo)` will create a new `Foo` object when the `EXPECT_CALL()` is executed, and will return the same pointer every time. If you want the side effect to happen every time, you need to define a custom action, which we'll teach in the [CookBook](V1_7_CookBook.md). - -Time for another quiz! What do you think the following means? - -``` -using ::testing::Return;... -EXPECT_CALL(turtle, GetY()) -.Times(4) -.WillOnce(Return(100)); -``` - -Obviously `turtle.GetY()` is expected to be called four times. But if you think it will return 100 every time, think twice! Remember that one `WillOnce()` clause will be consumed each time the function is invoked and the default action will be taken afterwards. So the right answer is that `turtle.GetY()` will return 100 the first time, but **return 0 from the second time on**, as returning 0 is the default action for `int` functions. - -## Using Multiple Expectations ## -So far we've only shown examples where you have a single expectation. More realistically, you're going to specify expectations on multiple mock methods, which may be from multiple mock objects. - -By default, when a mock method is invoked, Google Mock will search the expectations in the **reverse order** they are defined, and stop when an active expectation that matches the arguments is found (you can think of it as "newer rules override older ones."). If the matching expectation cannot take any more calls, you will get an upper-bound-violated failure. Here's an example: - -``` -using ::testing::_;... -EXPECT_CALL(turtle, Forward(_)); // #1 -EXPECT_CALL(turtle, Forward(10)) // #2 - .Times(2); -``` - -If `Forward(10)` is called three times in a row, the third time it will be an error, as the last matching expectation (#2) has been saturated. If, however, the third `Forward(10)` call is replaced by `Forward(20)`, then it would be OK, as now #1 will be the matching expectation. - -**Side note:** Why does Google Mock search for a match in the _reverse_ order of the expectations? The reason is that this allows a user to set up the default expectations in a mock object's constructor or the test fixture's set-up phase and then customize the mock by writing more specific expectations in the test body. So, if you have two expectations on the same method, you want to put the one with more specific matchers **after** the other, or the more specific rule would be shadowed by the more general one that comes after it. - -## Ordered vs Unordered Calls ## -By default, an expectation can match a call even though an earlier expectation hasn't been satisfied. In other words, the calls don't have to occur in the order the expectations are specified. - -Sometimes, you may want all the expected calls to occur in a strict order. To say this in Google Mock is easy: - -``` -using ::testing::InSequence;... -TEST(FooTest, DrawsLineSegment) { - ... - { - InSequence dummy; - - EXPECT_CALL(turtle, PenDown()); - EXPECT_CALL(turtle, Forward(100)); - EXPECT_CALL(turtle, PenUp()); - } - Foo(); -} -``` - -By creating an object of type `InSequence`, all expectations in its scope are put into a _sequence_ and have to occur _sequentially_. Since we are just relying on the constructor and destructor of this object to do the actual work, its name is really irrelevant. - -In this example, we test that `Foo()` calls the three expected functions in the order as written. If a call is made out-of-order, it will be an error. - -(What if you care about the relative order of some of the calls, but not all of them? Can you specify an arbitrary partial order? The answer is ... yes! If you are impatient, the details can be found in the [CookBook](V1_7_CookBook#Expecting_Partially_Ordered_Calls.md).) - -## All Expectations Are Sticky (Unless Said Otherwise) ## -Now let's do a quick quiz to see how well you can use this mock stuff already. How would you test that the turtle is asked to go to the origin _exactly twice_ (you want to ignore any other instructions it receives)? - -After you've come up with your answer, take a look at ours and compare notes (solve it yourself first - don't cheat!): - -``` -using ::testing::_;... -EXPECT_CALL(turtle, GoTo(_, _)) // #1 - .Times(AnyNumber()); -EXPECT_CALL(turtle, GoTo(0, 0)) // #2 - .Times(2); -``` - -Suppose `turtle.GoTo(0, 0)` is called three times. In the third time, Google Mock will see that the arguments match expectation #2 (remember that we always pick the last matching expectation). Now, since we said that there should be only two such calls, Google Mock will report an error immediately. This is basically what we've told you in the "Using Multiple Expectations" section above. - -This example shows that **expectations in Google Mock are "sticky" by default**, in the sense that they remain active even after we have reached their invocation upper bounds. This is an important rule to remember, as it affects the meaning of the spec, and is **different** to how it's done in many other mocking frameworks (Why'd we do that? Because we think our rule makes the common cases easier to express and understand.). - -Simple? Let's see if you've really understood it: what does the following code say? - -``` -using ::testing::Return; -... -for (int i = n; i > 0; i--) { - EXPECT_CALL(turtle, GetX()) - .WillOnce(Return(10*i)); -} -``` - -If you think it says that `turtle.GetX()` will be called `n` times and will return 10, 20, 30, ..., consecutively, think twice! The problem is that, as we said, expectations are sticky. So, the second time `turtle.GetX()` is called, the last (latest) `EXPECT_CALL()` statement will match, and will immediately lead to an "upper bound exceeded" error - this piece of code is not very useful! - -One correct way of saying that `turtle.GetX()` will return 10, 20, 30, ..., is to explicitly say that the expectations are _not_ sticky. In other words, they should _retire_ as soon as they are saturated: - -``` -using ::testing::Return; -... -for (int i = n; i > 0; i--) { - EXPECT_CALL(turtle, GetX()) - .WillOnce(Return(10*i)) - .RetiresOnSaturation(); -} -``` - -And, there's a better way to do it: in this case, we expect the calls to occur in a specific order, and we line up the actions to match the order. Since the order is important here, we should make it explicit using a sequence: - -``` -using ::testing::InSequence; -using ::testing::Return; -... -{ - InSequence s; - - for (int i = 1; i <= n; i++) { - EXPECT_CALL(turtle, GetX()) - .WillOnce(Return(10*i)) - .RetiresOnSaturation(); - } -} -``` - -By the way, the other situation where an expectation may _not_ be sticky is when it's in a sequence - as soon as another expectation that comes after it in the sequence has been used, it automatically retires (and will never be used to match any call). - -## Uninteresting Calls ## -A mock object may have many methods, and not all of them are that interesting. For example, in some tests we may not care about how many times `GetX()` and `GetY()` get called. - -In Google Mock, if you are not interested in a method, just don't say anything about it. If a call to this method occurs, you'll see a warning in the test output, but it won't be a failure. - -# What Now? # -Congratulations! You've learned enough about Google Mock to start using it. Now, you might want to join the [googlemock](http://groups.google.com/group/googlemock) discussion group and actually write some tests using Google Mock - it will be fun. Hey, it may even be addictive - you've been warned. - -Then, if you feel like increasing your mock quotient, you should move on to the [CookBook](V1_7_CookBook.md). You can learn many advanced features of Google Mock there -- and advance your level of enjoyment and testing bliss.
\ No newline at end of file diff --git a/googlemock/docs/v1_7/FrequentlyAskedQuestions.md b/googlemock/docs/v1_7/FrequentlyAskedQuestions.md deleted file mode 100644 index fa21233..0000000 --- a/googlemock/docs/v1_7/FrequentlyAskedQuestions.md +++ /dev/null @@ -1,628 +0,0 @@ - - -Please send your questions to the -[googlemock](http://groups.google.com/group/googlemock) discussion -group. If you need help with compiler errors, make sure you have -tried [Google Mock Doctor](#How_am_I_supposed_to_make_sense_of_these_horrible_template_error.md) first. - -## When I call a method on my mock object, the method for the real object is invoked instead. What's the problem? ## - -In order for a method to be mocked, it must be _virtual_, unless you use the [high-perf dependency injection technique](http://code.google.com/p/googlemock/wiki/V1_7_CookBook#Mocking_Nonvirtual_Methods). - -## I wrote some matchers. After I upgraded to a new version of Google Mock, they no longer compile. What's going on? ## - -After version 1.4.0 of Google Mock was released, we had an idea on how -to make it easier to write matchers that can generate informative -messages efficiently. We experimented with this idea and liked what -we saw. Therefore we decided to implement it. - -Unfortunately, this means that if you have defined your own matchers -by implementing `MatcherInterface` or using `MakePolymorphicMatcher()`, -your definitions will no longer compile. Matchers defined using the -`MATCHER*` family of macros are not affected. - -Sorry for the hassle if your matchers are affected. We believe it's -in everyone's long-term interest to make this change sooner than -later. Fortunately, it's usually not hard to migrate an existing -matcher to the new API. Here's what you need to do: - -If you wrote your matcher like this: -``` -// Old matcher definition that doesn't work with the latest -// Google Mock. -using ::testing::MatcherInterface; -... -class MyWonderfulMatcher : public MatcherInterface<MyType> { - public: - ... - virtual bool Matches(MyType value) const { - // Returns true if value matches. - return value.GetFoo() > 5; - } - ... -}; -``` - -you'll need to change it to: -``` -// New matcher definition that works with the latest Google Mock. -using ::testing::MatcherInterface; -using ::testing::MatchResultListener; -... -class MyWonderfulMatcher : public MatcherInterface<MyType> { - public: - ... - virtual bool MatchAndExplain(MyType value, - MatchResultListener* listener) const { - // Returns true if value matches. - return value.GetFoo() > 5; - } - ... -}; -``` -(i.e. rename `Matches()` to `MatchAndExplain()` and give it a second -argument of type `MatchResultListener*`.) - -If you were also using `ExplainMatchResultTo()` to improve the matcher -message: -``` -// Old matcher definition that doesn't work with the lastest -// Google Mock. -using ::testing::MatcherInterface; -... -class MyWonderfulMatcher : public MatcherInterface<MyType> { - public: - ... - virtual bool Matches(MyType value) const { - // Returns true if value matches. - return value.GetFoo() > 5; - } - - virtual void ExplainMatchResultTo(MyType value, - ::std::ostream* os) const { - // Prints some helpful information to os to help - // a user understand why value matches (or doesn't match). - *os << "the Foo property is " << value.GetFoo(); - } - ... -}; -``` - -you should move the logic of `ExplainMatchResultTo()` into -`MatchAndExplain()`, using the `MatchResultListener` argument where -the `::std::ostream` was used: -``` -// New matcher definition that works with the latest Google Mock. -using ::testing::MatcherInterface; -using ::testing::MatchResultListener; -... -class MyWonderfulMatcher : public MatcherInterface<MyType> { - public: - ... - virtual bool MatchAndExplain(MyType value, - MatchResultListener* listener) const { - // Returns true if value matches. - *listener << "the Foo property is " << value.GetFoo(); - return value.GetFoo() > 5; - } - ... -}; -``` - -If your matcher is defined using `MakePolymorphicMatcher()`: -``` -// Old matcher definition that doesn't work with the latest -// Google Mock. -using ::testing::MakePolymorphicMatcher; -... -class MyGreatMatcher { - public: - ... - bool Matches(MyType value) const { - // Returns true if value matches. - return value.GetBar() < 42; - } - ... -}; -... MakePolymorphicMatcher(MyGreatMatcher()) ... -``` - -you should rename the `Matches()` method to `MatchAndExplain()` and -add a `MatchResultListener*` argument (the same as what you need to do -for matchers defined by implementing `MatcherInterface`): -``` -// New matcher definition that works with the latest Google Mock. -using ::testing::MakePolymorphicMatcher; -using ::testing::MatchResultListener; -... -class MyGreatMatcher { - public: - ... - bool MatchAndExplain(MyType value, - MatchResultListener* listener) const { - // Returns true if value matches. - return value.GetBar() < 42; - } - ... -}; -... MakePolymorphicMatcher(MyGreatMatcher()) ... -``` - -If your polymorphic matcher uses `ExplainMatchResultTo()` for better -failure messages: -``` -// Old matcher definition that doesn't work with the latest -// Google Mock. -using ::testing::MakePolymorphicMatcher; -... -class MyGreatMatcher { - public: - ... - bool Matches(MyType value) const { - // Returns true if value matches. - return value.GetBar() < 42; - } - ... -}; -void ExplainMatchResultTo(const MyGreatMatcher& matcher, - MyType value, - ::std::ostream* os) { - // Prints some helpful information to os to help - // a user understand why value matches (or doesn't match). - *os << "the Bar property is " << value.GetBar(); -} -... MakePolymorphicMatcher(MyGreatMatcher()) ... -``` - -you'll need to move the logic inside `ExplainMatchResultTo()` to -`MatchAndExplain()`: -``` -// New matcher definition that works with the latest Google Mock. -using ::testing::MakePolymorphicMatcher; -using ::testing::MatchResultListener; -... -class MyGreatMatcher { - public: - ... - bool MatchAndExplain(MyType value, - MatchResultListener* listener) const { - // Returns true if value matches. - *listener << "the Bar property is " << value.GetBar(); - return value.GetBar() < 42; - } - ... -}; -... MakePolymorphicMatcher(MyGreatMatcher()) ... -``` - -For more information, you can read these -[two](http://code.google.com/p/googlemock/wiki/V1_7_CookBook#Writing_New_Monomorphic_Matchers) -[recipes](http://code.google.com/p/googlemock/wiki/V1_7_CookBook#Writing_New_Polymorphic_Matchers) -from the cookbook. As always, you -are welcome to post questions on `googlemock@googlegroups.com` if you -need any help. - -## When using Google Mock, do I have to use Google Test as the testing framework? I have my favorite testing framework and don't want to switch. ## - -Google Mock works out of the box with Google Test. However, it's easy -to configure it to work with any testing framework of your choice. -[Here](http://code.google.com/p/googlemock/wiki/V1_7_ForDummies#Using_Google_Mock_with_Any_Testing_Framework) is how. - -## How am I supposed to make sense of these horrible template errors? ## - -If you are confused by the compiler errors gcc threw at you, -try consulting the _Google Mock Doctor_ tool first. What it does is to -scan stdin for gcc error messages, and spit out diagnoses on the -problems (we call them diseases) your code has. - -To "install", run command: -``` -alias gmd='<path to googlemock>/scripts/gmock_doctor.py' -``` - -To use it, do: -``` -<your-favorite-build-command> <your-test> 2>&1 | gmd -``` - -For example: -``` -make my_test 2>&1 | gmd -``` - -Or you can run `gmd` and copy-n-paste gcc's error messages to it. - -## Can I mock a variadic function? ## - -You cannot mock a variadic function (i.e. a function taking ellipsis -(`...`) arguments) directly in Google Mock. - -The problem is that in general, there is _no way_ for a mock object to -know how many arguments are passed to the variadic method, and what -the arguments' types are. Only the _author of the base class_ knows -the protocol, and we cannot look into his head. - -Therefore, to mock such a function, the _user_ must teach the mock -object how to figure out the number of arguments and their types. One -way to do it is to provide overloaded versions of the function. - -Ellipsis arguments are inherited from C and not really a C++ feature. -They are unsafe to use and don't work with arguments that have -constructors or destructors. Therefore we recommend to avoid them in -C++ as much as possible. - -## MSVC gives me warning C4301 or C4373 when I define a mock method with a const parameter. Why? ## - -If you compile this using Microsoft Visual C++ 2005 SP1: -``` -class Foo { - ... - virtual void Bar(const int i) = 0; -}; - -class MockFoo : public Foo { - ... - MOCK_METHOD1(Bar, void(const int i)); -}; -``` -You may get the following warning: -``` -warning C4301: 'MockFoo::Bar': overriding virtual function only differs from 'Foo::Bar' by const/volatile qualifier -``` - -This is a MSVC bug. The same code compiles fine with gcc ,for -example. If you use Visual C++ 2008 SP1, you would get the warning: -``` -warning C4373: 'MockFoo::Bar': virtual function overrides 'Foo::Bar', previous versions of the compiler did not override when parameters only differed by const/volatile qualifiers -``` - -In C++, if you _declare_ a function with a `const` parameter, the -`const` modifier is _ignored_. Therefore, the `Foo` base class above -is equivalent to: -``` -class Foo { - ... - virtual void Bar(int i) = 0; // int or const int? Makes no difference. -}; -``` - -In fact, you can _declare_ Bar() with an `int` parameter, and _define_ -it with a `const int` parameter. The compiler will still match them -up. - -Since making a parameter `const` is meaningless in the method -_declaration_, we recommend to remove it in both `Foo` and `MockFoo`. -That should workaround the VC bug. - -Note that we are talking about the _top-level_ `const` modifier here. -If the function parameter is passed by pointer or reference, declaring -the _pointee_ or _referee_ as `const` is still meaningful. For -example, the following two declarations are _not_ equivalent: -``` -void Bar(int* p); // Neither p nor *p is const. -void Bar(const int* p); // p is not const, but *p is. -``` - -## I have a huge mock class, and Microsoft Visual C++ runs out of memory when compiling it. What can I do? ## - -We've noticed that when the `/clr` compiler flag is used, Visual C++ -uses 5~6 times as much memory when compiling a mock class. We suggest -to avoid `/clr` when compiling native C++ mocks. - -## I can't figure out why Google Mock thinks my expectations are not satisfied. What should I do? ## - -You might want to run your test with -`--gmock_verbose=info`. This flag lets Google Mock print a trace -of every mock function call it receives. By studying the trace, -you'll gain insights on why the expectations you set are not met. - -## How can I assert that a function is NEVER called? ## - -``` -EXPECT_CALL(foo, Bar(_)) - .Times(0); -``` - -## I have a failed test where Google Mock tells me TWICE that a particular expectation is not satisfied. Isn't this redundant? ## - -When Google Mock detects a failure, it prints relevant information -(the mock function arguments, the state of relevant expectations, and -etc) to help the user debug. If another failure is detected, Google -Mock will do the same, including printing the state of relevant -expectations. - -Sometimes an expectation's state didn't change between two failures, -and you'll see the same description of the state twice. They are -however _not_ redundant, as they refer to _different points in time_. -The fact they are the same _is_ interesting information. - -## I get a heap check failure when using a mock object, but using a real object is fine. What can be wrong? ## - -Does the class (hopefully a pure interface) you are mocking have a -virtual destructor? - -Whenever you derive from a base class, make sure its destructor is -virtual. Otherwise Bad Things will happen. Consider the following -code: - -``` -class Base { - public: - // Not virtual, but should be. - ~Base() { ... } - ... -}; - -class Derived : public Base { - public: - ... - private: - std::string value_; -}; - -... - Base* p = new Derived; - ... - delete p; // Surprise! ~Base() will be called, but ~Derived() will not - // - value_ is leaked. -``` - -By changing `~Base()` to virtual, `~Derived()` will be correctly -called when `delete p` is executed, and the heap checker -will be happy. - -## The "newer expectations override older ones" rule makes writing expectations awkward. Why does Google Mock do that? ## - -When people complain about this, often they are referring to code like: - -``` -// foo.Bar() should be called twice, return 1 the first time, and return -// 2 the second time. However, I have to write the expectations in the -// reverse order. This sucks big time!!! -EXPECT_CALL(foo, Bar()) - .WillOnce(Return(2)) - .RetiresOnSaturation(); -EXPECT_CALL(foo, Bar()) - .WillOnce(Return(1)) - .RetiresOnSaturation(); -``` - -The problem is that they didn't pick the **best** way to express the test's -intent. - -By default, expectations don't have to be matched in _any_ particular -order. If you want them to match in a certain order, you need to be -explicit. This is Google Mock's (and jMock's) fundamental philosophy: it's -easy to accidentally over-specify your tests, and we want to make it -harder to do so. - -There are two better ways to write the test spec. You could either -put the expectations in sequence: - -``` -// foo.Bar() should be called twice, return 1 the first time, and return -// 2 the second time. Using a sequence, we can write the expectations -// in their natural order. -{ - InSequence s; - EXPECT_CALL(foo, Bar()) - .WillOnce(Return(1)) - .RetiresOnSaturation(); - EXPECT_CALL(foo, Bar()) - .WillOnce(Return(2)) - .RetiresOnSaturation(); -} -``` - -or you can put the sequence of actions in the same expectation: - -``` -// foo.Bar() should be called twice, return 1 the first time, and return -// 2 the second time. -EXPECT_CALL(foo, Bar()) - .WillOnce(Return(1)) - .WillOnce(Return(2)) - .RetiresOnSaturation(); -``` - -Back to the original questions: why does Google Mock search the -expectations (and `ON_CALL`s) from back to front? Because this -allows a user to set up a mock's behavior for the common case early -(e.g. in the mock's constructor or the test fixture's set-up phase) -and customize it with more specific rules later. If Google Mock -searches from front to back, this very useful pattern won't be -possible. - -## Google Mock prints a warning when a function without EXPECT\_CALL is called, even if I have set its behavior using ON\_CALL. Would it be reasonable not to show the warning in this case? ## - -When choosing between being neat and being safe, we lean toward the -latter. So the answer is that we think it's better to show the -warning. - -Often people write `ON_CALL`s in the mock object's -constructor or `SetUp()`, as the default behavior rarely changes from -test to test. Then in the test body they set the expectations, which -are often different for each test. Having an `ON_CALL` in the set-up -part of a test doesn't mean that the calls are expected. If there's -no `EXPECT_CALL` and the method is called, it's possibly an error. If -we quietly let the call go through without notifying the user, bugs -may creep in unnoticed. - -If, however, you are sure that the calls are OK, you can write - -``` -EXPECT_CALL(foo, Bar(_)) - .WillRepeatedly(...); -``` - -instead of - -``` -ON_CALL(foo, Bar(_)) - .WillByDefault(...); -``` - -This tells Google Mock that you do expect the calls and no warning should be -printed. - -Also, you can control the verbosity using the `--gmock_verbose` flag. -If you find the output too noisy when debugging, just choose a less -verbose level. - -## How can I delete the mock function's argument in an action? ## - -If you find yourself needing to perform some action that's not -supported by Google Mock directly, remember that you can define your own -actions using -[MakeAction()](http://code.google.com/p/googlemock/wiki/V1_7_CookBook#Writing_New_Actions) or -[MakePolymorphicAction()](http://code.google.com/p/googlemock/wiki/V1_7_CookBook#Writing_New_Polymorphic_Actions), -or you can write a stub function and invoke it using -[Invoke()](http://code.google.com/p/googlemock/wiki/V1_7_CookBook#Using_Functions_Methods_Functors). - -## MOCK\_METHODn()'s second argument looks funny. Why don't you use the MOCK\_METHODn(Method, return\_type, arg\_1, ..., arg\_n) syntax? ## - -What?! I think it's beautiful. :-) - -While which syntax looks more natural is a subjective matter to some -extent, Google Mock's syntax was chosen for several practical advantages it -has. - -Try to mock a function that takes a map as an argument: -``` -virtual int GetSize(const map<int, std::string>& m); -``` - -Using the proposed syntax, it would be: -``` -MOCK_METHOD1(GetSize, int, const map<int, std::string>& m); -``` - -Guess what? You'll get a compiler error as the compiler thinks that -`const map<int, std::string>& m` are **two**, not one, arguments. To work -around this you can use `typedef` to give the map type a name, but -that gets in the way of your work. Google Mock's syntax avoids this -problem as the function's argument types are protected inside a pair -of parentheses: -``` -// This compiles fine. -MOCK_METHOD1(GetSize, int(const map<int, std::string>& m)); -``` - -You still need a `typedef` if the return type contains an unprotected -comma, but that's much rarer. - -Other advantages include: - 1. `MOCK_METHOD1(Foo, int, bool)` can leave a reader wonder whether the method returns `int` or `bool`, while there won't be such confusion using Google Mock's syntax. - 1. The way Google Mock describes a function type is nothing new, although many people may not be familiar with it. The same syntax was used in C, and the `function` library in `tr1` uses this syntax extensively. Since `tr1` will become a part of the new version of STL, we feel very comfortable to be consistent with it. - 1. The function type syntax is also used in other parts of Google Mock's API (e.g. the action interface) in order to make the implementation tractable. A user needs to learn it anyway in order to utilize Google Mock's more advanced features. We'd as well stick to the same syntax in `MOCK_METHOD*`! - -## My code calls a static/global function. Can I mock it? ## - -You can, but you need to make some changes. - -In general, if you find yourself needing to mock a static function, -it's a sign that your modules are too tightly coupled (and less -flexible, less reusable, less testable, etc). You are probably better -off defining a small interface and call the function through that -interface, which then can be easily mocked. It's a bit of work -initially, but usually pays for itself quickly. - -This Google Testing Blog -[post](http://googletesting.blogspot.com/2008/06/defeat-static-cling.html) -says it excellently. Check it out. - -## My mock object needs to do complex stuff. It's a lot of pain to specify the actions. Google Mock sucks! ## - -I know it's not a question, but you get an answer for free any way. :-) - -With Google Mock, you can create mocks in C++ easily. And people might be -tempted to use them everywhere. Sometimes they work great, and -sometimes you may find them, well, a pain to use. So, what's wrong in -the latter case? - -When you write a test without using mocks, you exercise the code and -assert that it returns the correct value or that the system is in an -expected state. This is sometimes called "state-based testing". - -Mocks are great for what some call "interaction-based" testing: -instead of checking the system state at the very end, mock objects -verify that they are invoked the right way and report an error as soon -as it arises, giving you a handle on the precise context in which the -error was triggered. This is often more effective and economical to -do than state-based testing. - -If you are doing state-based testing and using a test double just to -simulate the real object, you are probably better off using a fake. -Using a mock in this case causes pain, as it's not a strong point for -mocks to perform complex actions. If you experience this and think -that mocks suck, you are just not using the right tool for your -problem. Or, you might be trying to solve the wrong problem. :-) - -## I got a warning "Uninteresting function call encountered - default action taken.." Should I panic? ## - -By all means, NO! It's just an FYI. - -What it means is that you have a mock function, you haven't set any -expectations on it (by Google Mock's rule this means that you are not -interested in calls to this function and therefore it can be called -any number of times), and it is called. That's OK - you didn't say -it's not OK to call the function! - -What if you actually meant to disallow this function to be called, but -forgot to write `EXPECT_CALL(foo, Bar()).Times(0)`? While -one can argue that it's the user's fault, Google Mock tries to be nice and -prints you a note. - -So, when you see the message and believe that there shouldn't be any -uninteresting calls, you should investigate what's going on. To make -your life easier, Google Mock prints the function name and arguments -when an uninteresting call is encountered. - -## I want to define a custom action. Should I use Invoke() or implement the action interface? ## - -Either way is fine - you want to choose the one that's more convenient -for your circumstance. - -Usually, if your action is for a particular function type, defining it -using `Invoke()` should be easier; if your action can be used in -functions of different types (e.g. if you are defining -`Return(value)`), `MakePolymorphicAction()` is -easiest. Sometimes you want precise control on what types of -functions the action can be used in, and implementing -`ActionInterface` is the way to go here. See the implementation of -`Return()` in `include/gmock/gmock-actions.h` for an example. - -## I'm using the set-argument-pointee action, and the compiler complains about "conflicting return type specified". What does it mean? ## - -You got this error as Google Mock has no idea what value it should return -when the mock method is called. `SetArgPointee()` says what the -side effect is, but doesn't say what the return value should be. You -need `DoAll()` to chain a `SetArgPointee()` with a `Return()`. - -See this [recipe](http://code.google.com/p/googlemock/wiki/V1_7_CookBook#Mocking_Side_Effects) for more details and an example. - - -## My question is not in your FAQ! ## - -If you cannot find the answer to your question in this FAQ, there are -some other resources you can use: - - 1. read other [wiki pages](http://code.google.com/p/googlemock/w/list), - 1. search the mailing list [archive](http://groups.google.com/group/googlemock/topics), - 1. ask it on [googlemock@googlegroups.com](mailto:googlemock@googlegroups.com) and someone will answer it (to prevent spam, we require you to join the [discussion group](http://groups.google.com/group/googlemock) before you can post.). - -Please note that creating an issue in the -[issue tracker](http://code.google.com/p/googlemock/issues/list) is _not_ -a good way to get your answer, as it is monitored infrequently by a -very small number of people. - -When asking a question, it's helpful to provide as much of the -following information as possible (people cannot help you if there's -not enough information in your question): - - * the version (or the revision number if you check out from SVN directly) of Google Mock you use (Google Mock is under active development, so it's possible that your problem has been solved in a later version), - * your operating system, - * the name and version of your compiler, - * the complete command line flags you give to your compiler, - * the complete compiler error messages (if the question is about compilation), - * the _actual_ code (ideally, a minimal but complete program) that has the problem you encounter.
\ No newline at end of file diff --git a/googlemock/include/gmock/gmock-actions.h b/googlemock/include/gmock/gmock-actions.h index b3f654a..8e7e0e7 100644 --- a/googlemock/include/gmock/gmock-actions.h +++ b/googlemock/include/gmock/gmock-actions.h @@ -26,13 +26,14 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // Google Mock - a framework for writing C++ mock classes. // // This file implements some commonly used actions. +// GOOGLETEST_CM0002 DO NOT DELETE + #ifndef GMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_ #define GMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_ @@ -46,9 +47,10 @@ #include "gmock/internal/gmock-internal-utils.h" #include "gmock/internal/gmock-port.h" -#if GTEST_HAS_STD_TYPE_TRAITS_ // Defined by gtest-port.h via gmock-port.h. +#if GTEST_LANG_CXX11 // Defined by gtest-port.h via gmock-port.h. +#include <functional> #include <type_traits> -#endif +#endif // GTEST_LANG_CXX11 namespace testing { @@ -96,7 +98,7 @@ struct BuiltInDefaultValueGetter<T, false> { template <typename T> class BuiltInDefaultValue { public: -#if GTEST_HAS_STD_TYPE_TRAITS_ +#if GTEST_LANG_CXX11 // This function returns true iff type T has a built-in default value. static bool Exists() { return ::std::is_default_constructible<T>::value; @@ -107,7 +109,7 @@ class BuiltInDefaultValue { T, ::std::is_default_constructible<T>::value>::Get(); } -#else // GTEST_HAS_STD_TYPE_TRAITS_ +#else // GTEST_LANG_CXX11 // This function returns true iff type T has a built-in default value. static bool Exists() { return false; @@ -117,7 +119,7 @@ class BuiltInDefaultValue { return BuiltInDefaultValueGetter<T, false>::Get(); } -#endif // GTEST_HAS_STD_TYPE_TRAITS_ +#endif // GTEST_LANG_CXX11 }; // This partial specialization says that we use the same built-in @@ -135,7 +137,7 @@ template <typename T> class BuiltInDefaultValue<T*> { public: static bool Exists() { return true; } - static T* Get() { return NULL; } + static T* Get() { return nullptr; } }; // The following specializations define the default values for @@ -218,11 +220,11 @@ class DefaultValue { // Unsets the default value for type T. static void Clear() { delete producer_; - producer_ = NULL; + producer_ = nullptr; } // Returns true iff the user has set the default value for type T. - static bool IsSet() { return producer_ != NULL; } + static bool IsSet() { return producer_ != nullptr; } // Returns true if T has a default return value set by the user or there // exists a built-in default value. @@ -234,8 +236,8 @@ class DefaultValue { // otherwise returns the built-in default value. Requires that Exists() // is true, which ensures that the return value is well-defined. static T Get() { - return producer_ == NULL ? - internal::BuiltInDefaultValue<T>::Get() : producer_->Produce(); + return producer_ == nullptr ? internal::BuiltInDefaultValue<T>::Get() + : producer_->Produce(); } private: @@ -280,12 +282,10 @@ class DefaultValue<T&> { } // Unsets the default value for type T&. - static void Clear() { - address_ = NULL; - } + static void Clear() { address_ = nullptr; } // Returns true iff the user has set the default value for type T&. - static bool IsSet() { return address_ != NULL; } + static bool IsSet() { return address_ != nullptr; } // Returns true if T has a default return value set by the user or there // exists a built-in default value. @@ -297,8 +297,8 @@ class DefaultValue<T&> { // otherwise returns the built-in default value if there is one; // otherwise aborts the process. static T& Get() { - return address_ == NULL ? - internal::BuiltInDefaultValue<T&>::Get() : *address_; + return address_ == nullptr ? internal::BuiltInDefaultValue<T&>::Get() + : *address_; } private: @@ -316,11 +316,11 @@ class DefaultValue<void> { // Points to the user-set default value for type T. template <typename T> -typename DefaultValue<T>::ValueProducer* DefaultValue<T>::producer_ = NULL; +typename DefaultValue<T>::ValueProducer* DefaultValue<T>::producer_ = nullptr; // Points to the user-set default value for type T&. template <typename T> -T* DefaultValue<T&>::address_ = NULL; +T* DefaultValue<T&>::address_ = nullptr; // Implement this interface to define an action for function type F. template <typename F> @@ -359,14 +359,20 @@ class Action { // Constructs a null Action. Needed for storing Action objects in // STL containers. - Action() : impl_(NULL) {} + Action() {} - // Constructs an Action from its implementation. A NULL impl is - // used to represent the "do-default" action. - explicit Action(ActionInterface<F>* impl) : impl_(impl) {} +#if GTEST_LANG_CXX11 + // Construct an Action from a specified callable. + // This cannot take std::function directly, because then Action would not be + // directly constructible from lambda (it would require two conversions). + template <typename G, + typename = typename ::std::enable_if< + ::std::is_constructible<::std::function<F>, G>::value>::type> + Action(G&& fun) : fun_(::std::forward<G>(fun)) {} // NOLINT +#endif - // Copy constructor. - Action(const Action& action) : impl_(action.impl_) {} + // Constructs an Action from its implementation. + explicit Action(ActionInterface<F>* impl) : impl_(impl) {} // This constructor allows us to turn an Action<Func> object into an // Action<F>, as long as F's arguments can be implicitly converted @@ -376,7 +382,13 @@ class Action { explicit Action(const Action<Func>& action); // Returns true iff this is the DoDefault() action. - bool IsDoDefault() const { return impl_.get() == NULL; } + bool IsDoDefault() const { +#if GTEST_LANG_CXX11 + return impl_ == nullptr && fun_ == nullptr; +#else + return impl_ == NULL; +#endif + } // Performs the action. Note that this method is const even though // the corresponding method in ActionInterface is not. The reason @@ -384,14 +396,15 @@ class Action { // another concrete action, not that the concrete action it binds to // cannot change state. (Think of the difference between a const // pointer and a pointer to const.) - Result Perform(const ArgumentTuple& args) const { - internal::Assert( - !IsDoDefault(), __FILE__, __LINE__, - "You are using DoDefault() inside a composite action like " - "DoAll() or WithArgs(). This is not supported for technical " - "reasons. Please instead spell out the default action, or " - "assign the default action to an Action variable and use " - "the variable in various places."); + Result Perform(ArgumentTuple args) const { + if (IsDoDefault()) { + internal::IllegalDoDefault(__FILE__, __LINE__); + } +#if GTEST_LANG_CXX11 + if (fun_ != nullptr) { + return internal::Apply(fun_, ::std::move(args)); + } +#endif return impl_->Perform(args); } @@ -399,6 +412,18 @@ class Action { template <typename F1, typename F2> friend class internal::ActionAdaptor; + template <typename G> + friend class Action; + + // In C++11, Action can be implemented either as a generic functor (through + // std::function), or legacy ActionInterface. In C++98, only ActionInterface + // is available. The invariants are as follows: + // * in C++98, impl_ is null iff this is the default action + // * in C++11, at most one of fun_ & impl_ may be nonnull; both are null iff + // this is the default action +#if GTEST_LANG_CXX11 + ::std::function<F> fun_; +#endif internal::linked_ptr<ActionInterface<F> > impl_; }; @@ -414,7 +439,7 @@ class Action { // template <typename Result, typename ArgumentTuple> // Result Perform(const ArgumentTuple& args) const { // // Processes the arguments and returns a result, using -// // tr1::get<N>(args) to get the N-th (0-based) argument in the tuple. +// // std::get<N>(args) to get the N-th (0-based) argument in the tuple. // } // ... // }; @@ -530,6 +555,9 @@ struct ByMoveWrapper { // statement, and conversion of the result of Return to Action<T(U)> is a // good place for that. // +// The real life example of the above scenario happens when an invocation +// of gtl::Container() is passed into Return. +// template <typename R> class ReturnAction { public: @@ -749,7 +777,7 @@ class DoDefaultAction { // This template type conversion operator allows DoDefault() to be // used in any function. template <typename F> - operator Action<F>() const { return Action<F>(NULL); } + operator Action<F>() const { return Action<F>(); } // NOLINT }; // Implements the Assign action to set a given pointer referent to a @@ -810,7 +838,7 @@ class SetArgumentPointeeAction { template <typename Result, typename ArgumentTuple> void Perform(const ArgumentTuple& args) const { CompileAssertTypesEqual<void, Result>(); - *::testing::get<N>(args) = value_; + *::std::get<N>(args) = value_; } private: @@ -833,7 +861,7 @@ class SetArgumentPointeeAction<N, Proto, true> { template <typename Result, typename ArgumentTuple> void Perform(const ArgumentTuple& args) const { CompileAssertTypesEqual<void, Result>(); - ::testing::get<N>(args)->CopyFrom(*proto_); + ::std::get<N>(args)->CopyFrom(*proto_); } private: @@ -885,6 +913,28 @@ class InvokeMethodWithoutArgsAction { GTEST_DISALLOW_ASSIGN_(InvokeMethodWithoutArgsAction); }; +// Implements the InvokeWithoutArgs(callback) action. +template <typename CallbackType> +class InvokeCallbackWithoutArgsAction { + public: + // The c'tor takes ownership of the callback. + explicit InvokeCallbackWithoutArgsAction(CallbackType* callback) + : callback_(callback) { + callback->CheckIsRepeatable(); // Makes sure the callback is permanent. + } + + // This type conversion operator template allows Invoke(callback) to + // be used wherever the callback's return type can be implicitly + // converted to that of the mock function. + template <typename Result, typename ArgumentTuple> + Result Perform(const ArgumentTuple&) const { return callback_->Run(); } + + private: + const internal::linked_ptr<CallbackType> callback_; + + GTEST_DISALLOW_ASSIGN_(InvokeCallbackWithoutArgsAction); +}; + // Implements the IgnoreResult(action) action. template <typename A> class IgnoreResultAction { @@ -1029,9 +1079,9 @@ class DoBothAction { // return sqrt(x*x + y*y); // } // ... -// EXEPCT_CALL(mock, Foo("abc", _, _)) +// EXPECT_CALL(mock, Foo("abc", _, _)) // .WillOnce(Invoke(DistanceToOriginWithLabel)); -// EXEPCT_CALL(mock, Bar(5, _, _)) +// EXPECT_CALL(mock, Bar(5, _, _)) // .WillOnce(Invoke(DistanceToOriginWithIndex)); // // you could write @@ -1041,8 +1091,8 @@ class DoBothAction { // return sqrt(x*x + y*y); // } // ... -// EXEPCT_CALL(mock, Foo("abc", _, _)).WillOnce(Invoke(DistanceToOrigin)); -// EXEPCT_CALL(mock, Bar(5, _, _)).WillOnce(Invoke(DistanceToOrigin)); +// EXPECT_CALL(mock, Foo("abc", _, _)).WillOnce(Invoke(DistanceToOrigin)); +// EXPECT_CALL(mock, Bar(5, _, _)).WillOnce(Invoke(DistanceToOrigin)); typedef internal::IgnoredValue Unused; // This constructor allows us to turn an Action<From> object into an @@ -1052,7 +1102,14 @@ typedef internal::IgnoredValue Unused; template <typename To> template <typename From> Action<To>::Action(const Action<From>& from) - : impl_(new internal::ActionAdaptor<To, From>(from)) {} + : +#if GTEST_LANG_CXX11 + fun_(from.fun_), +#endif + impl_(from.impl_ == nullptr + ? nullptr + : new internal::ActionAdaptor<To, From>(from)) { +} // Creates an action that returns 'value'. 'value' is passed by value // instead of const reference - otherwise Return("string literal") diff --git a/googlemock/include/gmock/gmock-cardinalities.h b/googlemock/include/gmock/gmock-cardinalities.h index fc315f9..f916931 100644 --- a/googlemock/include/gmock/gmock-cardinalities.h +++ b/googlemock/include/gmock/gmock-cardinalities.h @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // Google Mock - a framework for writing C++ mock classes. // @@ -35,6 +34,8 @@ // cardinalities can be defined by the user implementing the // CardinalityInterface interface if necessary. +// GOOGLETEST_CM0002 DO NOT DELETE + #ifndef GMOCK_INCLUDE_GMOCK_GMOCK_CARDINALITIES_H_ #define GMOCK_INCLUDE_GMOCK_GMOCK_CARDINALITIES_H_ @@ -43,6 +44,9 @@ #include "gmock/internal/gmock-port.h" #include "gtest/gtest.h" +GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \ +/* class A needs to have dll-interface to be used by clients of class B */) + namespace testing { // To implement a cardinality Foo, define: @@ -144,4 +148,6 @@ inline Cardinality MakeCardinality(const CardinalityInterface* c) { } // namespace testing +GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251 + #endif // GMOCK_INCLUDE_GMOCK_GMOCK_CARDINALITIES_H_ diff --git a/googlemock/include/gmock/gmock-generated-actions.h b/googlemock/include/gmock/gmock-generated-actions.h index b5a889c..3ea14dd 100644 --- a/googlemock/include/gmock/gmock-generated-actions.h +++ b/googlemock/include/gmock/gmock-generated-actions.h @@ -1,4 +1,6 @@ -// This file was GENERATED by a script. DO NOT EDIT BY HAND!!! +// This file was GENERATED by command: +// pump.py gmock-generated-actions.h.pump +// DO NOT EDIT BY HAND!!! // Copyright 2007, Google Inc. // All rights reserved. @@ -28,13 +30,14 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // Google Mock - a framework for writing C++ mock classes. // // This file implements some commonly used variadic actions. +// GOOGLETEST_CM0002 DO NOT DELETE + #ifndef GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_ACTIONS_H_ #define GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_ACTIONS_H_ @@ -45,245 +48,324 @@ namespace testing { namespace internal { // InvokeHelper<F> knows how to unpack an N-tuple and invoke an N-ary -// function or method with the unpacked values, where F is a function -// type that takes N arguments. +// function, method, or callback with the unpacked values, where F is +// a function type that takes N arguments. template <typename Result, typename ArgumentTuple> class InvokeHelper; template <typename R> -class InvokeHelper<R, ::testing::tuple<> > { +class InvokeHelper<R, ::std::tuple<> > { public: template <typename Function> - static R Invoke(Function function, const ::testing::tuple<>&) { + static R Invoke(Function function, const ::std::tuple<>&) { return function(); } template <class Class, typename MethodPtr> static R InvokeMethod(Class* obj_ptr, MethodPtr method_ptr, - const ::testing::tuple<>&) { + const ::std::tuple<>&) { return (obj_ptr->*method_ptr)(); } + + template <typename CallbackType> + static R InvokeCallback(CallbackType* callback, + const ::std::tuple<>&) { + return callback->Run(); + } }; template <typename R, typename A1> -class InvokeHelper<R, ::testing::tuple<A1> > { +class InvokeHelper<R, ::std::tuple<A1> > { public: template <typename Function> - static R Invoke(Function function, const ::testing::tuple<A1>& args) { - return function(get<0>(args)); + static R Invoke(Function function, const ::std::tuple<A1>& args) { + return function(std::get<0>(args)); } template <class Class, typename MethodPtr> static R InvokeMethod(Class* obj_ptr, MethodPtr method_ptr, - const ::testing::tuple<A1>& args) { - return (obj_ptr->*method_ptr)(get<0>(args)); + const ::std::tuple<A1>& args) { + return (obj_ptr->*method_ptr)(std::get<0>(args)); + } + + template <typename CallbackType> + static R InvokeCallback(CallbackType* callback, + const ::std::tuple<A1>& args) { + return callback->Run(std::get<0>(args)); } }; template <typename R, typename A1, typename A2> -class InvokeHelper<R, ::testing::tuple<A1, A2> > { +class InvokeHelper<R, ::std::tuple<A1, A2> > { public: template <typename Function> - static R Invoke(Function function, const ::testing::tuple<A1, A2>& args) { - return function(get<0>(args), get<1>(args)); + static R Invoke(Function function, const ::std::tuple<A1, A2>& args) { + return function(std::get<0>(args), std::get<1>(args)); } template <class Class, typename MethodPtr> static R InvokeMethod(Class* obj_ptr, MethodPtr method_ptr, - const ::testing::tuple<A1, A2>& args) { - return (obj_ptr->*method_ptr)(get<0>(args), get<1>(args)); + const ::std::tuple<A1, A2>& args) { + return (obj_ptr->*method_ptr)(std::get<0>(args), std::get<1>(args)); + } + + template <typename CallbackType> + static R InvokeCallback(CallbackType* callback, + const ::std::tuple<A1, A2>& args) { + return callback->Run(std::get<0>(args), std::get<1>(args)); } }; template <typename R, typename A1, typename A2, typename A3> -class InvokeHelper<R, ::testing::tuple<A1, A2, A3> > { +class InvokeHelper<R, ::std::tuple<A1, A2, A3> > { public: template <typename Function> - static R Invoke(Function function, const ::testing::tuple<A1, A2, A3>& args) { - return function(get<0>(args), get<1>(args), get<2>(args)); + static R Invoke(Function function, const ::std::tuple<A1, A2, A3>& args) { + return function(std::get<0>(args), std::get<1>(args), + std::get<2>(args)); } template <class Class, typename MethodPtr> static R InvokeMethod(Class* obj_ptr, MethodPtr method_ptr, - const ::testing::tuple<A1, A2, A3>& args) { - return (obj_ptr->*method_ptr)(get<0>(args), get<1>(args), - get<2>(args)); + const ::std::tuple<A1, A2, A3>& args) { + return (obj_ptr->*method_ptr)(std::get<0>(args), std::get<1>(args), + std::get<2>(args)); + } + + template <typename CallbackType> + static R InvokeCallback(CallbackType* callback, + const ::std::tuple<A1, A2, A3>& args) { + return callback->Run(std::get<0>(args), std::get<1>(args), + std::get<2>(args)); } }; template <typename R, typename A1, typename A2, typename A3, typename A4> -class InvokeHelper<R, ::testing::tuple<A1, A2, A3, A4> > { +class InvokeHelper<R, ::std::tuple<A1, A2, A3, A4> > { public: template <typename Function> - static R Invoke(Function function, const ::testing::tuple<A1, A2, A3, - A4>& args) { - return function(get<0>(args), get<1>(args), get<2>(args), - get<3>(args)); + static R Invoke(Function function, const ::std::tuple<A1, A2, A3, A4>& args) { + return function(std::get<0>(args), std::get<1>(args), + std::get<2>(args), std::get<3>(args)); } template <class Class, typename MethodPtr> static R InvokeMethod(Class* obj_ptr, MethodPtr method_ptr, - const ::testing::tuple<A1, A2, A3, A4>& args) { - return (obj_ptr->*method_ptr)(get<0>(args), get<1>(args), - get<2>(args), get<3>(args)); + const ::std::tuple<A1, A2, A3, A4>& args) { + return (obj_ptr->*method_ptr)(std::get<0>(args), std::get<1>(args), + std::get<2>(args), std::get<3>(args)); + } + + template <typename CallbackType> + static R InvokeCallback(CallbackType* callback, + const ::std::tuple<A1, A2, A3, A4>& args) { + return callback->Run(std::get<0>(args), std::get<1>(args), + std::get<2>(args), std::get<3>(args)); } }; template <typename R, typename A1, typename A2, typename A3, typename A4, typename A5> -class InvokeHelper<R, ::testing::tuple<A1, A2, A3, A4, A5> > { +class InvokeHelper<R, ::std::tuple<A1, A2, A3, A4, A5> > { public: template <typename Function> - static R Invoke(Function function, const ::testing::tuple<A1, A2, A3, A4, + static R Invoke(Function function, const ::std::tuple<A1, A2, A3, A4, A5>& args) { - return function(get<0>(args), get<1>(args), get<2>(args), - get<3>(args), get<4>(args)); + return function(std::get<0>(args), std::get<1>(args), + std::get<2>(args), std::get<3>(args), std::get<4>(args)); } template <class Class, typename MethodPtr> static R InvokeMethod(Class* obj_ptr, MethodPtr method_ptr, - const ::testing::tuple<A1, A2, A3, A4, A5>& args) { - return (obj_ptr->*method_ptr)(get<0>(args), get<1>(args), - get<2>(args), get<3>(args), get<4>(args)); + const ::std::tuple<A1, A2, A3, A4, A5>& args) { + return (obj_ptr->*method_ptr)(std::get<0>(args), std::get<1>(args), + std::get<2>(args), std::get<3>(args), std::get<4>(args)); + } + + template <typename CallbackType> + static R InvokeCallback(CallbackType* callback, + const ::std::tuple<A1, A2, A3, A4, A5>& args) { + return callback->Run(std::get<0>(args), std::get<1>(args), + std::get<2>(args), std::get<3>(args), std::get<4>(args)); } }; template <typename R, typename A1, typename A2, typename A3, typename A4, typename A5, typename A6> -class InvokeHelper<R, ::testing::tuple<A1, A2, A3, A4, A5, A6> > { +class InvokeHelper<R, ::std::tuple<A1, A2, A3, A4, A5, A6> > { public: template <typename Function> - static R Invoke(Function function, const ::testing::tuple<A1, A2, A3, A4, A5, + static R Invoke(Function function, const ::std::tuple<A1, A2, A3, A4, A5, A6>& args) { - return function(get<0>(args), get<1>(args), get<2>(args), - get<3>(args), get<4>(args), get<5>(args)); + return function(std::get<0>(args), std::get<1>(args), + std::get<2>(args), std::get<3>(args), std::get<4>(args), + std::get<5>(args)); } template <class Class, typename MethodPtr> static R InvokeMethod(Class* obj_ptr, MethodPtr method_ptr, - const ::testing::tuple<A1, A2, A3, A4, A5, A6>& args) { - return (obj_ptr->*method_ptr)(get<0>(args), get<1>(args), - get<2>(args), get<3>(args), get<4>(args), get<5>(args)); + const ::std::tuple<A1, A2, A3, A4, A5, A6>& args) { + return (obj_ptr->*method_ptr)(std::get<0>(args), std::get<1>(args), + std::get<2>(args), std::get<3>(args), std::get<4>(args), + std::get<5>(args)); } + + // There is no InvokeCallback() for 6-tuples }; template <typename R, typename A1, typename A2, typename A3, typename A4, typename A5, typename A6, typename A7> -class InvokeHelper<R, ::testing::tuple<A1, A2, A3, A4, A5, A6, A7> > { +class InvokeHelper<R, ::std::tuple<A1, A2, A3, A4, A5, A6, A7> > { public: template <typename Function> - static R Invoke(Function function, const ::testing::tuple<A1, A2, A3, A4, A5, - A6, A7>& args) { - return function(get<0>(args), get<1>(args), get<2>(args), - get<3>(args), get<4>(args), get<5>(args), get<6>(args)); + static R Invoke(Function function, const ::std::tuple<A1, A2, A3, A4, A5, A6, + A7>& args) { + return function(std::get<0>(args), std::get<1>(args), + std::get<2>(args), std::get<3>(args), std::get<4>(args), + std::get<5>(args), std::get<6>(args)); } template <class Class, typename MethodPtr> static R InvokeMethod(Class* obj_ptr, MethodPtr method_ptr, - const ::testing::tuple<A1, A2, A3, A4, A5, A6, - A7>& args) { - return (obj_ptr->*method_ptr)(get<0>(args), get<1>(args), - get<2>(args), get<3>(args), get<4>(args), get<5>(args), - get<6>(args)); + const ::std::tuple<A1, A2, A3, A4, A5, A6, A7>& args) { + return (obj_ptr->*method_ptr)(std::get<0>(args), std::get<1>(args), + std::get<2>(args), std::get<3>(args), std::get<4>(args), + std::get<5>(args), std::get<6>(args)); } + + // There is no InvokeCallback() for 7-tuples }; template <typename R, typename A1, typename A2, typename A3, typename A4, typename A5, typename A6, typename A7, typename A8> -class InvokeHelper<R, ::testing::tuple<A1, A2, A3, A4, A5, A6, A7, A8> > { +class InvokeHelper<R, ::std::tuple<A1, A2, A3, A4, A5, A6, A7, A8> > { public: template <typename Function> - static R Invoke(Function function, const ::testing::tuple<A1, A2, A3, A4, A5, - A6, A7, A8>& args) { - return function(get<0>(args), get<1>(args), get<2>(args), - get<3>(args), get<4>(args), get<5>(args), get<6>(args), - get<7>(args)); + static R Invoke(Function function, const ::std::tuple<A1, A2, A3, A4, A5, A6, + A7, A8>& args) { + return function(std::get<0>(args), std::get<1>(args), + std::get<2>(args), std::get<3>(args), std::get<4>(args), + std::get<5>(args), std::get<6>(args), std::get<7>(args)); } template <class Class, typename MethodPtr> static R InvokeMethod(Class* obj_ptr, MethodPtr method_ptr, - const ::testing::tuple<A1, A2, A3, A4, A5, A6, A7, + const ::std::tuple<A1, A2, A3, A4, A5, A6, A7, A8>& args) { - return (obj_ptr->*method_ptr)(get<0>(args), get<1>(args), - get<2>(args), get<3>(args), get<4>(args), get<5>(args), - get<6>(args), get<7>(args)); + return (obj_ptr->*method_ptr)(std::get<0>(args), std::get<1>(args), + std::get<2>(args), std::get<3>(args), std::get<4>(args), + std::get<5>(args), std::get<6>(args), std::get<7>(args)); } + + // There is no InvokeCallback() for 8-tuples }; template <typename R, typename A1, typename A2, typename A3, typename A4, typename A5, typename A6, typename A7, typename A8, typename A9> -class InvokeHelper<R, ::testing::tuple<A1, A2, A3, A4, A5, A6, A7, A8, A9> > { +class InvokeHelper<R, ::std::tuple<A1, A2, A3, A4, A5, A6, A7, A8, A9> > { public: template <typename Function> - static R Invoke(Function function, const ::testing::tuple<A1, A2, A3, A4, A5, - A6, A7, A8, A9>& args) { - return function(get<0>(args), get<1>(args), get<2>(args), - get<3>(args), get<4>(args), get<5>(args), get<6>(args), - get<7>(args), get<8>(args)); + static R Invoke(Function function, const ::std::tuple<A1, A2, A3, A4, A5, A6, + A7, A8, A9>& args) { + return function(std::get<0>(args), std::get<1>(args), + std::get<2>(args), std::get<3>(args), std::get<4>(args), + std::get<5>(args), std::get<6>(args), std::get<7>(args), + std::get<8>(args)); } template <class Class, typename MethodPtr> static R InvokeMethod(Class* obj_ptr, MethodPtr method_ptr, - const ::testing::tuple<A1, A2, A3, A4, A5, A6, A7, A8, + const ::std::tuple<A1, A2, A3, A4, A5, A6, A7, A8, A9>& args) { - return (obj_ptr->*method_ptr)(get<0>(args), get<1>(args), - get<2>(args), get<3>(args), get<4>(args), get<5>(args), - get<6>(args), get<7>(args), get<8>(args)); + return (obj_ptr->*method_ptr)(std::get<0>(args), std::get<1>(args), + std::get<2>(args), std::get<3>(args), std::get<4>(args), + std::get<5>(args), std::get<6>(args), std::get<7>(args), + std::get<8>(args)); } + + // There is no InvokeCallback() for 9-tuples }; template <typename R, typename A1, typename A2, typename A3, typename A4, typename A5, typename A6, typename A7, typename A8, typename A9, typename A10> -class InvokeHelper<R, ::testing::tuple<A1, A2, A3, A4, A5, A6, A7, A8, A9, - A10> > { +class InvokeHelper<R, ::std::tuple<A1, A2, A3, A4, A5, A6, A7, A8, A9, A10> > { public: template <typename Function> - static R Invoke(Function function, const ::testing::tuple<A1, A2, A3, A4, A5, - A6, A7, A8, A9, A10>& args) { - return function(get<0>(args), get<1>(args), get<2>(args), - get<3>(args), get<4>(args), get<5>(args), get<6>(args), - get<7>(args), get<8>(args), get<9>(args)); + static R Invoke(Function function, const ::std::tuple<A1, A2, A3, A4, A5, A6, + A7, A8, A9, A10>& args) { + return function(std::get<0>(args), std::get<1>(args), + std::get<2>(args), std::get<3>(args), std::get<4>(args), + std::get<5>(args), std::get<6>(args), std::get<7>(args), + std::get<8>(args), std::get<9>(args)); } template <class Class, typename MethodPtr> static R InvokeMethod(Class* obj_ptr, MethodPtr method_ptr, - const ::testing::tuple<A1, A2, A3, A4, A5, A6, A7, A8, - A9, A10>& args) { - return (obj_ptr->*method_ptr)(get<0>(args), get<1>(args), - get<2>(args), get<3>(args), get<4>(args), get<5>(args), - get<6>(args), get<7>(args), get<8>(args), get<9>(args)); + const ::std::tuple<A1, A2, A3, A4, A5, A6, A7, A8, A9, + A10>& args) { + return (obj_ptr->*method_ptr)(std::get<0>(args), std::get<1>(args), + std::get<2>(args), std::get<3>(args), std::get<4>(args), + std::get<5>(args), std::get<6>(args), std::get<7>(args), + std::get<8>(args), std::get<9>(args)); } + + // There is no InvokeCallback() for 10-tuples +}; + +// Implements the Invoke(callback) action. +template <typename CallbackType> +class InvokeCallbackAction { + public: + // The c'tor takes ownership of the callback. + explicit InvokeCallbackAction(CallbackType* callback) + : callback_(callback) { + callback->CheckIsRepeatable(); // Makes sure the callback is permanent. + } + + // This type conversion operator template allows Invoke(callback) to + // be used wherever the callback's type is compatible with that of + // the mock function, i.e. if the mock function's arguments can be + // implicitly converted to the callback's arguments and the + // callback's result can be implicitly converted to the mock + // function's result. + template <typename Result, typename ArgumentTuple> + Result Perform(const ArgumentTuple& args) const { + return InvokeHelper<Result, ArgumentTuple>::InvokeCallback( + callback_.get(), args); + } + private: + const linked_ptr<CallbackType> callback_; }; // An INTERNAL macro for extracting the type of a tuple field. It's // subject to change without notice - DO NOT USE IN USER CODE! #define GMOCK_FIELD_(Tuple, N) \ - typename ::testing::tuple_element<N, Tuple>::type + typename ::std::tuple_element<N, Tuple>::type // SelectArgs<Result, ArgumentTuple, k1, k2, ..., k_n>::type is the // type of an n-ary function whose i-th (1-based) argument type is the // k{i}-th (0-based) field of ArgumentTuple, which must be a tuple // type, and whose return type is Result. For example, -// SelectArgs<int, ::testing::tuple<bool, char, double, long>, 0, 3>::type +// SelectArgs<int, ::std::tuple<bool, char, double, long>, 0, 3>::type // is int(bool, long). // // SelectArgs<Result, ArgumentTuple, k1, k2, ..., k_n>::Select(args) // returns the selected fields (k1, k2, ..., k_n) of args as a tuple. // For example, -// SelectArgs<int, tuple<bool, char, double>, 2, 0>::Select( -// ::testing::make_tuple(true, 'a', 2.5)) +// SelectArgs<int, std::tuple<bool, char, double>, 2, 0>::Select( +// ::std::make_tuple(true, 'a', 2.5)) // returns tuple (2.5, true). // // The numbers in list k1, k2, ..., k_n must be >= 0, where n can be @@ -302,9 +384,10 @@ class SelectArgs { GMOCK_FIELD_(ArgumentTuple, k10)); typedef typename Function<type>::ArgumentTuple SelectedArgs; static SelectedArgs Select(const ArgumentTuple& args) { - return SelectedArgs(get<k1>(args), get<k2>(args), get<k3>(args), - get<k4>(args), get<k5>(args), get<k6>(args), get<k7>(args), - get<k8>(args), get<k9>(args), get<k10>(args)); + return SelectedArgs(std::get<k1>(args), std::get<k2>(args), + std::get<k3>(args), std::get<k4>(args), std::get<k5>(args), + std::get<k6>(args), std::get<k7>(args), std::get<k8>(args), + std::get<k9>(args), std::get<k10>(args)); } }; @@ -326,7 +409,7 @@ class SelectArgs<Result, ArgumentTuple, typedef Result type(GMOCK_FIELD_(ArgumentTuple, k1)); typedef typename Function<type>::ArgumentTuple SelectedArgs; static SelectedArgs Select(const ArgumentTuple& args) { - return SelectedArgs(get<k1>(args)); + return SelectedArgs(std::get<k1>(args)); } }; @@ -338,7 +421,7 @@ class SelectArgs<Result, ArgumentTuple, GMOCK_FIELD_(ArgumentTuple, k2)); typedef typename Function<type>::ArgumentTuple SelectedArgs; static SelectedArgs Select(const ArgumentTuple& args) { - return SelectedArgs(get<k1>(args), get<k2>(args)); + return SelectedArgs(std::get<k1>(args), std::get<k2>(args)); } }; @@ -350,7 +433,8 @@ class SelectArgs<Result, ArgumentTuple, GMOCK_FIELD_(ArgumentTuple, k2), GMOCK_FIELD_(ArgumentTuple, k3)); typedef typename Function<type>::ArgumentTuple SelectedArgs; static SelectedArgs Select(const ArgumentTuple& args) { - return SelectedArgs(get<k1>(args), get<k2>(args), get<k3>(args)); + return SelectedArgs(std::get<k1>(args), std::get<k2>(args), + std::get<k3>(args)); } }; @@ -364,8 +448,8 @@ class SelectArgs<Result, ArgumentTuple, GMOCK_FIELD_(ArgumentTuple, k4)); typedef typename Function<type>::ArgumentTuple SelectedArgs; static SelectedArgs Select(const ArgumentTuple& args) { - return SelectedArgs(get<k1>(args), get<k2>(args), get<k3>(args), - get<k4>(args)); + return SelectedArgs(std::get<k1>(args), std::get<k2>(args), + std::get<k3>(args), std::get<k4>(args)); } }; @@ -379,8 +463,8 @@ class SelectArgs<Result, ArgumentTuple, GMOCK_FIELD_(ArgumentTuple, k4), GMOCK_FIELD_(ArgumentTuple, k5)); typedef typename Function<type>::ArgumentTuple SelectedArgs; static SelectedArgs Select(const ArgumentTuple& args) { - return SelectedArgs(get<k1>(args), get<k2>(args), get<k3>(args), - get<k4>(args), get<k5>(args)); + return SelectedArgs(std::get<k1>(args), std::get<k2>(args), + std::get<k3>(args), std::get<k4>(args), std::get<k5>(args)); } }; @@ -395,8 +479,9 @@ class SelectArgs<Result, ArgumentTuple, GMOCK_FIELD_(ArgumentTuple, k6)); typedef typename Function<type>::ArgumentTuple SelectedArgs; static SelectedArgs Select(const ArgumentTuple& args) { - return SelectedArgs(get<k1>(args), get<k2>(args), get<k3>(args), - get<k4>(args), get<k5>(args), get<k6>(args)); + return SelectedArgs(std::get<k1>(args), std::get<k2>(args), + std::get<k3>(args), std::get<k4>(args), std::get<k5>(args), + std::get<k6>(args)); } }; @@ -411,8 +496,9 @@ class SelectArgs<Result, ArgumentTuple, GMOCK_FIELD_(ArgumentTuple, k6), GMOCK_FIELD_(ArgumentTuple, k7)); typedef typename Function<type>::ArgumentTuple SelectedArgs; static SelectedArgs Select(const ArgumentTuple& args) { - return SelectedArgs(get<k1>(args), get<k2>(args), get<k3>(args), - get<k4>(args), get<k5>(args), get<k6>(args), get<k7>(args)); + return SelectedArgs(std::get<k1>(args), std::get<k2>(args), + std::get<k3>(args), std::get<k4>(args), std::get<k5>(args), + std::get<k6>(args), std::get<k7>(args)); } }; @@ -428,9 +514,9 @@ class SelectArgs<Result, ArgumentTuple, GMOCK_FIELD_(ArgumentTuple, k8)); typedef typename Function<type>::ArgumentTuple SelectedArgs; static SelectedArgs Select(const ArgumentTuple& args) { - return SelectedArgs(get<k1>(args), get<k2>(args), get<k3>(args), - get<k4>(args), get<k5>(args), get<k6>(args), get<k7>(args), - get<k8>(args)); + return SelectedArgs(std::get<k1>(args), std::get<k2>(args), + std::get<k3>(args), std::get<k4>(args), std::get<k5>(args), + std::get<k6>(args), std::get<k7>(args), std::get<k8>(args)); } }; @@ -446,9 +532,10 @@ class SelectArgs<Result, ArgumentTuple, GMOCK_FIELD_(ArgumentTuple, k8), GMOCK_FIELD_(ArgumentTuple, k9)); typedef typename Function<type>::ArgumentTuple SelectedArgs; static SelectedArgs Select(const ArgumentTuple& args) { - return SelectedArgs(get<k1>(args), get<k2>(args), get<k3>(args), - get<k4>(args), get<k5>(args), get<k6>(args), get<k7>(args), - get<k8>(args), get<k9>(args)); + return SelectedArgs(std::get<k1>(args), std::get<k2>(args), + std::get<k3>(args), std::get<k4>(args), std::get<k5>(args), + std::get<k6>(args), std::get<k7>(args), std::get<k8>(args), + std::get<k9>(args)); } }; @@ -511,7 +598,7 @@ struct ExcessiveArg {}; template <typename Result, class Impl> class ActionHelper { public: - static Result Perform(Impl* impl, const ::testing::tuple<>& args) { + static Result Perform(Impl* impl, const ::std::tuple<>& args) { return impl->template gmock_PerformImpl<>(args, ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), @@ -519,95 +606,96 @@ class ActionHelper { } template <typename A0> - static Result Perform(Impl* impl, const ::testing::tuple<A0>& args) { - return impl->template gmock_PerformImpl<A0>(args, get<0>(args), + static Result Perform(Impl* impl, const ::std::tuple<A0>& args) { + return impl->template gmock_PerformImpl<A0>(args, std::get<0>(args), ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), ExcessiveArg()); } template <typename A0, typename A1> - static Result Perform(Impl* impl, const ::testing::tuple<A0, A1>& args) { - return impl->template gmock_PerformImpl<A0, A1>(args, get<0>(args), - get<1>(args), ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), + static Result Perform(Impl* impl, const ::std::tuple<A0, A1>& args) { + return impl->template gmock_PerformImpl<A0, A1>(args, std::get<0>(args), + std::get<1>(args), ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), ExcessiveArg()); } template <typename A0, typename A1, typename A2> - static Result Perform(Impl* impl, const ::testing::tuple<A0, A1, A2>& args) { - return impl->template gmock_PerformImpl<A0, A1, A2>(args, get<0>(args), - get<1>(args), get<2>(args), ExcessiveArg(), ExcessiveArg(), + static Result Perform(Impl* impl, const ::std::tuple<A0, A1, A2>& args) { + return impl->template gmock_PerformImpl<A0, A1, A2>(args, + std::get<0>(args), std::get<1>(args), std::get<2>(args), ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), - ExcessiveArg()); + ExcessiveArg(), ExcessiveArg(), ExcessiveArg()); } template <typename A0, typename A1, typename A2, typename A3> - static Result Perform(Impl* impl, const ::testing::tuple<A0, A1, A2, - A3>& args) { - return impl->template gmock_PerformImpl<A0, A1, A2, A3>(args, get<0>(args), - get<1>(args), get<2>(args), get<3>(args), ExcessiveArg(), - ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), - ExcessiveArg()); + static Result Perform(Impl* impl, const ::std::tuple<A0, A1, A2, A3>& args) { + return impl->template gmock_PerformImpl<A0, A1, A2, A3>(args, + std::get<0>(args), std::get<1>(args), std::get<2>(args), + std::get<3>(args), ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), + ExcessiveArg(), ExcessiveArg(), ExcessiveArg()); } template <typename A0, typename A1, typename A2, typename A3, typename A4> - static Result Perform(Impl* impl, const ::testing::tuple<A0, A1, A2, A3, + static Result Perform(Impl* impl, const ::std::tuple<A0, A1, A2, A3, A4>& args) { return impl->template gmock_PerformImpl<A0, A1, A2, A3, A4>(args, - get<0>(args), get<1>(args), get<2>(args), get<3>(args), get<4>(args), - ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), - ExcessiveArg()); + std::get<0>(args), std::get<1>(args), std::get<2>(args), + std::get<3>(args), std::get<4>(args), ExcessiveArg(), ExcessiveArg(), + ExcessiveArg(), ExcessiveArg(), ExcessiveArg()); } template <typename A0, typename A1, typename A2, typename A3, typename A4, typename A5> - static Result Perform(Impl* impl, const ::testing::tuple<A0, A1, A2, A3, A4, + static Result Perform(Impl* impl, const ::std::tuple<A0, A1, A2, A3, A4, A5>& args) { return impl->template gmock_PerformImpl<A0, A1, A2, A3, A4, A5>(args, - get<0>(args), get<1>(args), get<2>(args), get<3>(args), get<4>(args), - get<5>(args), ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), - ExcessiveArg()); + std::get<0>(args), std::get<1>(args), std::get<2>(args), + std::get<3>(args), std::get<4>(args), std::get<5>(args), + ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), ExcessiveArg()); } template <typename A0, typename A1, typename A2, typename A3, typename A4, typename A5, typename A6> - static Result Perform(Impl* impl, const ::testing::tuple<A0, A1, A2, A3, A4, - A5, A6>& args) { + static Result Perform(Impl* impl, const ::std::tuple<A0, A1, A2, A3, A4, A5, + A6>& args) { return impl->template gmock_PerformImpl<A0, A1, A2, A3, A4, A5, A6>(args, - get<0>(args), get<1>(args), get<2>(args), get<3>(args), get<4>(args), - get<5>(args), get<6>(args), ExcessiveArg(), ExcessiveArg(), - ExcessiveArg()); + std::get<0>(args), std::get<1>(args), std::get<2>(args), + std::get<3>(args), std::get<4>(args), std::get<5>(args), + std::get<6>(args), ExcessiveArg(), ExcessiveArg(), ExcessiveArg()); } template <typename A0, typename A1, typename A2, typename A3, typename A4, typename A5, typename A6, typename A7> - static Result Perform(Impl* impl, const ::testing::tuple<A0, A1, A2, A3, A4, - A5, A6, A7>& args) { + static Result Perform(Impl* impl, const ::std::tuple<A0, A1, A2, A3, A4, A5, + A6, A7>& args) { return impl->template gmock_PerformImpl<A0, A1, A2, A3, A4, A5, A6, - A7>(args, get<0>(args), get<1>(args), get<2>(args), get<3>(args), - get<4>(args), get<5>(args), get<6>(args), get<7>(args), ExcessiveArg(), - ExcessiveArg()); + A7>(args, std::get<0>(args), std::get<1>(args), std::get<2>(args), + std::get<3>(args), std::get<4>(args), std::get<5>(args), + std::get<6>(args), std::get<7>(args), ExcessiveArg(), ExcessiveArg()); } template <typename A0, typename A1, typename A2, typename A3, typename A4, typename A5, typename A6, typename A7, typename A8> - static Result Perform(Impl* impl, const ::testing::tuple<A0, A1, A2, A3, A4, - A5, A6, A7, A8>& args) { + static Result Perform(Impl* impl, const ::std::tuple<A0, A1, A2, A3, A4, A5, + A6, A7, A8>& args) { return impl->template gmock_PerformImpl<A0, A1, A2, A3, A4, A5, A6, A7, - A8>(args, get<0>(args), get<1>(args), get<2>(args), get<3>(args), - get<4>(args), get<5>(args), get<6>(args), get<7>(args), get<8>(args), + A8>(args, std::get<0>(args), std::get<1>(args), std::get<2>(args), + std::get<3>(args), std::get<4>(args), std::get<5>(args), + std::get<6>(args), std::get<7>(args), std::get<8>(args), ExcessiveArg()); } template <typename A0, typename A1, typename A2, typename A3, typename A4, typename A5, typename A6, typename A7, typename A8, typename A9> - static Result Perform(Impl* impl, const ::testing::tuple<A0, A1, A2, A3, A4, - A5, A6, A7, A8, A9>& args) { + static Result Perform(Impl* impl, const ::std::tuple<A0, A1, A2, A3, A4, A5, + A6, A7, A8, A9>& args) { return impl->template gmock_PerformImpl<A0, A1, A2, A3, A4, A5, A6, A7, A8, - A9>(args, get<0>(args), get<1>(args), get<2>(args), get<3>(args), - get<4>(args), get<5>(args), get<6>(args), get<7>(args), get<8>(args), - get<9>(args)); + A9>(args, std::get<0>(args), std::get<1>(args), std::get<2>(args), + std::get<3>(args), std::get<4>(args), std::get<5>(args), + std::get<6>(args), std::get<7>(args), std::get<8>(args), + std::get<9>(args)); } }; @@ -874,8 +962,8 @@ DoAll(Action1 a1, Action2 a2, Action3 a3, Action4 a4, Action5 a5, Action6 a6, // // MORE INFORMATION: // -// To learn more about using these macros, please search for 'ACTION' -// on http://code.google.com/p/googlemock/wiki/CookBook. +// To learn more about using these macros, please search for 'ACTION' on +// https://github.com/google/googletest/blob/master/googlemock/docs/CookBook.md // An internal macro needed for implementing ACTION*(). #define GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_\ @@ -915,7 +1003,7 @@ DoAll(Action1 a1, Action2 a2, Action3 a3, Action4 a4, Action5 a5, Action6 a6, // ACTION_TEMPLATE(DuplicateArg, // HAS_2_TEMPLATE_PARAMS(int, k, typename, T), // AND_1_VALUE_PARAMS(output)) { -// *output = T(::testing::get<k>(args)); +// *output = T(::std::get<k>(args)); // } // ... // int n; @@ -1073,52 +1161,90 @@ DoAll(Action1 a1, Action2 a2, Action3 a3, Action4 a4, Action5 a5, Action6 a6, #define GMOCK_INTERNAL_INIT_AND_0_VALUE_PARAMS()\ () #define GMOCK_INTERNAL_INIT_AND_1_VALUE_PARAMS(p0)\ - (p0##_type gmock_p0) : p0(gmock_p0) + (p0##_type gmock_p0) : p0(::testing::internal::move(gmock_p0)) #define GMOCK_INTERNAL_INIT_AND_2_VALUE_PARAMS(p0, p1)\ - (p0##_type gmock_p0, p1##_type gmock_p1) : p0(gmock_p0), p1(gmock_p1) + (p0##_type gmock_p0, \ + p1##_type gmock_p1) : p0(::testing::internal::move(gmock_p0)), \ + p1(::testing::internal::move(gmock_p1)) #define GMOCK_INTERNAL_INIT_AND_3_VALUE_PARAMS(p0, p1, p2)\ (p0##_type gmock_p0, p1##_type gmock_p1, \ - p2##_type gmock_p2) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2) + p2##_type gmock_p2) : p0(::testing::internal::move(gmock_p0)), \ + p1(::testing::internal::move(gmock_p1)), \ + p2(::testing::internal::move(gmock_p2)) #define GMOCK_INTERNAL_INIT_AND_4_VALUE_PARAMS(p0, p1, p2, p3)\ (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ - p3##_type gmock_p3) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), \ - p3(gmock_p3) + p3##_type gmock_p3) : p0(::testing::internal::move(gmock_p0)), \ + p1(::testing::internal::move(gmock_p1)), \ + p2(::testing::internal::move(gmock_p2)), \ + p3(::testing::internal::move(gmock_p3)) #define GMOCK_INTERNAL_INIT_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4)\ (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ - p3##_type gmock_p3, p4##_type gmock_p4) : p0(gmock_p0), p1(gmock_p1), \ - p2(gmock_p2), p3(gmock_p3), p4(gmock_p4) + p3##_type gmock_p3, \ + p4##_type gmock_p4) : p0(::testing::internal::move(gmock_p0)), \ + p1(::testing::internal::move(gmock_p1)), \ + p2(::testing::internal::move(gmock_p2)), \ + p3(::testing::internal::move(gmock_p3)), \ + p4(::testing::internal::move(gmock_p4)) #define GMOCK_INTERNAL_INIT_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5)\ (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ p3##_type gmock_p3, p4##_type gmock_p4, \ - p5##_type gmock_p5) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), \ - p3(gmock_p3), p4(gmock_p4), p5(gmock_p5) + p5##_type gmock_p5) : p0(::testing::internal::move(gmock_p0)), \ + p1(::testing::internal::move(gmock_p1)), \ + p2(::testing::internal::move(gmock_p2)), \ + p3(::testing::internal::move(gmock_p3)), \ + p4(::testing::internal::move(gmock_p4)), \ + p5(::testing::internal::move(gmock_p5)) #define GMOCK_INTERNAL_INIT_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6)\ (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \ - p6##_type gmock_p6) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), \ - p3(gmock_p3), p4(gmock_p4), p5(gmock_p5), p6(gmock_p6) + p6##_type gmock_p6) : p0(::testing::internal::move(gmock_p0)), \ + p1(::testing::internal::move(gmock_p1)), \ + p2(::testing::internal::move(gmock_p2)), \ + p3(::testing::internal::move(gmock_p3)), \ + p4(::testing::internal::move(gmock_p4)), \ + p5(::testing::internal::move(gmock_p5)), \ + p6(::testing::internal::move(gmock_p6)) #define GMOCK_INTERNAL_INIT_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7)\ (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \ - p6##_type gmock_p6, p7##_type gmock_p7) : p0(gmock_p0), p1(gmock_p1), \ - p2(gmock_p2), p3(gmock_p3), p4(gmock_p4), p5(gmock_p5), p6(gmock_p6), \ - p7(gmock_p7) + p6##_type gmock_p6, \ + p7##_type gmock_p7) : p0(::testing::internal::move(gmock_p0)), \ + p1(::testing::internal::move(gmock_p1)), \ + p2(::testing::internal::move(gmock_p2)), \ + p3(::testing::internal::move(gmock_p3)), \ + p4(::testing::internal::move(gmock_p4)), \ + p5(::testing::internal::move(gmock_p5)), \ + p6(::testing::internal::move(gmock_p6)), \ + p7(::testing::internal::move(gmock_p7)) #define GMOCK_INTERNAL_INIT_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \ p7, p8)\ (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \ p6##_type gmock_p6, p7##_type gmock_p7, \ - p8##_type gmock_p8) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), \ - p3(gmock_p3), p4(gmock_p4), p5(gmock_p5), p6(gmock_p6), p7(gmock_p7), \ - p8(gmock_p8) + p8##_type gmock_p8) : p0(::testing::internal::move(gmock_p0)), \ + p1(::testing::internal::move(gmock_p1)), \ + p2(::testing::internal::move(gmock_p2)), \ + p3(::testing::internal::move(gmock_p3)), \ + p4(::testing::internal::move(gmock_p4)), \ + p5(::testing::internal::move(gmock_p5)), \ + p6(::testing::internal::move(gmock_p6)), \ + p7(::testing::internal::move(gmock_p7)), \ + p8(::testing::internal::move(gmock_p8)) #define GMOCK_INTERNAL_INIT_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \ p7, p8, p9)\ (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \ p6##_type gmock_p6, p7##_type gmock_p7, p8##_type gmock_p8, \ - p9##_type gmock_p9) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), \ - p3(gmock_p3), p4(gmock_p4), p5(gmock_p5), p6(gmock_p6), p7(gmock_p7), \ - p8(gmock_p8), p9(gmock_p9) + p9##_type gmock_p9) : p0(::testing::internal::move(gmock_p0)), \ + p1(::testing::internal::move(gmock_p1)), \ + p2(::testing::internal::move(gmock_p2)), \ + p3(::testing::internal::move(gmock_p3)), \ + p4(::testing::internal::move(gmock_p4)), \ + p5(::testing::internal::move(gmock_p5)), \ + p6(::testing::internal::move(gmock_p6)), \ + p7(::testing::internal::move(gmock_p7)), \ + p8(::testing::internal::move(gmock_p8)), \ + p9(::testing::internal::move(gmock_p9)) // Declares the fields for storing the value parameters. #define GMOCK_INTERNAL_DEFN_AND_0_VALUE_PARAMS() @@ -1354,7 +1480,8 @@ DoAll(Action1 a1, Action2 a2, Action3 a3, Action4 a4, Action5 a5, Action6 a6, template <typename p0##_type>\ class name##ActionP {\ public:\ - explicit name##ActionP(p0##_type gmock_p0) : p0(gmock_p0) {}\ + explicit name##ActionP(p0##_type gmock_p0) : \ + p0(::testing::internal::forward<p0##_type>(gmock_p0)) {}\ template <typename F>\ class gmock_Impl : public ::testing::ActionInterface<F> {\ public:\ @@ -1362,7 +1489,8 @@ DoAll(Action1 a1, Action2 a2, Action3 a3, Action4 a4, Action5 a5, Action6 a6, typedef typename ::testing::internal::Function<F>::Result return_type;\ typedef typename ::testing::internal::Function<F>::ArgumentTuple\ args_type;\ - explicit gmock_Impl(p0##_type gmock_p0) : p0(gmock_p0) {}\ + explicit gmock_Impl(p0##_type gmock_p0) : \ + p0(::testing::internal::forward<p0##_type>(gmock_p0)) {}\ virtual return_type Perform(const args_type& args) {\ return ::testing::internal::ActionHelper<return_type, gmock_Impl>::\ Perform(this, args);\ @@ -1404,8 +1532,9 @@ DoAll(Action1 a1, Action2 a2, Action3 a3, Action4 a4, Action5 a5, Action6 a6, template <typename p0##_type, typename p1##_type>\ class name##ActionP2 {\ public:\ - name##ActionP2(p0##_type gmock_p0, p1##_type gmock_p1) : p0(gmock_p0), \ - p1(gmock_p1) {}\ + name##ActionP2(p0##_type gmock_p0, \ + p1##_type gmock_p1) : p0(::testing::internal::forward<p0##_type>(gmock_p0)), \ + p1(::testing::internal::forward<p1##_type>(gmock_p1)) {}\ template <typename F>\ class gmock_Impl : public ::testing::ActionInterface<F> {\ public:\ @@ -1413,8 +1542,9 @@ DoAll(Action1 a1, Action2 a2, Action3 a3, Action4 a4, Action5 a5, Action6 a6, typedef typename ::testing::internal::Function<F>::Result return_type;\ typedef typename ::testing::internal::Function<F>::ArgumentTuple\ args_type;\ - gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1) : p0(gmock_p0), \ - p1(gmock_p1) {}\ + gmock_Impl(p0##_type gmock_p0, \ + p1##_type gmock_p1) : p0(::testing::internal::forward<p0##_type>(gmock_p0)), \ + p1(::testing::internal::forward<p1##_type>(gmock_p1)) {}\ virtual return_type Perform(const args_type& args) {\ return ::testing::internal::ActionHelper<return_type, gmock_Impl>::\ Perform(this, args);\ @@ -1460,7 +1590,9 @@ DoAll(Action1 a1, Action2 a2, Action3 a3, Action4 a4, Action5 a5, Action6 a6, class name##ActionP3 {\ public:\ name##ActionP3(p0##_type gmock_p0, p1##_type gmock_p1, \ - p2##_type gmock_p2) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2) {}\ + p2##_type gmock_p2) : p0(::testing::internal::forward<p0##_type>(gmock_p0)), \ + p1(::testing::internal::forward<p1##_type>(gmock_p1)), \ + p2(::testing::internal::forward<p2##_type>(gmock_p2)) {}\ template <typename F>\ class gmock_Impl : public ::testing::ActionInterface<F> {\ public:\ @@ -1469,7 +1601,9 @@ DoAll(Action1 a1, Action2 a2, Action3 a3, Action4 a4, Action5 a5, Action6 a6, typedef typename ::testing::internal::Function<F>::ArgumentTuple\ args_type;\ gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, \ - p2##_type gmock_p2) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2) {}\ + p2##_type gmock_p2) : p0(::testing::internal::forward<p0##_type>(gmock_p0)), \ + p1(::testing::internal::forward<p1##_type>(gmock_p1)), \ + p2(::testing::internal::forward<p2##_type>(gmock_p2)) {}\ virtual return_type Perform(const args_type& args) {\ return ::testing::internal::ActionHelper<return_type, gmock_Impl>::\ Perform(this, args);\ @@ -1519,8 +1653,11 @@ DoAll(Action1 a1, Action2 a2, Action3 a3, Action4 a4, Action5 a5, Action6 a6, class name##ActionP4 {\ public:\ name##ActionP4(p0##_type gmock_p0, p1##_type gmock_p1, \ - p2##_type gmock_p2, p3##_type gmock_p3) : p0(gmock_p0), p1(gmock_p1), \ - p2(gmock_p2), p3(gmock_p3) {}\ + p2##_type gmock_p2, \ + p3##_type gmock_p3) : p0(::testing::internal::forward<p0##_type>(gmock_p0)), \ + p1(::testing::internal::forward<p1##_type>(gmock_p1)), \ + p2(::testing::internal::forward<p2##_type>(gmock_p2)), \ + p3(::testing::internal::forward<p3##_type>(gmock_p3)) {}\ template <typename F>\ class gmock_Impl : public ::testing::ActionInterface<F> {\ public:\ @@ -1529,8 +1666,10 @@ DoAll(Action1 a1, Action2 a2, Action3 a3, Action4 a4, Action5 a5, Action6 a6, typedef typename ::testing::internal::Function<F>::ArgumentTuple\ args_type;\ gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ - p3##_type gmock_p3) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), \ - p3(gmock_p3) {}\ + p3##_type gmock_p3) : p0(::testing::internal::forward<p0##_type>(gmock_p0)), \ + p1(::testing::internal::forward<p1##_type>(gmock_p1)), \ + p2(::testing::internal::forward<p2##_type>(gmock_p2)), \ + p3(::testing::internal::forward<p3##_type>(gmock_p3)) {}\ virtual return_type Perform(const args_type& args) {\ return ::testing::internal::ActionHelper<return_type, gmock_Impl>::\ Perform(this, args);\ @@ -1587,8 +1726,11 @@ DoAll(Action1 a1, Action2 a2, Action3 a3, Action4 a4, Action5 a5, Action6 a6, public:\ name##ActionP5(p0##_type gmock_p0, p1##_type gmock_p1, \ p2##_type gmock_p2, p3##_type gmock_p3, \ - p4##_type gmock_p4) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), \ - p3(gmock_p3), p4(gmock_p4) {}\ + p4##_type gmock_p4) : p0(::testing::internal::forward<p0##_type>(gmock_p0)), \ + p1(::testing::internal::forward<p1##_type>(gmock_p1)), \ + p2(::testing::internal::forward<p2##_type>(gmock_p2)), \ + p3(::testing::internal::forward<p3##_type>(gmock_p3)), \ + p4(::testing::internal::forward<p4##_type>(gmock_p4)) {}\ template <typename F>\ class gmock_Impl : public ::testing::ActionInterface<F> {\ public:\ @@ -1597,8 +1739,12 @@ DoAll(Action1 a1, Action2 a2, Action3 a3, Action4 a4, Action5 a5, Action6 a6, typedef typename ::testing::internal::Function<F>::ArgumentTuple\ args_type;\ gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ - p3##_type gmock_p3, p4##_type gmock_p4) : p0(gmock_p0), \ - p1(gmock_p1), p2(gmock_p2), p3(gmock_p3), p4(gmock_p4) {}\ + p3##_type gmock_p3, \ + p4##_type gmock_p4) : p0(::testing::internal::forward<p0##_type>(gmock_p0)), \ + p1(::testing::internal::forward<p1##_type>(gmock_p1)), \ + p2(::testing::internal::forward<p2##_type>(gmock_p2)), \ + p3(::testing::internal::forward<p3##_type>(gmock_p3)), \ + p4(::testing::internal::forward<p4##_type>(gmock_p4)) {}\ virtual return_type Perform(const args_type& args) {\ return ::testing::internal::ActionHelper<return_type, gmock_Impl>::\ Perform(this, args);\ @@ -1657,8 +1803,12 @@ DoAll(Action1 a1, Action2 a2, Action3 a3, Action4 a4, Action5 a5, Action6 a6, public:\ name##ActionP6(p0##_type gmock_p0, p1##_type gmock_p1, \ p2##_type gmock_p2, p3##_type gmock_p3, p4##_type gmock_p4, \ - p5##_type gmock_p5) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), \ - p3(gmock_p3), p4(gmock_p4), p5(gmock_p5) {}\ + p5##_type gmock_p5) : p0(::testing::internal::forward<p0##_type>(gmock_p0)), \ + p1(::testing::internal::forward<p1##_type>(gmock_p1)), \ + p2(::testing::internal::forward<p2##_type>(gmock_p2)), \ + p3(::testing::internal::forward<p3##_type>(gmock_p3)), \ + p4(::testing::internal::forward<p4##_type>(gmock_p4)), \ + p5(::testing::internal::forward<p5##_type>(gmock_p5)) {}\ template <typename F>\ class gmock_Impl : public ::testing::ActionInterface<F> {\ public:\ @@ -1668,8 +1818,12 @@ DoAll(Action1 a1, Action2 a2, Action3 a3, Action4 a4, Action5 a5, Action6 a6, args_type;\ gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ p3##_type gmock_p3, p4##_type gmock_p4, \ - p5##_type gmock_p5) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), \ - p3(gmock_p3), p4(gmock_p4), p5(gmock_p5) {}\ + p5##_type gmock_p5) : p0(::testing::internal::forward<p0##_type>(gmock_p0)), \ + p1(::testing::internal::forward<p1##_type>(gmock_p1)), \ + p2(::testing::internal::forward<p2##_type>(gmock_p2)), \ + p3(::testing::internal::forward<p3##_type>(gmock_p3)), \ + p4(::testing::internal::forward<p4##_type>(gmock_p4)), \ + p5(::testing::internal::forward<p5##_type>(gmock_p5)) {}\ virtual return_type Perform(const args_type& args) {\ return ::testing::internal::ActionHelper<return_type, gmock_Impl>::\ Perform(this, args);\ @@ -1731,9 +1885,14 @@ DoAll(Action1 a1, Action2 a2, Action3 a3, Action4 a4, Action5 a5, Action6 a6, public:\ name##ActionP7(p0##_type gmock_p0, p1##_type gmock_p1, \ p2##_type gmock_p2, p3##_type gmock_p3, p4##_type gmock_p4, \ - p5##_type gmock_p5, p6##_type gmock_p6) : p0(gmock_p0), p1(gmock_p1), \ - p2(gmock_p2), p3(gmock_p3), p4(gmock_p4), p5(gmock_p5), \ - p6(gmock_p6) {}\ + p5##_type gmock_p5, \ + p6##_type gmock_p6) : p0(::testing::internal::forward<p0##_type>(gmock_p0)), \ + p1(::testing::internal::forward<p1##_type>(gmock_p1)), \ + p2(::testing::internal::forward<p2##_type>(gmock_p2)), \ + p3(::testing::internal::forward<p3##_type>(gmock_p3)), \ + p4(::testing::internal::forward<p4##_type>(gmock_p4)), \ + p5(::testing::internal::forward<p5##_type>(gmock_p5)), \ + p6(::testing::internal::forward<p6##_type>(gmock_p6)) {}\ template <typename F>\ class gmock_Impl : public ::testing::ActionInterface<F> {\ public:\ @@ -1743,8 +1902,13 @@ DoAll(Action1 a1, Action2 a2, Action3 a3, Action4 a4, Action5 a5, Action6 a6, args_type;\ gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \ - p6##_type gmock_p6) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), \ - p3(gmock_p3), p4(gmock_p4), p5(gmock_p5), p6(gmock_p6) {}\ + p6##_type gmock_p6) : p0(::testing::internal::forward<p0##_type>(gmock_p0)), \ + p1(::testing::internal::forward<p1##_type>(gmock_p1)), \ + p2(::testing::internal::forward<p2##_type>(gmock_p2)), \ + p3(::testing::internal::forward<p3##_type>(gmock_p3)), \ + p4(::testing::internal::forward<p4##_type>(gmock_p4)), \ + p5(::testing::internal::forward<p5##_type>(gmock_p5)), \ + p6(::testing::internal::forward<p6##_type>(gmock_p6)) {}\ virtual return_type Perform(const args_type& args) {\ return ::testing::internal::ActionHelper<return_type, gmock_Impl>::\ Perform(this, args);\ @@ -1813,9 +1977,14 @@ DoAll(Action1 a1, Action2 a2, Action3 a3, Action4 a4, Action5 a5, Action6 a6, name##ActionP8(p0##_type gmock_p0, p1##_type gmock_p1, \ p2##_type gmock_p2, p3##_type gmock_p3, p4##_type gmock_p4, \ p5##_type gmock_p5, p6##_type gmock_p6, \ - p7##_type gmock_p7) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), \ - p3(gmock_p3), p4(gmock_p4), p5(gmock_p5), p6(gmock_p6), \ - p7(gmock_p7) {}\ + p7##_type gmock_p7) : p0(::testing::internal::forward<p0##_type>(gmock_p0)), \ + p1(::testing::internal::forward<p1##_type>(gmock_p1)), \ + p2(::testing::internal::forward<p2##_type>(gmock_p2)), \ + p3(::testing::internal::forward<p3##_type>(gmock_p3)), \ + p4(::testing::internal::forward<p4##_type>(gmock_p4)), \ + p5(::testing::internal::forward<p5##_type>(gmock_p5)), \ + p6(::testing::internal::forward<p6##_type>(gmock_p6)), \ + p7(::testing::internal::forward<p7##_type>(gmock_p7)) {}\ template <typename F>\ class gmock_Impl : public ::testing::ActionInterface<F> {\ public:\ @@ -1825,9 +1994,15 @@ DoAll(Action1 a1, Action2 a2, Action3 a3, Action4 a4, Action5 a5, Action6 a6, args_type;\ gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \ - p6##_type gmock_p6, p7##_type gmock_p7) : p0(gmock_p0), \ - p1(gmock_p1), p2(gmock_p2), p3(gmock_p3), p4(gmock_p4), \ - p5(gmock_p5), p6(gmock_p6), p7(gmock_p7) {}\ + p6##_type gmock_p6, \ + p7##_type gmock_p7) : p0(::testing::internal::forward<p0##_type>(gmock_p0)), \ + p1(::testing::internal::forward<p1##_type>(gmock_p1)), \ + p2(::testing::internal::forward<p2##_type>(gmock_p2)), \ + p3(::testing::internal::forward<p3##_type>(gmock_p3)), \ + p4(::testing::internal::forward<p4##_type>(gmock_p4)), \ + p5(::testing::internal::forward<p5##_type>(gmock_p5)), \ + p6(::testing::internal::forward<p6##_type>(gmock_p6)), \ + p7(::testing::internal::forward<p7##_type>(gmock_p7)) {}\ virtual return_type Perform(const args_type& args) {\ return ::testing::internal::ActionHelper<return_type, gmock_Impl>::\ Perform(this, args);\ @@ -1900,9 +2075,15 @@ DoAll(Action1 a1, Action2 a2, Action3 a3, Action4 a4, Action5 a5, Action6 a6, name##ActionP9(p0##_type gmock_p0, p1##_type gmock_p1, \ p2##_type gmock_p2, p3##_type gmock_p3, p4##_type gmock_p4, \ p5##_type gmock_p5, p6##_type gmock_p6, p7##_type gmock_p7, \ - p8##_type gmock_p8) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), \ - p3(gmock_p3), p4(gmock_p4), p5(gmock_p5), p6(gmock_p6), p7(gmock_p7), \ - p8(gmock_p8) {}\ + p8##_type gmock_p8) : p0(::testing::internal::forward<p0##_type>(gmock_p0)), \ + p1(::testing::internal::forward<p1##_type>(gmock_p1)), \ + p2(::testing::internal::forward<p2##_type>(gmock_p2)), \ + p3(::testing::internal::forward<p3##_type>(gmock_p3)), \ + p4(::testing::internal::forward<p4##_type>(gmock_p4)), \ + p5(::testing::internal::forward<p5##_type>(gmock_p5)), \ + p6(::testing::internal::forward<p6##_type>(gmock_p6)), \ + p7(::testing::internal::forward<p7##_type>(gmock_p7)), \ + p8(::testing::internal::forward<p8##_type>(gmock_p8)) {}\ template <typename F>\ class gmock_Impl : public ::testing::ActionInterface<F> {\ public:\ @@ -1913,9 +2094,15 @@ DoAll(Action1 a1, Action2 a2, Action3 a3, Action4 a4, Action5 a5, Action6 a6, gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \ p6##_type gmock_p6, p7##_type gmock_p7, \ - p8##_type gmock_p8) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), \ - p3(gmock_p3), p4(gmock_p4), p5(gmock_p5), p6(gmock_p6), \ - p7(gmock_p7), p8(gmock_p8) {}\ + p8##_type gmock_p8) : p0(::testing::internal::forward<p0##_type>(gmock_p0)), \ + p1(::testing::internal::forward<p1##_type>(gmock_p1)), \ + p2(::testing::internal::forward<p2##_type>(gmock_p2)), \ + p3(::testing::internal::forward<p3##_type>(gmock_p3)), \ + p4(::testing::internal::forward<p4##_type>(gmock_p4)), \ + p5(::testing::internal::forward<p5##_type>(gmock_p5)), \ + p6(::testing::internal::forward<p6##_type>(gmock_p6)), \ + p7(::testing::internal::forward<p7##_type>(gmock_p7)), \ + p8(::testing::internal::forward<p8##_type>(gmock_p8)) {}\ virtual return_type Perform(const args_type& args) {\ return ::testing::internal::ActionHelper<return_type, gmock_Impl>::\ Perform(this, args);\ @@ -1992,9 +2179,17 @@ DoAll(Action1 a1, Action2 a2, Action3 a3, Action4 a4, Action5 a5, Action6 a6, name##ActionP10(p0##_type gmock_p0, p1##_type gmock_p1, \ p2##_type gmock_p2, p3##_type gmock_p3, p4##_type gmock_p4, \ p5##_type gmock_p5, p6##_type gmock_p6, p7##_type gmock_p7, \ - p8##_type gmock_p8, p9##_type gmock_p9) : p0(gmock_p0), p1(gmock_p1), \ - p2(gmock_p2), p3(gmock_p3), p4(gmock_p4), p5(gmock_p5), p6(gmock_p6), \ - p7(gmock_p7), p8(gmock_p8), p9(gmock_p9) {}\ + p8##_type gmock_p8, \ + p9##_type gmock_p9) : p0(::testing::internal::forward<p0##_type>(gmock_p0)), \ + p1(::testing::internal::forward<p1##_type>(gmock_p1)), \ + p2(::testing::internal::forward<p2##_type>(gmock_p2)), \ + p3(::testing::internal::forward<p3##_type>(gmock_p3)), \ + p4(::testing::internal::forward<p4##_type>(gmock_p4)), \ + p5(::testing::internal::forward<p5##_type>(gmock_p5)), \ + p6(::testing::internal::forward<p6##_type>(gmock_p6)), \ + p7(::testing::internal::forward<p7##_type>(gmock_p7)), \ + p8(::testing::internal::forward<p8##_type>(gmock_p8)), \ + p9(::testing::internal::forward<p9##_type>(gmock_p9)) {}\ template <typename F>\ class gmock_Impl : public ::testing::ActionInterface<F> {\ public:\ @@ -2005,9 +2200,16 @@ DoAll(Action1 a1, Action2 a2, Action3 a3, Action4 a4, Action5 a5, Action6 a6, gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \ p6##_type gmock_p6, p7##_type gmock_p7, p8##_type gmock_p8, \ - p9##_type gmock_p9) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), \ - p3(gmock_p3), p4(gmock_p4), p5(gmock_p5), p6(gmock_p6), \ - p7(gmock_p7), p8(gmock_p8), p9(gmock_p9) {}\ + p9##_type gmock_p9) : p0(::testing::internal::forward<p0##_type>(gmock_p0)), \ + p1(::testing::internal::forward<p1##_type>(gmock_p1)), \ + p2(::testing::internal::forward<p2##_type>(gmock_p2)), \ + p3(::testing::internal::forward<p3##_type>(gmock_p3)), \ + p4(::testing::internal::forward<p4##_type>(gmock_p4)), \ + p5(::testing::internal::forward<p5##_type>(gmock_p5)), \ + p6(::testing::internal::forward<p6##_type>(gmock_p6)), \ + p7(::testing::internal::forward<p7##_type>(gmock_p7)), \ + p8(::testing::internal::forward<p8##_type>(gmock_p8)), \ + p9(::testing::internal::forward<p9##_type>(gmock_p9)) {}\ virtual return_type Perform(const args_type& args) {\ return ::testing::internal::ActionHelper<return_type, gmock_Impl>::\ Perform(this, args);\ @@ -2199,7 +2401,7 @@ ACTION_TEMPLATE(InvokeArgument, using internal::invoke_argument::InvokeArgumentAdl; return InvokeArgumentAdl<return_type>( internal::invoke_argument::AdlTag(), - ::testing::get<k>(args)); + ::std::get<k>(args)); } ACTION_TEMPLATE(InvokeArgument, @@ -2208,7 +2410,7 @@ ACTION_TEMPLATE(InvokeArgument, using internal::invoke_argument::InvokeArgumentAdl; return InvokeArgumentAdl<return_type>( internal::invoke_argument::AdlTag(), - ::testing::get<k>(args), p0); + ::std::get<k>(args), p0); } ACTION_TEMPLATE(InvokeArgument, @@ -2217,7 +2419,7 @@ ACTION_TEMPLATE(InvokeArgument, using internal::invoke_argument::InvokeArgumentAdl; return InvokeArgumentAdl<return_type>( internal::invoke_argument::AdlTag(), - ::testing::get<k>(args), p0, p1); + ::std::get<k>(args), p0, p1); } ACTION_TEMPLATE(InvokeArgument, @@ -2226,7 +2428,7 @@ ACTION_TEMPLATE(InvokeArgument, using internal::invoke_argument::InvokeArgumentAdl; return InvokeArgumentAdl<return_type>( internal::invoke_argument::AdlTag(), - ::testing::get<k>(args), p0, p1, p2); + ::std::get<k>(args), p0, p1, p2); } ACTION_TEMPLATE(InvokeArgument, @@ -2235,7 +2437,7 @@ ACTION_TEMPLATE(InvokeArgument, using internal::invoke_argument::InvokeArgumentAdl; return InvokeArgumentAdl<return_type>( internal::invoke_argument::AdlTag(), - ::testing::get<k>(args), p0, p1, p2, p3); + ::std::get<k>(args), p0, p1, p2, p3); } ACTION_TEMPLATE(InvokeArgument, @@ -2244,7 +2446,7 @@ ACTION_TEMPLATE(InvokeArgument, using internal::invoke_argument::InvokeArgumentAdl; return InvokeArgumentAdl<return_type>( internal::invoke_argument::AdlTag(), - ::testing::get<k>(args), p0, p1, p2, p3, p4); + ::std::get<k>(args), p0, p1, p2, p3, p4); } ACTION_TEMPLATE(InvokeArgument, @@ -2253,7 +2455,7 @@ ACTION_TEMPLATE(InvokeArgument, using internal::invoke_argument::InvokeArgumentAdl; return InvokeArgumentAdl<return_type>( internal::invoke_argument::AdlTag(), - ::testing::get<k>(args), p0, p1, p2, p3, p4, p5); + ::std::get<k>(args), p0, p1, p2, p3, p4, p5); } ACTION_TEMPLATE(InvokeArgument, @@ -2262,7 +2464,7 @@ ACTION_TEMPLATE(InvokeArgument, using internal::invoke_argument::InvokeArgumentAdl; return InvokeArgumentAdl<return_type>( internal::invoke_argument::AdlTag(), - ::testing::get<k>(args), p0, p1, p2, p3, p4, p5, p6); + ::std::get<k>(args), p0, p1, p2, p3, p4, p5, p6); } ACTION_TEMPLATE(InvokeArgument, @@ -2271,7 +2473,7 @@ ACTION_TEMPLATE(InvokeArgument, using internal::invoke_argument::InvokeArgumentAdl; return InvokeArgumentAdl<return_type>( internal::invoke_argument::AdlTag(), - ::testing::get<k>(args), p0, p1, p2, p3, p4, p5, p6, p7); + ::std::get<k>(args), p0, p1, p2, p3, p4, p5, p6, p7); } ACTION_TEMPLATE(InvokeArgument, @@ -2280,7 +2482,7 @@ ACTION_TEMPLATE(InvokeArgument, using internal::invoke_argument::InvokeArgumentAdl; return InvokeArgumentAdl<return_type>( internal::invoke_argument::AdlTag(), - ::testing::get<k>(args), p0, p1, p2, p3, p4, p5, p6, p7, p8); + ::std::get<k>(args), p0, p1, p2, p3, p4, p5, p6, p7, p8); } ACTION_TEMPLATE(InvokeArgument, @@ -2289,7 +2491,7 @@ ACTION_TEMPLATE(InvokeArgument, using internal::invoke_argument::InvokeArgumentAdl; return InvokeArgumentAdl<return_type>( internal::invoke_argument::AdlTag(), - ::testing::get<k>(args), p0, p1, p2, p3, p4, p5, p6, p7, p8, p9); + ::std::get<k>(args), p0, p1, p2, p3, p4, p5, p6, p7, p8, p9); } // Various overloads for ReturnNew<T>(). @@ -2369,7 +2571,7 @@ ACTION_TEMPLATE(ReturnNew, } // namespace testing -// Include any custom actions added by the local installation. +// Include any custom callback actions added by the local installation. // We must include this header at the end to make sure it can use the // declarations from this file. #include "gmock/internal/custom/gmock-generated-actions.h" diff --git a/googlemock/include/gmock/gmock-generated-actions.h.pump b/googlemock/include/gmock/gmock-generated-actions.h.pump index 66d9f9d..2794ebb 100644 --- a/googlemock/include/gmock/gmock-generated-actions.h.pump +++ b/googlemock/include/gmock/gmock-generated-actions.h.pump @@ -1,5 +1,5 @@ $$ -*- mode: c++; -*- -$$ This is a Pump source file. Please use Pump to convert it to +$$ This is a Pump source file. Please use Pump to convert it to $$ gmock-generated-actions.h. $$ $var n = 10 $$ The maximum arity we support. @@ -32,13 +32,14 @@ $$}} This meta comment fixes auto-indentation in editors. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // Google Mock - a framework for writing C++ mock classes. // // This file implements some commonly used variadic actions. +// GOOGLETEST_CM0002 DO NOT DELETE + #ifndef GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_ACTIONS_H_ #define GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_ACTIONS_H_ @@ -49,41 +50,79 @@ namespace testing { namespace internal { // InvokeHelper<F> knows how to unpack an N-tuple and invoke an N-ary -// function or method with the unpacked values, where F is a function -// type that takes N arguments. +// function, method, or callback with the unpacked values, where F is +// a function type that takes N arguments. template <typename Result, typename ArgumentTuple> class InvokeHelper; +$var max_callback_arity = 5 $range i 0..n $for i [[ $range j 1..i $var types = [[$for j [[, typename A$j]]]] $var as = [[$for j, [[A$j]]]] $var args = [[$if i==0 [[]] $else [[ args]]]] -$var gets = [[$for j, [[get<$(j - 1)>(args)]]]] +$var gets = [[$for j, [[std::get<$(j - 1)>(args)]]]] template <typename R$types> -class InvokeHelper<R, ::testing::tuple<$as> > { +class InvokeHelper<R, ::std::tuple<$as> > { public: template <typename Function> - static R Invoke(Function function, const ::testing::tuple<$as>&$args) { + static R Invoke(Function function, const ::std::tuple<$as>&$args) { return function($gets); } template <class Class, typename MethodPtr> static R InvokeMethod(Class* obj_ptr, MethodPtr method_ptr, - const ::testing::tuple<$as>&$args) { + const ::std::tuple<$as>&$args) { return (obj_ptr->*method_ptr)($gets); } + + +$if i <= max_callback_arity [[ + template <typename CallbackType> + static R InvokeCallback(CallbackType* callback, + const ::std::tuple<$as>&$args) { + return callback->Run($gets); + } +]] $else [[ + // There is no InvokeCallback() for $i-tuples +]] + }; ]] +// Implements the Invoke(callback) action. +template <typename CallbackType> +class InvokeCallbackAction { + public: + // The c'tor takes ownership of the callback. + explicit InvokeCallbackAction(CallbackType* callback) + : callback_(callback) { + callback->CheckIsRepeatable(); // Makes sure the callback is permanent. + } + + // This type conversion operator template allows Invoke(callback) to + // be used wherever the callback's type is compatible with that of + // the mock function, i.e. if the mock function's arguments can be + // implicitly converted to the callback's arguments and the + // callback's result can be implicitly converted to the mock + // function's result. + template <typename Result, typename ArgumentTuple> + Result Perform(const ArgumentTuple& args) const { + return InvokeHelper<Result, ArgumentTuple>::InvokeCallback( + callback_.get(), args); + } + private: + const linked_ptr<CallbackType> callback_; +}; + // An INTERNAL macro for extracting the type of a tuple field. It's // subject to change without notice - DO NOT USE IN USER CODE! #define GMOCK_FIELD_(Tuple, N) \ - typename ::testing::tuple_element<N, Tuple>::type + typename ::std::tuple_element<N, Tuple>::type $range i 1..n @@ -91,14 +130,14 @@ $range i 1..n // type of an n-ary function whose i-th (1-based) argument type is the // k{i}-th (0-based) field of ArgumentTuple, which must be a tuple // type, and whose return type is Result. For example, -// SelectArgs<int, ::testing::tuple<bool, char, double, long>, 0, 3>::type +// SelectArgs<int, ::std::tuple<bool, char, double, long>, 0, 3>::type // is int(bool, long). // // SelectArgs<Result, ArgumentTuple, k1, k2, ..., k_n>::Select(args) // returns the selected fields (k1, k2, ..., k_n) of args as a tuple. // For example, -// SelectArgs<int, tuple<bool, char, double>, 2, 0>::Select( -// ::testing::make_tuple(true, 'a', 2.5)) +// SelectArgs<int, std::tuple<bool, char, double>, 2, 0>::Select( +// ::std::make_tuple(true, 'a', 2.5)) // returns tuple (2.5, true). // // The numbers in list k1, k2, ..., k_n must be >= 0, where n can be @@ -111,7 +150,7 @@ class SelectArgs { typedef Result type($for i, [[GMOCK_FIELD_(ArgumentTuple, k$i)]]); typedef typename Function<type>::ArgumentTuple SelectedArgs; static SelectedArgs Select(const ArgumentTuple& args) { - return SelectedArgs($for i, [[get<k$i>(args)]]); + return SelectedArgs($for i, [[std::get<k$i>(args)]]); } }; @@ -127,7 +166,7 @@ class SelectArgs<Result, ArgumentTuple, typedef typename Function<type>::ArgumentTuple SelectedArgs; static SelectedArgs Select(const ArgumentTuple& [[]] $if i == 1 [[/* args */]] $else [[args]]) { - return SelectedArgs($for j1, [[get<k$j1>(args)]]); + return SelectedArgs($for j1, [[std::get<k$j1>(args)]]); } }; @@ -201,12 +240,12 @@ $range j 0..i-1 ]]]] $range j 0..i-1 $var As = [[$for j, [[A$j]]]] -$var as = [[$for j, [[get<$j>(args)]]]] +$var as = [[$for j, [[std::get<$j>(args)]]]] $range k 1..n-i $var eas = [[$for k, [[ExcessiveArg()]]]] $var arg_list = [[$if (i==0) | (i==n) [[$as$eas]] $else [[$as, $eas]]]] $template - static Result Perform(Impl* impl, const ::testing::tuple<$As>& args) { + static Result Perform(Impl* impl, const ::std::tuple<$As>& args) { return impl->template gmock_PerformImpl<$As>(args, $arg_list); } @@ -356,8 +395,8 @@ $range j2 2..i // // MORE INFORMATION: // -// To learn more about using these macros, please search for 'ACTION' -// on http://code.google.com/p/googlemock/wiki/CookBook. +// To learn more about using these macros, please search for 'ACTION' on +// https://github.com/google/googletest/blob/master/googlemock/docs/CookBook.md $range i 0..n $range k 0..n-1 @@ -393,7 +432,7 @@ $for k [[, \ // ACTION_TEMPLATE(DuplicateArg, // HAS_2_TEMPLATE_PARAMS(int, k, typename, T), // AND_1_VALUE_PARAMS(output)) { -// *output = T(::testing::get<k>(args)); +// *output = T(::std::get<k>(args)); // } // ... // int n; @@ -486,7 +525,7 @@ _VALUE_PARAMS($for j, [[p$j]]) $for j [[, typename p$j##_type]] $for i [[ $range j 0..i-1 #define GMOCK_INTERNAL_INIT_AND_$i[[]]_VALUE_PARAMS($for j, [[p$j]])\ - ($for j, [[p$j##_type gmock_p$j]])$if i>0 [[ : ]]$for j, [[p$j(gmock_p$j)]] + ($for j, [[p$j##_type gmock_p$j]])$if i>0 [[ : ]]$for j, [[p$j(::testing::internal::move(gmock_p$j))]] ]] @@ -619,7 +658,7 @@ $var class_name = [[name##Action[[$if i==0 [[]] $elif i==1 [[P]] $range j 0..i-1 $var ctor_param_list = [[$for j, [[p$j##_type gmock_p$j]]]] $var param_types_and_names = [[$for j, [[p$j##_type p$j]]]] -$var inits = [[$if i==0 [[]] $else [[ : $for j, [[p$j(gmock_p$j)]]]]]] +$var inits = [[$if i==0 [[]] $else [[ : $for j, [[p$j(::testing::internal::forward<p$j##_type>(gmock_p$j))]]]]]] $var param_field_decls = [[$for j [[ @@ -757,7 +796,7 @@ ACTION_TEMPLATE(InvokeArgument, using internal::invoke_argument::InvokeArgumentAdl; return InvokeArgumentAdl<return_type>( internal::invoke_argument::AdlTag(), - ::testing::get<k>(args)$for j [[, p$j]]); + ::std::get<k>(args)$for j [[, p$j]]); } ]] diff --git a/googlemock/include/gmock/gmock-generated-function-mockers.h b/googlemock/include/gmock/gmock-generated-function-mockers.h index 4fa5ca9..9886115 100644 --- a/googlemock/include/gmock/gmock-generated-function-mockers.h +++ b/googlemock/include/gmock/gmock-generated-function-mockers.h @@ -30,13 +30,14 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // Google Mock - a framework for writing C++ mock classes. // // This file implements function mockers of various arities. +// GOOGLETEST_CM0002 DO NOT DELETE + #ifndef GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_FUNCTION_MOCKERS_H_ #define GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_FUNCTION_MOCKERS_H_ @@ -68,8 +69,8 @@ class FunctionMocker<R()> : public typedef R F(); typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple; - MockSpec<F>& With() { - return this->current_spec(); + MockSpec<F> With() { + return MockSpec<F>(this, ::std::make_tuple()); } R Invoke() { @@ -88,9 +89,8 @@ class FunctionMocker<R(A1)> : public typedef R F(A1); typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple; - MockSpec<F>& With(const Matcher<A1>& m1) { - this->current_spec().SetMatchers(::testing::make_tuple(m1)); - return this->current_spec(); + MockSpec<F> With(const Matcher<A1>& m1) { + return MockSpec<F>(this, ::std::make_tuple(m1)); } R Invoke(A1 a1) { @@ -98,7 +98,7 @@ class FunctionMocker<R(A1)> : public // by the C++ standard [14.6.4] here, as the base class type is // dependent on the template argument (and thus shouldn't be // looked into when resolving InvokeWith). - return this->InvokeWith(ArgumentTuple(a1)); + return this->InvokeWith(ArgumentTuple(internal::forward<A1>(a1))); } }; @@ -109,9 +109,8 @@ class FunctionMocker<R(A1, A2)> : public typedef R F(A1, A2); typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple; - MockSpec<F>& With(const Matcher<A1>& m1, const Matcher<A2>& m2) { - this->current_spec().SetMatchers(::testing::make_tuple(m1, m2)); - return this->current_spec(); + MockSpec<F> With(const Matcher<A1>& m1, const Matcher<A2>& m2) { + return MockSpec<F>(this, ::std::make_tuple(m1, m2)); } R Invoke(A1 a1, A2 a2) { @@ -119,7 +118,8 @@ class FunctionMocker<R(A1, A2)> : public // by the C++ standard [14.6.4] here, as the base class type is // dependent on the template argument (and thus shouldn't be // looked into when resolving InvokeWith). - return this->InvokeWith(ArgumentTuple(a1, a2)); + return this->InvokeWith(ArgumentTuple(internal::forward<A1>(a1), + internal::forward<A2>(a2))); } }; @@ -130,10 +130,9 @@ class FunctionMocker<R(A1, A2, A3)> : public typedef R F(A1, A2, A3); typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple; - MockSpec<F>& With(const Matcher<A1>& m1, const Matcher<A2>& m2, + MockSpec<F> With(const Matcher<A1>& m1, const Matcher<A2>& m2, const Matcher<A3>& m3) { - this->current_spec().SetMatchers(::testing::make_tuple(m1, m2, m3)); - return this->current_spec(); + return MockSpec<F>(this, ::std::make_tuple(m1, m2, m3)); } R Invoke(A1 a1, A2 a2, A3 a3) { @@ -141,7 +140,8 @@ class FunctionMocker<R(A1, A2, A3)> : public // by the C++ standard [14.6.4] here, as the base class type is // dependent on the template argument (and thus shouldn't be // looked into when resolving InvokeWith). - return this->InvokeWith(ArgumentTuple(a1, a2, a3)); + return this->InvokeWith(ArgumentTuple(internal::forward<A1>(a1), + internal::forward<A2>(a2), internal::forward<A3>(a3))); } }; @@ -152,10 +152,9 @@ class FunctionMocker<R(A1, A2, A3, A4)> : public typedef R F(A1, A2, A3, A4); typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple; - MockSpec<F>& With(const Matcher<A1>& m1, const Matcher<A2>& m2, + MockSpec<F> With(const Matcher<A1>& m1, const Matcher<A2>& m2, const Matcher<A3>& m3, const Matcher<A4>& m4) { - this->current_spec().SetMatchers(::testing::make_tuple(m1, m2, m3, m4)); - return this->current_spec(); + return MockSpec<F>(this, ::std::make_tuple(m1, m2, m3, m4)); } R Invoke(A1 a1, A2 a2, A3 a3, A4 a4) { @@ -163,7 +162,9 @@ class FunctionMocker<R(A1, A2, A3, A4)> : public // by the C++ standard [14.6.4] here, as the base class type is // dependent on the template argument (and thus shouldn't be // looked into when resolving InvokeWith). - return this->InvokeWith(ArgumentTuple(a1, a2, a3, a4)); + return this->InvokeWith(ArgumentTuple(internal::forward<A1>(a1), + internal::forward<A2>(a2), internal::forward<A3>(a3), + internal::forward<A4>(a4))); } }; @@ -175,10 +176,9 @@ class FunctionMocker<R(A1, A2, A3, A4, A5)> : public typedef R F(A1, A2, A3, A4, A5); typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple; - MockSpec<F>& With(const Matcher<A1>& m1, const Matcher<A2>& m2, + MockSpec<F> With(const Matcher<A1>& m1, const Matcher<A2>& m2, const Matcher<A3>& m3, const Matcher<A4>& m4, const Matcher<A5>& m5) { - this->current_spec().SetMatchers(::testing::make_tuple(m1, m2, m3, m4, m5)); - return this->current_spec(); + return MockSpec<F>(this, ::std::make_tuple(m1, m2, m3, m4, m5)); } R Invoke(A1 a1, A2 a2, A3 a3, A4 a4, A5 a5) { @@ -186,7 +186,9 @@ class FunctionMocker<R(A1, A2, A3, A4, A5)> : public // by the C++ standard [14.6.4] here, as the base class type is // dependent on the template argument (and thus shouldn't be // looked into when resolving InvokeWith). - return this->InvokeWith(ArgumentTuple(a1, a2, a3, a4, a5)); + return this->InvokeWith(ArgumentTuple(internal::forward<A1>(a1), + internal::forward<A2>(a2), internal::forward<A3>(a3), + internal::forward<A4>(a4), internal::forward<A5>(a5))); } }; @@ -198,12 +200,10 @@ class FunctionMocker<R(A1, A2, A3, A4, A5, A6)> : public typedef R F(A1, A2, A3, A4, A5, A6); typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple; - MockSpec<F>& With(const Matcher<A1>& m1, const Matcher<A2>& m2, + MockSpec<F> With(const Matcher<A1>& m1, const Matcher<A2>& m2, const Matcher<A3>& m3, const Matcher<A4>& m4, const Matcher<A5>& m5, const Matcher<A6>& m6) { - this->current_spec().SetMatchers(::testing::make_tuple(m1, m2, m3, m4, m5, - m6)); - return this->current_spec(); + return MockSpec<F>(this, ::std::make_tuple(m1, m2, m3, m4, m5, m6)); } R Invoke(A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6) { @@ -211,7 +211,10 @@ class FunctionMocker<R(A1, A2, A3, A4, A5, A6)> : public // by the C++ standard [14.6.4] here, as the base class type is // dependent on the template argument (and thus shouldn't be // looked into when resolving InvokeWith). - return this->InvokeWith(ArgumentTuple(a1, a2, a3, a4, a5, a6)); + return this->InvokeWith(ArgumentTuple(internal::forward<A1>(a1), + internal::forward<A2>(a2), internal::forward<A3>(a3), + internal::forward<A4>(a4), internal::forward<A5>(a5), + internal::forward<A6>(a6))); } }; @@ -223,12 +226,10 @@ class FunctionMocker<R(A1, A2, A3, A4, A5, A6, A7)> : public typedef R F(A1, A2, A3, A4, A5, A6, A7); typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple; - MockSpec<F>& With(const Matcher<A1>& m1, const Matcher<A2>& m2, + MockSpec<F> With(const Matcher<A1>& m1, const Matcher<A2>& m2, const Matcher<A3>& m3, const Matcher<A4>& m4, const Matcher<A5>& m5, const Matcher<A6>& m6, const Matcher<A7>& m7) { - this->current_spec().SetMatchers(::testing::make_tuple(m1, m2, m3, m4, m5, - m6, m7)); - return this->current_spec(); + return MockSpec<F>(this, ::std::make_tuple(m1, m2, m3, m4, m5, m6, m7)); } R Invoke(A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6, A7 a7) { @@ -236,7 +237,10 @@ class FunctionMocker<R(A1, A2, A3, A4, A5, A6, A7)> : public // by the C++ standard [14.6.4] here, as the base class type is // dependent on the template argument (and thus shouldn't be // looked into when resolving InvokeWith). - return this->InvokeWith(ArgumentTuple(a1, a2, a3, a4, a5, a6, a7)); + return this->InvokeWith(ArgumentTuple(internal::forward<A1>(a1), + internal::forward<A2>(a2), internal::forward<A3>(a3), + internal::forward<A4>(a4), internal::forward<A5>(a5), + internal::forward<A6>(a6), internal::forward<A7>(a7))); } }; @@ -248,12 +252,10 @@ class FunctionMocker<R(A1, A2, A3, A4, A5, A6, A7, A8)> : public typedef R F(A1, A2, A3, A4, A5, A6, A7, A8); typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple; - MockSpec<F>& With(const Matcher<A1>& m1, const Matcher<A2>& m2, + MockSpec<F> With(const Matcher<A1>& m1, const Matcher<A2>& m2, const Matcher<A3>& m3, const Matcher<A4>& m4, const Matcher<A5>& m5, const Matcher<A6>& m6, const Matcher<A7>& m7, const Matcher<A8>& m8) { - this->current_spec().SetMatchers(::testing::make_tuple(m1, m2, m3, m4, m5, - m6, m7, m8)); - return this->current_spec(); + return MockSpec<F>(this, ::std::make_tuple(m1, m2, m3, m4, m5, m6, m7, m8)); } R Invoke(A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6, A7 a7, A8 a8) { @@ -261,7 +263,11 @@ class FunctionMocker<R(A1, A2, A3, A4, A5, A6, A7, A8)> : public // by the C++ standard [14.6.4] here, as the base class type is // dependent on the template argument (and thus shouldn't be // looked into when resolving InvokeWith). - return this->InvokeWith(ArgumentTuple(a1, a2, a3, a4, a5, a6, a7, a8)); + return this->InvokeWith(ArgumentTuple(internal::forward<A1>(a1), + internal::forward<A2>(a2), internal::forward<A3>(a3), + internal::forward<A4>(a4), internal::forward<A5>(a5), + internal::forward<A6>(a6), internal::forward<A7>(a7), + internal::forward<A8>(a8))); } }; @@ -273,13 +279,12 @@ class FunctionMocker<R(A1, A2, A3, A4, A5, A6, A7, A8, A9)> : public typedef R F(A1, A2, A3, A4, A5, A6, A7, A8, A9); typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple; - MockSpec<F>& With(const Matcher<A1>& m1, const Matcher<A2>& m2, + MockSpec<F> With(const Matcher<A1>& m1, const Matcher<A2>& m2, const Matcher<A3>& m3, const Matcher<A4>& m4, const Matcher<A5>& m5, const Matcher<A6>& m6, const Matcher<A7>& m7, const Matcher<A8>& m8, const Matcher<A9>& m9) { - this->current_spec().SetMatchers(::testing::make_tuple(m1, m2, m3, m4, m5, - m6, m7, m8, m9)); - return this->current_spec(); + return MockSpec<F>(this, ::std::make_tuple(m1, m2, m3, m4, m5, m6, m7, m8, + m9)); } R Invoke(A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6, A7 a7, A8 a8, A9 a9) { @@ -287,7 +292,11 @@ class FunctionMocker<R(A1, A2, A3, A4, A5, A6, A7, A8, A9)> : public // by the C++ standard [14.6.4] here, as the base class type is // dependent on the template argument (and thus shouldn't be // looked into when resolving InvokeWith). - return this->InvokeWith(ArgumentTuple(a1, a2, a3, a4, a5, a6, a7, a8, a9)); + return this->InvokeWith(ArgumentTuple(internal::forward<A1>(a1), + internal::forward<A2>(a2), internal::forward<A3>(a3), + internal::forward<A4>(a4), internal::forward<A5>(a5), + internal::forward<A6>(a6), internal::forward<A7>(a7), + internal::forward<A8>(a8), internal::forward<A9>(a9))); } }; @@ -300,13 +309,12 @@ class FunctionMocker<R(A1, A2, A3, A4, A5, A6, A7, A8, A9, A10)> : public typedef R F(A1, A2, A3, A4, A5, A6, A7, A8, A9, A10); typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple; - MockSpec<F>& With(const Matcher<A1>& m1, const Matcher<A2>& m2, + MockSpec<F> With(const Matcher<A1>& m1, const Matcher<A2>& m2, const Matcher<A3>& m3, const Matcher<A4>& m4, const Matcher<A5>& m5, const Matcher<A6>& m6, const Matcher<A7>& m7, const Matcher<A8>& m8, const Matcher<A9>& m9, const Matcher<A10>& m10) { - this->current_spec().SetMatchers(::testing::make_tuple(m1, m2, m3, m4, m5, - m6, m7, m8, m9, m10)); - return this->current_spec(); + return MockSpec<F>(this, ::std::make_tuple(m1, m2, m3, m4, m5, m6, m7, m8, + m9, m10)); } R Invoke(A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6, A7 a7, A8 a8, A9 a9, @@ -315,11 +323,67 @@ class FunctionMocker<R(A1, A2, A3, A4, A5, A6, A7, A8, A9, A10)> : public // by the C++ standard [14.6.4] here, as the base class type is // dependent on the template argument (and thus shouldn't be // looked into when resolving InvokeWith). - return this->InvokeWith(ArgumentTuple(a1, a2, a3, a4, a5, a6, a7, a8, a9, - a10)); + return this->InvokeWith(ArgumentTuple(internal::forward<A1>(a1), + internal::forward<A2>(a2), internal::forward<A3>(a3), + internal::forward<A4>(a4), internal::forward<A5>(a5), + internal::forward<A6>(a6), internal::forward<A7>(a7), + internal::forward<A8>(a8), internal::forward<A9>(a9), + internal::forward<A10>(a10))); } }; +// Removes the given pointer; this is a helper for the expectation setter method +// for parameterless matchers. +// +// We want to make sure that the user cannot set a parameterless expectation on +// overloaded methods, including methods which are overloaded on const. Example: +// +// class MockClass { +// MOCK_METHOD0(GetName, string&()); +// MOCK_CONST_METHOD0(GetName, const string&()); +// }; +// +// TEST() { +// // This should be an error, as it's not clear which overload is expected. +// EXPECT_CALL(mock, GetName).WillOnce(ReturnRef(value)); +// } +// +// Here are the generated expectation-setter methods: +// +// class MockClass { +// // Overload 1 +// MockSpec<string&()> gmock_GetName() { ... } +// // Overload 2. Declared const so that the compiler will generate an +// // error when trying to resolve between this and overload 4 in +// // 'gmock_GetName(WithoutMatchers(), nullptr)'. +// MockSpec<string&()> gmock_GetName( +// const WithoutMatchers&, const Function<string&()>*) const { +// // Removes const from this, calls overload 1 +// return AdjustConstness_(this)->gmock_GetName(); +// } +// +// // Overload 3 +// const string& gmock_GetName() const { ... } +// // Overload 4 +// MockSpec<const string&()> gmock_GetName( +// const WithoutMatchers&, const Function<const string&()>*) const { +// // Does not remove const, calls overload 3 +// return AdjustConstness_const(this)->gmock_GetName(); +// } +// } +// +template <typename MockType> +const MockType* AdjustConstness_const(const MockType* mock) { + return mock; +} + +// Removes const from and returns the given pointer; this is a helper for the +// expectation setter method for parameterless matchers. +template <typename MockType> +MockType* AdjustConstness_(const MockType* mock) { + return const_cast<MockType*>(mock); +} + } // namespace internal // The style guide prohibits "using" statements in a namespace scope @@ -356,18 +420,24 @@ using internal::FunctionMocker; #define GMOCK_METHOD0_(tn, constness, ct, Method, ...) \ GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \ ) constness { \ - GTEST_COMPILE_ASSERT_((::testing::tuple_size< \ + GTEST_COMPILE_ASSERT_((::std::tuple_size< \ tn ::testing::internal::Function<__VA_ARGS__>::ArgumentTuple>::value \ == 0), \ this_method_does_not_take_0_arguments); \ GMOCK_MOCKER_(0, constness, Method).SetOwnerAndName(this, #Method); \ return GMOCK_MOCKER_(0, constness, Method).Invoke(); \ } \ - ::testing::MockSpec<__VA_ARGS__>& \ + ::testing::MockSpec<__VA_ARGS__> \ gmock_##Method() constness { \ GMOCK_MOCKER_(0, constness, Method).RegisterOwner(this); \ return GMOCK_MOCKER_(0, constness, Method).With(); \ } \ + ::testing::MockSpec<__VA_ARGS__> gmock_##Method( \ + const ::testing::internal::WithoutMatchers&, \ + constness ::testing::internal::Function<__VA_ARGS__>* ) const { \ + return ::testing::internal::AdjustConstness_##constness(this)-> \ + gmock_##Method(); \ + } \ mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(0, constness, \ Method) @@ -375,57 +445,78 @@ using internal::FunctionMocker; #define GMOCK_METHOD1_(tn, constness, ct, Method, ...) \ GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \ GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1) constness { \ - GTEST_COMPILE_ASSERT_((::testing::tuple_size< \ + GTEST_COMPILE_ASSERT_((::std::tuple_size< \ tn ::testing::internal::Function<__VA_ARGS__>::ArgumentTuple>::value \ == 1), \ this_method_does_not_take_1_argument); \ GMOCK_MOCKER_(1, constness, Method).SetOwnerAndName(this, #Method); \ - return GMOCK_MOCKER_(1, constness, Method).Invoke(gmock_a1); \ + return GMOCK_MOCKER_(1, constness, \ + Method).Invoke(::testing::internal::forward<GMOCK_ARG_(tn, 1, \ + __VA_ARGS__)>(gmock_a1)); \ } \ - ::testing::MockSpec<__VA_ARGS__>& \ + ::testing::MockSpec<__VA_ARGS__> \ gmock_##Method(GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1) constness { \ GMOCK_MOCKER_(1, constness, Method).RegisterOwner(this); \ return GMOCK_MOCKER_(1, constness, Method).With(gmock_a1); \ } \ + ::testing::MockSpec<__VA_ARGS__> gmock_##Method( \ + const ::testing::internal::WithoutMatchers&, \ + constness ::testing::internal::Function<__VA_ARGS__>* ) const { \ + return ::testing::internal::AdjustConstness_##constness(this)-> \ + gmock_##Method(::testing::A<GMOCK_ARG_(tn, 1, __VA_ARGS__)>()); \ + } \ mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(1, constness, \ Method) // INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!! #define GMOCK_METHOD2_(tn, constness, ct, Method, ...) \ GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \ - GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, \ - GMOCK_ARG_(tn, 2, __VA_ARGS__) gmock_a2) constness { \ - GTEST_COMPILE_ASSERT_((::testing::tuple_size< \ + GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, GMOCK_ARG_(tn, 2, \ + __VA_ARGS__) gmock_a2) constness { \ + GTEST_COMPILE_ASSERT_((::std::tuple_size< \ tn ::testing::internal::Function<__VA_ARGS__>::ArgumentTuple>::value \ == 2), \ this_method_does_not_take_2_arguments); \ GMOCK_MOCKER_(2, constness, Method).SetOwnerAndName(this, #Method); \ - return GMOCK_MOCKER_(2, constness, Method).Invoke(gmock_a1, gmock_a2); \ + return GMOCK_MOCKER_(2, constness, \ + Method).Invoke(::testing::internal::forward<GMOCK_ARG_(tn, 1, \ + __VA_ARGS__)>(gmock_a1), \ + ::testing::internal::forward<GMOCK_ARG_(tn, 2, __VA_ARGS__)>(gmock_a2)); \ } \ - ::testing::MockSpec<__VA_ARGS__>& \ + ::testing::MockSpec<__VA_ARGS__> \ gmock_##Method(GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1, \ GMOCK_MATCHER_(tn, 2, __VA_ARGS__) gmock_a2) constness { \ GMOCK_MOCKER_(2, constness, Method).RegisterOwner(this); \ return GMOCK_MOCKER_(2, constness, Method).With(gmock_a1, gmock_a2); \ } \ + ::testing::MockSpec<__VA_ARGS__> gmock_##Method( \ + const ::testing::internal::WithoutMatchers&, \ + constness ::testing::internal::Function<__VA_ARGS__>* ) const { \ + return ::testing::internal::AdjustConstness_##constness(this)-> \ + gmock_##Method(::testing::A<GMOCK_ARG_(tn, 1, __VA_ARGS__)>(), \ + ::testing::A<GMOCK_ARG_(tn, 2, __VA_ARGS__)>()); \ + } \ mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(2, constness, \ Method) // INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!! #define GMOCK_METHOD3_(tn, constness, ct, Method, ...) \ GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \ - GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, \ - GMOCK_ARG_(tn, 2, __VA_ARGS__) gmock_a2, \ - GMOCK_ARG_(tn, 3, __VA_ARGS__) gmock_a3) constness { \ - GTEST_COMPILE_ASSERT_((::testing::tuple_size< \ + GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, GMOCK_ARG_(tn, 2, \ + __VA_ARGS__) gmock_a2, GMOCK_ARG_(tn, 3, \ + __VA_ARGS__) gmock_a3) constness { \ + GTEST_COMPILE_ASSERT_((::std::tuple_size< \ tn ::testing::internal::Function<__VA_ARGS__>::ArgumentTuple>::value \ == 3), \ this_method_does_not_take_3_arguments); \ GMOCK_MOCKER_(3, constness, Method).SetOwnerAndName(this, #Method); \ - return GMOCK_MOCKER_(3, constness, Method).Invoke(gmock_a1, gmock_a2, \ - gmock_a3); \ + return GMOCK_MOCKER_(3, constness, \ + Method).Invoke(::testing::internal::forward<GMOCK_ARG_(tn, 1, \ + __VA_ARGS__)>(gmock_a1), \ + ::testing::internal::forward<GMOCK_ARG_(tn, 2, __VA_ARGS__)>(gmock_a2), \ + ::testing::internal::forward<GMOCK_ARG_(tn, 3, __VA_ARGS__)>(gmock_a3)); \ } \ - ::testing::MockSpec<__VA_ARGS__>& \ + ::testing::MockSpec<__VA_ARGS__> \ gmock_##Method(GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1, \ GMOCK_MATCHER_(tn, 2, __VA_ARGS__) gmock_a2, \ GMOCK_MATCHER_(tn, 3, __VA_ARGS__) gmock_a3) constness { \ @@ -433,25 +524,36 @@ using internal::FunctionMocker; return GMOCK_MOCKER_(3, constness, Method).With(gmock_a1, gmock_a2, \ gmock_a3); \ } \ + ::testing::MockSpec<__VA_ARGS__> gmock_##Method( \ + const ::testing::internal::WithoutMatchers&, \ + constness ::testing::internal::Function<__VA_ARGS__>* ) const { \ + return ::testing::internal::AdjustConstness_##constness(this)-> \ + gmock_##Method(::testing::A<GMOCK_ARG_(tn, 1, __VA_ARGS__)>(), \ + ::testing::A<GMOCK_ARG_(tn, 2, __VA_ARGS__)>(), \ + ::testing::A<GMOCK_ARG_(tn, 3, __VA_ARGS__)>()); \ + } \ mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(3, constness, \ Method) // INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!! #define GMOCK_METHOD4_(tn, constness, ct, Method, ...) \ GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \ - GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, \ - GMOCK_ARG_(tn, 2, __VA_ARGS__) gmock_a2, \ - GMOCK_ARG_(tn, 3, __VA_ARGS__) gmock_a3, \ - GMOCK_ARG_(tn, 4, __VA_ARGS__) gmock_a4) constness { \ - GTEST_COMPILE_ASSERT_((::testing::tuple_size< \ + GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, GMOCK_ARG_(tn, 2, \ + __VA_ARGS__) gmock_a2, GMOCK_ARG_(tn, 3, __VA_ARGS__) gmock_a3, \ + GMOCK_ARG_(tn, 4, __VA_ARGS__) gmock_a4) constness { \ + GTEST_COMPILE_ASSERT_((::std::tuple_size< \ tn ::testing::internal::Function<__VA_ARGS__>::ArgumentTuple>::value \ == 4), \ this_method_does_not_take_4_arguments); \ GMOCK_MOCKER_(4, constness, Method).SetOwnerAndName(this, #Method); \ - return GMOCK_MOCKER_(4, constness, Method).Invoke(gmock_a1, gmock_a2, \ - gmock_a3, gmock_a4); \ + return GMOCK_MOCKER_(4, constness, \ + Method).Invoke(::testing::internal::forward<GMOCK_ARG_(tn, 1, \ + __VA_ARGS__)>(gmock_a1), \ + ::testing::internal::forward<GMOCK_ARG_(tn, 2, __VA_ARGS__)>(gmock_a2), \ + ::testing::internal::forward<GMOCK_ARG_(tn, 3, __VA_ARGS__)>(gmock_a3), \ + ::testing::internal::forward<GMOCK_ARG_(tn, 4, __VA_ARGS__)>(gmock_a4)); \ } \ - ::testing::MockSpec<__VA_ARGS__>& \ + ::testing::MockSpec<__VA_ARGS__> \ gmock_##Method(GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1, \ GMOCK_MATCHER_(tn, 2, __VA_ARGS__) gmock_a2, \ GMOCK_MATCHER_(tn, 3, __VA_ARGS__) gmock_a3, \ @@ -460,26 +562,39 @@ using internal::FunctionMocker; return GMOCK_MOCKER_(4, constness, Method).With(gmock_a1, gmock_a2, \ gmock_a3, gmock_a4); \ } \ + ::testing::MockSpec<__VA_ARGS__> gmock_##Method( \ + const ::testing::internal::WithoutMatchers&, \ + constness ::testing::internal::Function<__VA_ARGS__>* ) const { \ + return ::testing::internal::AdjustConstness_##constness(this)-> \ + gmock_##Method(::testing::A<GMOCK_ARG_(tn, 1, __VA_ARGS__)>(), \ + ::testing::A<GMOCK_ARG_(tn, 2, __VA_ARGS__)>(), \ + ::testing::A<GMOCK_ARG_(tn, 3, __VA_ARGS__)>(), \ + ::testing::A<GMOCK_ARG_(tn, 4, __VA_ARGS__)>()); \ + } \ mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(4, constness, \ Method) // INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!! #define GMOCK_METHOD5_(tn, constness, ct, Method, ...) \ GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \ - GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, \ - GMOCK_ARG_(tn, 2, __VA_ARGS__) gmock_a2, \ - GMOCK_ARG_(tn, 3, __VA_ARGS__) gmock_a3, \ - GMOCK_ARG_(tn, 4, __VA_ARGS__) gmock_a4, \ - GMOCK_ARG_(tn, 5, __VA_ARGS__) gmock_a5) constness { \ - GTEST_COMPILE_ASSERT_((::testing::tuple_size< \ + GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, GMOCK_ARG_(tn, 2, \ + __VA_ARGS__) gmock_a2, GMOCK_ARG_(tn, 3, __VA_ARGS__) gmock_a3, \ + GMOCK_ARG_(tn, 4, __VA_ARGS__) gmock_a4, GMOCK_ARG_(tn, 5, \ + __VA_ARGS__) gmock_a5) constness { \ + GTEST_COMPILE_ASSERT_((::std::tuple_size< \ tn ::testing::internal::Function<__VA_ARGS__>::ArgumentTuple>::value \ == 5), \ this_method_does_not_take_5_arguments); \ GMOCK_MOCKER_(5, constness, Method).SetOwnerAndName(this, #Method); \ - return GMOCK_MOCKER_(5, constness, Method).Invoke(gmock_a1, gmock_a2, \ - gmock_a3, gmock_a4, gmock_a5); \ + return GMOCK_MOCKER_(5, constness, \ + Method).Invoke(::testing::internal::forward<GMOCK_ARG_(tn, 1, \ + __VA_ARGS__)>(gmock_a1), \ + ::testing::internal::forward<GMOCK_ARG_(tn, 2, __VA_ARGS__)>(gmock_a2), \ + ::testing::internal::forward<GMOCK_ARG_(tn, 3, __VA_ARGS__)>(gmock_a3), \ + ::testing::internal::forward<GMOCK_ARG_(tn, 4, __VA_ARGS__)>(gmock_a4), \ + ::testing::internal::forward<GMOCK_ARG_(tn, 5, __VA_ARGS__)>(gmock_a5)); \ } \ - ::testing::MockSpec<__VA_ARGS__>& \ + ::testing::MockSpec<__VA_ARGS__> \ gmock_##Method(GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1, \ GMOCK_MATCHER_(tn, 2, __VA_ARGS__) gmock_a2, \ GMOCK_MATCHER_(tn, 3, __VA_ARGS__) gmock_a3, \ @@ -489,27 +604,42 @@ using internal::FunctionMocker; return GMOCK_MOCKER_(5, constness, Method).With(gmock_a1, gmock_a2, \ gmock_a3, gmock_a4, gmock_a5); \ } \ + ::testing::MockSpec<__VA_ARGS__> gmock_##Method( \ + const ::testing::internal::WithoutMatchers&, \ + constness ::testing::internal::Function<__VA_ARGS__>* ) const { \ + return ::testing::internal::AdjustConstness_##constness(this)-> \ + gmock_##Method(::testing::A<GMOCK_ARG_(tn, 1, __VA_ARGS__)>(), \ + ::testing::A<GMOCK_ARG_(tn, 2, __VA_ARGS__)>(), \ + ::testing::A<GMOCK_ARG_(tn, 3, __VA_ARGS__)>(), \ + ::testing::A<GMOCK_ARG_(tn, 4, __VA_ARGS__)>(), \ + ::testing::A<GMOCK_ARG_(tn, 5, __VA_ARGS__)>()); \ + } \ mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(5, constness, \ Method) // INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!! #define GMOCK_METHOD6_(tn, constness, ct, Method, ...) \ GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \ - GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, \ - GMOCK_ARG_(tn, 2, __VA_ARGS__) gmock_a2, \ - GMOCK_ARG_(tn, 3, __VA_ARGS__) gmock_a3, \ - GMOCK_ARG_(tn, 4, __VA_ARGS__) gmock_a4, \ - GMOCK_ARG_(tn, 5, __VA_ARGS__) gmock_a5, \ - GMOCK_ARG_(tn, 6, __VA_ARGS__) gmock_a6) constness { \ - GTEST_COMPILE_ASSERT_((::testing::tuple_size< \ + GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, GMOCK_ARG_(tn, 2, \ + __VA_ARGS__) gmock_a2, GMOCK_ARG_(tn, 3, __VA_ARGS__) gmock_a3, \ + GMOCK_ARG_(tn, 4, __VA_ARGS__) gmock_a4, GMOCK_ARG_(tn, 5, \ + __VA_ARGS__) gmock_a5, GMOCK_ARG_(tn, 6, \ + __VA_ARGS__) gmock_a6) constness { \ + GTEST_COMPILE_ASSERT_((::std::tuple_size< \ tn ::testing::internal::Function<__VA_ARGS__>::ArgumentTuple>::value \ == 6), \ this_method_does_not_take_6_arguments); \ GMOCK_MOCKER_(6, constness, Method).SetOwnerAndName(this, #Method); \ - return GMOCK_MOCKER_(6, constness, Method).Invoke(gmock_a1, gmock_a2, \ - gmock_a3, gmock_a4, gmock_a5, gmock_a6); \ + return GMOCK_MOCKER_(6, constness, \ + Method).Invoke(::testing::internal::forward<GMOCK_ARG_(tn, 1, \ + __VA_ARGS__)>(gmock_a1), \ + ::testing::internal::forward<GMOCK_ARG_(tn, 2, __VA_ARGS__)>(gmock_a2), \ + ::testing::internal::forward<GMOCK_ARG_(tn, 3, __VA_ARGS__)>(gmock_a3), \ + ::testing::internal::forward<GMOCK_ARG_(tn, 4, __VA_ARGS__)>(gmock_a4), \ + ::testing::internal::forward<GMOCK_ARG_(tn, 5, __VA_ARGS__)>(gmock_a5), \ + ::testing::internal::forward<GMOCK_ARG_(tn, 6, __VA_ARGS__)>(gmock_a6)); \ } \ - ::testing::MockSpec<__VA_ARGS__>& \ + ::testing::MockSpec<__VA_ARGS__> \ gmock_##Method(GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1, \ GMOCK_MATCHER_(tn, 2, __VA_ARGS__) gmock_a2, \ GMOCK_MATCHER_(tn, 3, __VA_ARGS__) gmock_a3, \ @@ -520,28 +650,44 @@ using internal::FunctionMocker; return GMOCK_MOCKER_(6, constness, Method).With(gmock_a1, gmock_a2, \ gmock_a3, gmock_a4, gmock_a5, gmock_a6); \ } \ + ::testing::MockSpec<__VA_ARGS__> gmock_##Method( \ + const ::testing::internal::WithoutMatchers&, \ + constness ::testing::internal::Function<__VA_ARGS__>* ) const { \ + return ::testing::internal::AdjustConstness_##constness(this)-> \ + gmock_##Method(::testing::A<GMOCK_ARG_(tn, 1, __VA_ARGS__)>(), \ + ::testing::A<GMOCK_ARG_(tn, 2, __VA_ARGS__)>(), \ + ::testing::A<GMOCK_ARG_(tn, 3, __VA_ARGS__)>(), \ + ::testing::A<GMOCK_ARG_(tn, 4, __VA_ARGS__)>(), \ + ::testing::A<GMOCK_ARG_(tn, 5, __VA_ARGS__)>(), \ + ::testing::A<GMOCK_ARG_(tn, 6, __VA_ARGS__)>()); \ + } \ mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(6, constness, \ Method) // INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!! #define GMOCK_METHOD7_(tn, constness, ct, Method, ...) \ GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \ - GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, \ - GMOCK_ARG_(tn, 2, __VA_ARGS__) gmock_a2, \ - GMOCK_ARG_(tn, 3, __VA_ARGS__) gmock_a3, \ - GMOCK_ARG_(tn, 4, __VA_ARGS__) gmock_a4, \ - GMOCK_ARG_(tn, 5, __VA_ARGS__) gmock_a5, \ - GMOCK_ARG_(tn, 6, __VA_ARGS__) gmock_a6, \ - GMOCK_ARG_(tn, 7, __VA_ARGS__) gmock_a7) constness { \ - GTEST_COMPILE_ASSERT_((::testing::tuple_size< \ + GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, GMOCK_ARG_(tn, 2, \ + __VA_ARGS__) gmock_a2, GMOCK_ARG_(tn, 3, __VA_ARGS__) gmock_a3, \ + GMOCK_ARG_(tn, 4, __VA_ARGS__) gmock_a4, GMOCK_ARG_(tn, 5, \ + __VA_ARGS__) gmock_a5, GMOCK_ARG_(tn, 6, __VA_ARGS__) gmock_a6, \ + GMOCK_ARG_(tn, 7, __VA_ARGS__) gmock_a7) constness { \ + GTEST_COMPILE_ASSERT_((::std::tuple_size< \ tn ::testing::internal::Function<__VA_ARGS__>::ArgumentTuple>::value \ == 7), \ this_method_does_not_take_7_arguments); \ GMOCK_MOCKER_(7, constness, Method).SetOwnerAndName(this, #Method); \ - return GMOCK_MOCKER_(7, constness, Method).Invoke(gmock_a1, gmock_a2, \ - gmock_a3, gmock_a4, gmock_a5, gmock_a6, gmock_a7); \ + return GMOCK_MOCKER_(7, constness, \ + Method).Invoke(::testing::internal::forward<GMOCK_ARG_(tn, 1, \ + __VA_ARGS__)>(gmock_a1), \ + ::testing::internal::forward<GMOCK_ARG_(tn, 2, __VA_ARGS__)>(gmock_a2), \ + ::testing::internal::forward<GMOCK_ARG_(tn, 3, __VA_ARGS__)>(gmock_a3), \ + ::testing::internal::forward<GMOCK_ARG_(tn, 4, __VA_ARGS__)>(gmock_a4), \ + ::testing::internal::forward<GMOCK_ARG_(tn, 5, __VA_ARGS__)>(gmock_a5), \ + ::testing::internal::forward<GMOCK_ARG_(tn, 6, __VA_ARGS__)>(gmock_a6), \ + ::testing::internal::forward<GMOCK_ARG_(tn, 7, __VA_ARGS__)>(gmock_a7)); \ } \ - ::testing::MockSpec<__VA_ARGS__>& \ + ::testing::MockSpec<__VA_ARGS__> \ gmock_##Method(GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1, \ GMOCK_MATCHER_(tn, 2, __VA_ARGS__) gmock_a2, \ GMOCK_MATCHER_(tn, 3, __VA_ARGS__) gmock_a3, \ @@ -553,29 +699,47 @@ using internal::FunctionMocker; return GMOCK_MOCKER_(7, constness, Method).With(gmock_a1, gmock_a2, \ gmock_a3, gmock_a4, gmock_a5, gmock_a6, gmock_a7); \ } \ + ::testing::MockSpec<__VA_ARGS__> gmock_##Method( \ + const ::testing::internal::WithoutMatchers&, \ + constness ::testing::internal::Function<__VA_ARGS__>* ) const { \ + return ::testing::internal::AdjustConstness_##constness(this)-> \ + gmock_##Method(::testing::A<GMOCK_ARG_(tn, 1, __VA_ARGS__)>(), \ + ::testing::A<GMOCK_ARG_(tn, 2, __VA_ARGS__)>(), \ + ::testing::A<GMOCK_ARG_(tn, 3, __VA_ARGS__)>(), \ + ::testing::A<GMOCK_ARG_(tn, 4, __VA_ARGS__)>(), \ + ::testing::A<GMOCK_ARG_(tn, 5, __VA_ARGS__)>(), \ + ::testing::A<GMOCK_ARG_(tn, 6, __VA_ARGS__)>(), \ + ::testing::A<GMOCK_ARG_(tn, 7, __VA_ARGS__)>()); \ + } \ mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(7, constness, \ Method) // INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!! #define GMOCK_METHOD8_(tn, constness, ct, Method, ...) \ GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \ - GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, \ - GMOCK_ARG_(tn, 2, __VA_ARGS__) gmock_a2, \ - GMOCK_ARG_(tn, 3, __VA_ARGS__) gmock_a3, \ - GMOCK_ARG_(tn, 4, __VA_ARGS__) gmock_a4, \ - GMOCK_ARG_(tn, 5, __VA_ARGS__) gmock_a5, \ - GMOCK_ARG_(tn, 6, __VA_ARGS__) gmock_a6, \ - GMOCK_ARG_(tn, 7, __VA_ARGS__) gmock_a7, \ - GMOCK_ARG_(tn, 8, __VA_ARGS__) gmock_a8) constness { \ - GTEST_COMPILE_ASSERT_((::testing::tuple_size< \ + GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, GMOCK_ARG_(tn, 2, \ + __VA_ARGS__) gmock_a2, GMOCK_ARG_(tn, 3, __VA_ARGS__) gmock_a3, \ + GMOCK_ARG_(tn, 4, __VA_ARGS__) gmock_a4, GMOCK_ARG_(tn, 5, \ + __VA_ARGS__) gmock_a5, GMOCK_ARG_(tn, 6, __VA_ARGS__) gmock_a6, \ + GMOCK_ARG_(tn, 7, __VA_ARGS__) gmock_a7, GMOCK_ARG_(tn, 8, \ + __VA_ARGS__) gmock_a8) constness { \ + GTEST_COMPILE_ASSERT_((::std::tuple_size< \ tn ::testing::internal::Function<__VA_ARGS__>::ArgumentTuple>::value \ == 8), \ this_method_does_not_take_8_arguments); \ GMOCK_MOCKER_(8, constness, Method).SetOwnerAndName(this, #Method); \ - return GMOCK_MOCKER_(8, constness, Method).Invoke(gmock_a1, gmock_a2, \ - gmock_a3, gmock_a4, gmock_a5, gmock_a6, gmock_a7, gmock_a8); \ + return GMOCK_MOCKER_(8, constness, \ + Method).Invoke(::testing::internal::forward<GMOCK_ARG_(tn, 1, \ + __VA_ARGS__)>(gmock_a1), \ + ::testing::internal::forward<GMOCK_ARG_(tn, 2, __VA_ARGS__)>(gmock_a2), \ + ::testing::internal::forward<GMOCK_ARG_(tn, 3, __VA_ARGS__)>(gmock_a3), \ + ::testing::internal::forward<GMOCK_ARG_(tn, 4, __VA_ARGS__)>(gmock_a4), \ + ::testing::internal::forward<GMOCK_ARG_(tn, 5, __VA_ARGS__)>(gmock_a5), \ + ::testing::internal::forward<GMOCK_ARG_(tn, 6, __VA_ARGS__)>(gmock_a6), \ + ::testing::internal::forward<GMOCK_ARG_(tn, 7, __VA_ARGS__)>(gmock_a7), \ + ::testing::internal::forward<GMOCK_ARG_(tn, 8, __VA_ARGS__)>(gmock_a8)); \ } \ - ::testing::MockSpec<__VA_ARGS__>& \ + ::testing::MockSpec<__VA_ARGS__> \ gmock_##Method(GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1, \ GMOCK_MATCHER_(tn, 2, __VA_ARGS__) gmock_a2, \ GMOCK_MATCHER_(tn, 3, __VA_ARGS__) gmock_a3, \ @@ -588,31 +752,50 @@ using internal::FunctionMocker; return GMOCK_MOCKER_(8, constness, Method).With(gmock_a1, gmock_a2, \ gmock_a3, gmock_a4, gmock_a5, gmock_a6, gmock_a7, gmock_a8); \ } \ + ::testing::MockSpec<__VA_ARGS__> gmock_##Method( \ + const ::testing::internal::WithoutMatchers&, \ + constness ::testing::internal::Function<__VA_ARGS__>* ) const { \ + return ::testing::internal::AdjustConstness_##constness(this)-> \ + gmock_##Method(::testing::A<GMOCK_ARG_(tn, 1, __VA_ARGS__)>(), \ + ::testing::A<GMOCK_ARG_(tn, 2, __VA_ARGS__)>(), \ + ::testing::A<GMOCK_ARG_(tn, 3, __VA_ARGS__)>(), \ + ::testing::A<GMOCK_ARG_(tn, 4, __VA_ARGS__)>(), \ + ::testing::A<GMOCK_ARG_(tn, 5, __VA_ARGS__)>(), \ + ::testing::A<GMOCK_ARG_(tn, 6, __VA_ARGS__)>(), \ + ::testing::A<GMOCK_ARG_(tn, 7, __VA_ARGS__)>(), \ + ::testing::A<GMOCK_ARG_(tn, 8, __VA_ARGS__)>()); \ + } \ mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(8, constness, \ Method) // INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!! #define GMOCK_METHOD9_(tn, constness, ct, Method, ...) \ GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \ - GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, \ - GMOCK_ARG_(tn, 2, __VA_ARGS__) gmock_a2, \ - GMOCK_ARG_(tn, 3, __VA_ARGS__) gmock_a3, \ - GMOCK_ARG_(tn, 4, __VA_ARGS__) gmock_a4, \ - GMOCK_ARG_(tn, 5, __VA_ARGS__) gmock_a5, \ - GMOCK_ARG_(tn, 6, __VA_ARGS__) gmock_a6, \ - GMOCK_ARG_(tn, 7, __VA_ARGS__) gmock_a7, \ - GMOCK_ARG_(tn, 8, __VA_ARGS__) gmock_a8, \ - GMOCK_ARG_(tn, 9, __VA_ARGS__) gmock_a9) constness { \ - GTEST_COMPILE_ASSERT_((::testing::tuple_size< \ + GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, GMOCK_ARG_(tn, 2, \ + __VA_ARGS__) gmock_a2, GMOCK_ARG_(tn, 3, __VA_ARGS__) gmock_a3, \ + GMOCK_ARG_(tn, 4, __VA_ARGS__) gmock_a4, GMOCK_ARG_(tn, 5, \ + __VA_ARGS__) gmock_a5, GMOCK_ARG_(tn, 6, __VA_ARGS__) gmock_a6, \ + GMOCK_ARG_(tn, 7, __VA_ARGS__) gmock_a7, GMOCK_ARG_(tn, 8, \ + __VA_ARGS__) gmock_a8, GMOCK_ARG_(tn, 9, \ + __VA_ARGS__) gmock_a9) constness { \ + GTEST_COMPILE_ASSERT_((::std::tuple_size< \ tn ::testing::internal::Function<__VA_ARGS__>::ArgumentTuple>::value \ == 9), \ this_method_does_not_take_9_arguments); \ GMOCK_MOCKER_(9, constness, Method).SetOwnerAndName(this, #Method); \ - return GMOCK_MOCKER_(9, constness, Method).Invoke(gmock_a1, gmock_a2, \ - gmock_a3, gmock_a4, gmock_a5, gmock_a6, gmock_a7, gmock_a8, \ - gmock_a9); \ + return GMOCK_MOCKER_(9, constness, \ + Method).Invoke(::testing::internal::forward<GMOCK_ARG_(tn, 1, \ + __VA_ARGS__)>(gmock_a1), \ + ::testing::internal::forward<GMOCK_ARG_(tn, 2, __VA_ARGS__)>(gmock_a2), \ + ::testing::internal::forward<GMOCK_ARG_(tn, 3, __VA_ARGS__)>(gmock_a3), \ + ::testing::internal::forward<GMOCK_ARG_(tn, 4, __VA_ARGS__)>(gmock_a4), \ + ::testing::internal::forward<GMOCK_ARG_(tn, 5, __VA_ARGS__)>(gmock_a5), \ + ::testing::internal::forward<GMOCK_ARG_(tn, 6, __VA_ARGS__)>(gmock_a6), \ + ::testing::internal::forward<GMOCK_ARG_(tn, 7, __VA_ARGS__)>(gmock_a7), \ + ::testing::internal::forward<GMOCK_ARG_(tn, 8, __VA_ARGS__)>(gmock_a8), \ + ::testing::internal::forward<GMOCK_ARG_(tn, 9, __VA_ARGS__)>(gmock_a9)); \ } \ - ::testing::MockSpec<__VA_ARGS__>& \ + ::testing::MockSpec<__VA_ARGS__> \ gmock_##Method(GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1, \ GMOCK_MATCHER_(tn, 2, __VA_ARGS__) gmock_a2, \ GMOCK_MATCHER_(tn, 3, __VA_ARGS__) gmock_a3, \ @@ -627,32 +810,52 @@ using internal::FunctionMocker; gmock_a3, gmock_a4, gmock_a5, gmock_a6, gmock_a7, gmock_a8, \ gmock_a9); \ } \ + ::testing::MockSpec<__VA_ARGS__> gmock_##Method( \ + const ::testing::internal::WithoutMatchers&, \ + constness ::testing::internal::Function<__VA_ARGS__>* ) const { \ + return ::testing::internal::AdjustConstness_##constness(this)-> \ + gmock_##Method(::testing::A<GMOCK_ARG_(tn, 1, __VA_ARGS__)>(), \ + ::testing::A<GMOCK_ARG_(tn, 2, __VA_ARGS__)>(), \ + ::testing::A<GMOCK_ARG_(tn, 3, __VA_ARGS__)>(), \ + ::testing::A<GMOCK_ARG_(tn, 4, __VA_ARGS__)>(), \ + ::testing::A<GMOCK_ARG_(tn, 5, __VA_ARGS__)>(), \ + ::testing::A<GMOCK_ARG_(tn, 6, __VA_ARGS__)>(), \ + ::testing::A<GMOCK_ARG_(tn, 7, __VA_ARGS__)>(), \ + ::testing::A<GMOCK_ARG_(tn, 8, __VA_ARGS__)>(), \ + ::testing::A<GMOCK_ARG_(tn, 9, __VA_ARGS__)>()); \ + } \ mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(9, constness, \ Method) // INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!! #define GMOCK_METHOD10_(tn, constness, ct, Method, ...) \ GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \ - GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, \ - GMOCK_ARG_(tn, 2, __VA_ARGS__) gmock_a2, \ - GMOCK_ARG_(tn, 3, __VA_ARGS__) gmock_a3, \ - GMOCK_ARG_(tn, 4, __VA_ARGS__) gmock_a4, \ - GMOCK_ARG_(tn, 5, __VA_ARGS__) gmock_a5, \ - GMOCK_ARG_(tn, 6, __VA_ARGS__) gmock_a6, \ - GMOCK_ARG_(tn, 7, __VA_ARGS__) gmock_a7, \ - GMOCK_ARG_(tn, 8, __VA_ARGS__) gmock_a8, \ - GMOCK_ARG_(tn, 9, __VA_ARGS__) gmock_a9, \ - GMOCK_ARG_(tn, 10, __VA_ARGS__) gmock_a10) constness { \ - GTEST_COMPILE_ASSERT_((::testing::tuple_size< \ + GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, GMOCK_ARG_(tn, 2, \ + __VA_ARGS__) gmock_a2, GMOCK_ARG_(tn, 3, __VA_ARGS__) gmock_a3, \ + GMOCK_ARG_(tn, 4, __VA_ARGS__) gmock_a4, GMOCK_ARG_(tn, 5, \ + __VA_ARGS__) gmock_a5, GMOCK_ARG_(tn, 6, __VA_ARGS__) gmock_a6, \ + GMOCK_ARG_(tn, 7, __VA_ARGS__) gmock_a7, GMOCK_ARG_(tn, 8, \ + __VA_ARGS__) gmock_a8, GMOCK_ARG_(tn, 9, __VA_ARGS__) gmock_a9, \ + GMOCK_ARG_(tn, 10, __VA_ARGS__) gmock_a10) constness { \ + GTEST_COMPILE_ASSERT_((::std::tuple_size< \ tn ::testing::internal::Function<__VA_ARGS__>::ArgumentTuple>::value \ == 10), \ this_method_does_not_take_10_arguments); \ GMOCK_MOCKER_(10, constness, Method).SetOwnerAndName(this, #Method); \ - return GMOCK_MOCKER_(10, constness, Method).Invoke(gmock_a1, gmock_a2, \ - gmock_a3, gmock_a4, gmock_a5, gmock_a6, gmock_a7, gmock_a8, gmock_a9, \ - gmock_a10); \ + return GMOCK_MOCKER_(10, constness, \ + Method).Invoke(::testing::internal::forward<GMOCK_ARG_(tn, 1, \ + __VA_ARGS__)>(gmock_a1), \ + ::testing::internal::forward<GMOCK_ARG_(tn, 2, __VA_ARGS__)>(gmock_a2), \ + ::testing::internal::forward<GMOCK_ARG_(tn, 3, __VA_ARGS__)>(gmock_a3), \ + ::testing::internal::forward<GMOCK_ARG_(tn, 4, __VA_ARGS__)>(gmock_a4), \ + ::testing::internal::forward<GMOCK_ARG_(tn, 5, __VA_ARGS__)>(gmock_a5), \ + ::testing::internal::forward<GMOCK_ARG_(tn, 6, __VA_ARGS__)>(gmock_a6), \ + ::testing::internal::forward<GMOCK_ARG_(tn, 7, __VA_ARGS__)>(gmock_a7), \ + ::testing::internal::forward<GMOCK_ARG_(tn, 8, __VA_ARGS__)>(gmock_a8), \ + ::testing::internal::forward<GMOCK_ARG_(tn, 9, __VA_ARGS__)>(gmock_a9), \ + ::testing::internal::forward<GMOCK_ARG_(tn, 10, __VA_ARGS__)>(gmock_a10)); \ } \ - ::testing::MockSpec<__VA_ARGS__>& \ + ::testing::MockSpec<__VA_ARGS__> \ gmock_##Method(GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1, \ GMOCK_MATCHER_(tn, 2, __VA_ARGS__) gmock_a2, \ GMOCK_MATCHER_(tn, 3, __VA_ARGS__) gmock_a3, \ @@ -669,6 +872,21 @@ using internal::FunctionMocker; gmock_a3, gmock_a4, gmock_a5, gmock_a6, gmock_a7, gmock_a8, gmock_a9, \ gmock_a10); \ } \ + ::testing::MockSpec<__VA_ARGS__> gmock_##Method( \ + const ::testing::internal::WithoutMatchers&, \ + constness ::testing::internal::Function<__VA_ARGS__>* ) const { \ + return ::testing::internal::AdjustConstness_##constness(this)-> \ + gmock_##Method(::testing::A<GMOCK_ARG_(tn, 1, __VA_ARGS__)>(), \ + ::testing::A<GMOCK_ARG_(tn, 2, __VA_ARGS__)>(), \ + ::testing::A<GMOCK_ARG_(tn, 3, __VA_ARGS__)>(), \ + ::testing::A<GMOCK_ARG_(tn, 4, __VA_ARGS__)>(), \ + ::testing::A<GMOCK_ARG_(tn, 5, __VA_ARGS__)>(), \ + ::testing::A<GMOCK_ARG_(tn, 6, __VA_ARGS__)>(), \ + ::testing::A<GMOCK_ARG_(tn, 7, __VA_ARGS__)>(), \ + ::testing::A<GMOCK_ARG_(tn, 8, __VA_ARGS__)>(), \ + ::testing::A<GMOCK_ARG_(tn, 9, __VA_ARGS__)>(), \ + ::testing::A<GMOCK_ARG_(tn, 10, __VA_ARGS__)>()); \ + } \ mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(10, constness, \ Method) @@ -880,7 +1098,7 @@ class MockFunction<R()> { MOCK_METHOD0_T(Call, R()); #if GTEST_HAS_STD_FUNCTION_ - std::function<R()> AsStdFunction() { + ::std::function<R()> AsStdFunction() { return [this]() -> R { return this->Call(); }; @@ -899,9 +1117,9 @@ class MockFunction<R(A0)> { MOCK_METHOD1_T(Call, R(A0)); #if GTEST_HAS_STD_FUNCTION_ - std::function<R(A0)> AsStdFunction() { + ::std::function<R(A0)> AsStdFunction() { return [this](A0 a0) -> R { - return this->Call(a0); + return this->Call(::std::forward<A0>(a0)); }; } #endif // GTEST_HAS_STD_FUNCTION_ @@ -918,9 +1136,9 @@ class MockFunction<R(A0, A1)> { MOCK_METHOD2_T(Call, R(A0, A1)); #if GTEST_HAS_STD_FUNCTION_ - std::function<R(A0, A1)> AsStdFunction() { + ::std::function<R(A0, A1)> AsStdFunction() { return [this](A0 a0, A1 a1) -> R { - return this->Call(a0, a1); + return this->Call(::std::forward<A0>(a0), ::std::forward<A1>(a1)); }; } #endif // GTEST_HAS_STD_FUNCTION_ @@ -937,9 +1155,10 @@ class MockFunction<R(A0, A1, A2)> { MOCK_METHOD3_T(Call, R(A0, A1, A2)); #if GTEST_HAS_STD_FUNCTION_ - std::function<R(A0, A1, A2)> AsStdFunction() { + ::std::function<R(A0, A1, A2)> AsStdFunction() { return [this](A0 a0, A1 a1, A2 a2) -> R { - return this->Call(a0, a1, a2); + return this->Call(::std::forward<A0>(a0), ::std::forward<A1>(a1), + ::std::forward<A2>(a2)); }; } #endif // GTEST_HAS_STD_FUNCTION_ @@ -956,9 +1175,10 @@ class MockFunction<R(A0, A1, A2, A3)> { MOCK_METHOD4_T(Call, R(A0, A1, A2, A3)); #if GTEST_HAS_STD_FUNCTION_ - std::function<R(A0, A1, A2, A3)> AsStdFunction() { + ::std::function<R(A0, A1, A2, A3)> AsStdFunction() { return [this](A0 a0, A1 a1, A2 a2, A3 a3) -> R { - return this->Call(a0, a1, a2, a3); + return this->Call(::std::forward<A0>(a0), ::std::forward<A1>(a1), + ::std::forward<A2>(a2), ::std::forward<A3>(a3)); }; } #endif // GTEST_HAS_STD_FUNCTION_ @@ -976,9 +1196,11 @@ class MockFunction<R(A0, A1, A2, A3, A4)> { MOCK_METHOD5_T(Call, R(A0, A1, A2, A3, A4)); #if GTEST_HAS_STD_FUNCTION_ - std::function<R(A0, A1, A2, A3, A4)> AsStdFunction() { + ::std::function<R(A0, A1, A2, A3, A4)> AsStdFunction() { return [this](A0 a0, A1 a1, A2 a2, A3 a3, A4 a4) -> R { - return this->Call(a0, a1, a2, a3, a4); + return this->Call(::std::forward<A0>(a0), ::std::forward<A1>(a1), + ::std::forward<A2>(a2), ::std::forward<A3>(a3), + ::std::forward<A4>(a4)); }; } #endif // GTEST_HAS_STD_FUNCTION_ @@ -996,9 +1218,11 @@ class MockFunction<R(A0, A1, A2, A3, A4, A5)> { MOCK_METHOD6_T(Call, R(A0, A1, A2, A3, A4, A5)); #if GTEST_HAS_STD_FUNCTION_ - std::function<R(A0, A1, A2, A3, A4, A5)> AsStdFunction() { + ::std::function<R(A0, A1, A2, A3, A4, A5)> AsStdFunction() { return [this](A0 a0, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5) -> R { - return this->Call(a0, a1, a2, a3, a4, a5); + return this->Call(::std::forward<A0>(a0), ::std::forward<A1>(a1), + ::std::forward<A2>(a2), ::std::forward<A3>(a3), + ::std::forward<A4>(a4), ::std::forward<A5>(a5)); }; } #endif // GTEST_HAS_STD_FUNCTION_ @@ -1016,9 +1240,12 @@ class MockFunction<R(A0, A1, A2, A3, A4, A5, A6)> { MOCK_METHOD7_T(Call, R(A0, A1, A2, A3, A4, A5, A6)); #if GTEST_HAS_STD_FUNCTION_ - std::function<R(A0, A1, A2, A3, A4, A5, A6)> AsStdFunction() { + ::std::function<R(A0, A1, A2, A3, A4, A5, A6)> AsStdFunction() { return [this](A0 a0, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6) -> R { - return this->Call(a0, a1, a2, a3, a4, a5, a6); + return this->Call(::std::forward<A0>(a0), ::std::forward<A1>(a1), + ::std::forward<A2>(a2), ::std::forward<A3>(a3), + ::std::forward<A4>(a4), ::std::forward<A5>(a5), + ::std::forward<A6>(a6)); }; } #endif // GTEST_HAS_STD_FUNCTION_ @@ -1036,9 +1263,12 @@ class MockFunction<R(A0, A1, A2, A3, A4, A5, A6, A7)> { MOCK_METHOD8_T(Call, R(A0, A1, A2, A3, A4, A5, A6, A7)); #if GTEST_HAS_STD_FUNCTION_ - std::function<R(A0, A1, A2, A3, A4, A5, A6, A7)> AsStdFunction() { + ::std::function<R(A0, A1, A2, A3, A4, A5, A6, A7)> AsStdFunction() { return [this](A0 a0, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6, A7 a7) -> R { - return this->Call(a0, a1, a2, a3, a4, a5, a6, a7); + return this->Call(::std::forward<A0>(a0), ::std::forward<A1>(a1), + ::std::forward<A2>(a2), ::std::forward<A3>(a3), + ::std::forward<A4>(a4), ::std::forward<A5>(a5), + ::std::forward<A6>(a6), ::std::forward<A7>(a7)); }; } #endif // GTEST_HAS_STD_FUNCTION_ @@ -1056,10 +1286,14 @@ class MockFunction<R(A0, A1, A2, A3, A4, A5, A6, A7, A8)> { MOCK_METHOD9_T(Call, R(A0, A1, A2, A3, A4, A5, A6, A7, A8)); #if GTEST_HAS_STD_FUNCTION_ - std::function<R(A0, A1, A2, A3, A4, A5, A6, A7, A8)> AsStdFunction() { + ::std::function<R(A0, A1, A2, A3, A4, A5, A6, A7, A8)> AsStdFunction() { return [this](A0 a0, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6, A7 a7, A8 a8) -> R { - return this->Call(a0, a1, a2, a3, a4, a5, a6, a7, a8); + return this->Call(::std::forward<A0>(a0), ::std::forward<A1>(a1), + ::std::forward<A2>(a2), ::std::forward<A3>(a3), + ::std::forward<A4>(a4), ::std::forward<A5>(a5), + ::std::forward<A6>(a6), ::std::forward<A7>(a7), + ::std::forward<A8>(a8)); }; } #endif // GTEST_HAS_STD_FUNCTION_ @@ -1078,10 +1312,14 @@ class MockFunction<R(A0, A1, A2, A3, A4, A5, A6, A7, A8, A9)> { MOCK_METHOD10_T(Call, R(A0, A1, A2, A3, A4, A5, A6, A7, A8, A9)); #if GTEST_HAS_STD_FUNCTION_ - std::function<R(A0, A1, A2, A3, A4, A5, A6, A7, A8, A9)> AsStdFunction() { + ::std::function<R(A0, A1, A2, A3, A4, A5, A6, A7, A8, A9)> AsStdFunction() { return [this](A0 a0, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6, A7 a7, A8 a8, A9 a9) -> R { - return this->Call(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9); + return this->Call(::std::forward<A0>(a0), ::std::forward<A1>(a1), + ::std::forward<A2>(a2), ::std::forward<A3>(a3), + ::std::forward<A4>(a4), ::std::forward<A5>(a5), + ::std::forward<A6>(a6), ::std::forward<A7>(a7), + ::std::forward<A8>(a8), ::std::forward<A9>(a9)); }; } #endif // GTEST_HAS_STD_FUNCTION_ diff --git a/googlemock/include/gmock/gmock-generated-function-mockers.h.pump b/googlemock/include/gmock/gmock-generated-function-mockers.h.pump index 811502d..e05b18d 100644 --- a/googlemock/include/gmock/gmock-generated-function-mockers.h.pump +++ b/googlemock/include/gmock/gmock-generated-function-mockers.h.pump @@ -1,6 +1,6 @@ $$ -*- mode: c++; -*- -$$ This is a Pump source file. Please use Pump to convert it to -$$ gmock-generated-function-mockers.h. +$$ This is a Pump source file. Please use Pump to convert +$$ it to gmock-generated-function-mockers.h. $$ $var n = 10 $$ The maximum arity we support. // Copyright 2007, Google Inc. @@ -31,13 +31,14 @@ $var n = 10 $$ The maximum arity we support. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // Google Mock - a framework for writing C++ mock classes. // // This file implements function mockers of various arities. +// GOOGLETEST_CM0002 DO NOT DELETE + #ifndef GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_FUNCTION_MOCKERS_H_ #define GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_FUNCTION_MOCKERS_H_ @@ -68,7 +69,7 @@ $for i [[ $range j 1..i $var typename_As = [[$for j [[, typename A$j]]]] $var As = [[$for j, [[A$j]]]] -$var as = [[$for j, [[a$j]]]] +$var as = [[$for j, [[internal::forward<A$j>(a$j)]]]] $var Aas = [[$for j, [[A$j a$j]]]] $var ms = [[$for j, [[m$j]]]] $var matchers = [[$for j, [[const Matcher<A$j>& m$j]]]] @@ -79,13 +80,8 @@ class FunctionMocker<R($As)> : public typedef R F($As); typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple; - MockSpec<F>& With($matchers) { - -$if i >= 1 [[ - this->current_spec().SetMatchers(::testing::make_tuple($ms)); - -]] - return this->current_spec(); + MockSpec<F> With($matchers) { + return MockSpec<F>(this, ::std::make_tuple($ms)); } R Invoke($Aas) { @@ -99,6 +95,58 @@ $if i >= 1 [[ ]] +// Removes the given pointer; this is a helper for the expectation setter method +// for parameterless matchers. +// +// We want to make sure that the user cannot set a parameterless expectation on +// overloaded methods, including methods which are overloaded on const. Example: +// +// class MockClass { +// MOCK_METHOD0(GetName, string&()); +// MOCK_CONST_METHOD0(GetName, const string&()); +// }; +// +// TEST() { +// // This should be an error, as it's not clear which overload is expected. +// EXPECT_CALL(mock, GetName).WillOnce(ReturnRef(value)); +// } +// +// Here are the generated expectation-setter methods: +// +// class MockClass { +// // Overload 1 +// MockSpec<string&()> gmock_GetName() { ... } +// // Overload 2. Declared const so that the compiler will generate an +// // error when trying to resolve between this and overload 4 in +// // 'gmock_GetName(WithoutMatchers(), nullptr)'. +// MockSpec<string&()> gmock_GetName( +// const WithoutMatchers&, const Function<string&()>*) const { +// // Removes const from this, calls overload 1 +// return AdjustConstness_(this)->gmock_GetName(); +// } +// +// // Overload 3 +// const string& gmock_GetName() const { ... } +// // Overload 4 +// MockSpec<const string&()> gmock_GetName( +// const WithoutMatchers&, const Function<const string&()>*) const { +// // Does not remove const, calls overload 3 +// return AdjustConstness_const(this)->gmock_GetName(); +// } +// } +// +template <typename MockType> +const MockType* AdjustConstness_const(const MockType* mock) { + return mock; +} + +// Removes const from and returns the given pointer; this is a helper for the +// expectation setter method for parameterless matchers. +template <typename MockType> +MockType* AdjustConstness_(const MockType* mock) { + return const_cast<MockType*>(mock); +} + } // namespace internal // The style guide prohibits "using" statements in a namespace scope @@ -134,26 +182,35 @@ using internal::FunctionMocker; $for i [[ $range j 1..i -$var arg_as = [[$for j, \ - [[GMOCK_ARG_(tn, $j, __VA_ARGS__) gmock_a$j]]]] -$var as = [[$for j, [[gmock_a$j]]]] -$var matcher_as = [[$for j, \ +$var arg_as = [[$for j, [[GMOCK_ARG_(tn, $j, __VA_ARGS__) gmock_a$j]]]] +$var as = [[$for j, \ + [[::testing::internal::forward<GMOCK_ARG_(tn, $j, __VA_ARGS__)>(gmock_a$j)]]]] +$var matcher_arg_as = [[$for j, \ [[GMOCK_MATCHER_(tn, $j, __VA_ARGS__) gmock_a$j]]]] +$var matcher_as = [[$for j, [[gmock_a$j]]]] +$var anything_matchers = [[$for j, \ + [[::testing::A<GMOCK_ARG_(tn, $j, __VA_ARGS__)>()]]]] // INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!! #define GMOCK_METHOD$i[[]]_(tn, constness, ct, Method, ...) \ GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \ $arg_as) constness { \ - GTEST_COMPILE_ASSERT_((::testing::tuple_size< \ + GTEST_COMPILE_ASSERT_((::std::tuple_size< \ tn ::testing::internal::Function<__VA_ARGS__>::ArgumentTuple>::value == $i), \ this_method_does_not_take_$i[[]]_argument[[$if i != 1 [[s]]]]); \ GMOCK_MOCKER_($i, constness, Method).SetOwnerAndName(this, #Method); \ return GMOCK_MOCKER_($i, constness, Method).Invoke($as); \ } \ - ::testing::MockSpec<__VA_ARGS__>& \ - gmock_##Method($matcher_as) constness { \ + ::testing::MockSpec<__VA_ARGS__> \ + gmock_##Method($matcher_arg_as) constness { \ GMOCK_MOCKER_($i, constness, Method).RegisterOwner(this); \ - return GMOCK_MOCKER_($i, constness, Method).With($as); \ + return GMOCK_MOCKER_($i, constness, Method).With($matcher_as); \ } \ + ::testing::MockSpec<__VA_ARGS__> gmock_##Method( \ + const ::testing::internal::WithoutMatchers&, \ + constness ::testing::internal::Function<__VA_ARGS__>* ) const { \ + return ::testing::internal::AdjustConstness_##constness(this)-> \ + gmock_##Method($anything_matchers); \ + } \ mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_($i, constness, Method) @@ -263,7 +320,7 @@ class MockFunction; $for i [[ $range j 0..i-1 $var ArgTypes = [[$for j, [[A$j]]]] -$var ArgNames = [[$for j, [[a$j]]]] +$var ArgValues = [[$for j, [[::std::forward<A$j>(a$j)]]]] $var ArgDecls = [[$for j, [[A$j a$j]]]] template <typename R$for j [[, typename A$j]]> class MockFunction<R($ArgTypes)> { @@ -273,9 +330,9 @@ class MockFunction<R($ArgTypes)> { MOCK_METHOD$i[[]]_T(Call, R($ArgTypes)); #if GTEST_HAS_STD_FUNCTION_ - std::function<R($ArgTypes)> AsStdFunction() { + ::std::function<R($ArgTypes)> AsStdFunction() { return [this]($ArgDecls) -> R { - return this->Call($ArgNames); + return this->Call($ArgValues); }; } #endif // GTEST_HAS_STD_FUNCTION_ diff --git a/googlemock/include/gmock/gmock-generated-matchers.h b/googlemock/include/gmock/gmock-generated-matchers.h index 57056fd..166122a 100644 --- a/googlemock/include/gmock/gmock-generated-matchers.h +++ b/googlemock/include/gmock/gmock-generated-matchers.h @@ -35,6 +35,8 @@ // // This file implements some commonly used variadic matchers. +// GOOGLETEST_CM0002 DO NOT DELETE + #ifndef GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_MATCHERS_H_ #define GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_MATCHERS_H_ @@ -49,7 +51,7 @@ namespace internal { // The type of the i-th (0-based) field of Tuple. #define GMOCK_FIELD_TYPE_(Tuple, i) \ - typename ::testing::tuple_element<i, Tuple>::type + typename ::std::tuple_element<i, Tuple>::type // TupleFields<Tuple, k0, ..., kn> is for selecting fields from a // tuple of type Tuple. It has two members: @@ -57,10 +59,11 @@ namespace internal { // type: a tuple type whose i-th field is the ki-th field of Tuple. // GetSelectedFields(t): returns fields k0, ..., and kn of t as a tuple. // -// For example, in class TupleFields<tuple<bool, char, int>, 2, 0>, we have: +// For example, in class TupleFields<std::tuple<bool, char, int>, 2, 0>, +// we have: // -// type is tuple<int, bool>, and -// GetSelectedFields(make_tuple(true, 'a', 42)) is (42, true). +// type is std::tuple<int, bool>, and +// GetSelectedFields(std::make_tuple(true, 'a', 42)) is (42, true). template <class Tuple, int k0 = -1, int k1 = -1, int k2 = -1, int k3 = -1, int k4 = -1, int k5 = -1, int k6 = -1, int k7 = -1, int k8 = -1, @@ -72,15 +75,15 @@ template <class Tuple, int k0, int k1, int k2, int k3, int k4, int k5, int k6, int k7, int k8, int k9> class TupleFields { public: - typedef ::testing::tuple<GMOCK_FIELD_TYPE_(Tuple, k0), - GMOCK_FIELD_TYPE_(Tuple, k1), GMOCK_FIELD_TYPE_(Tuple, k2), - GMOCK_FIELD_TYPE_(Tuple, k3), GMOCK_FIELD_TYPE_(Tuple, k4), - GMOCK_FIELD_TYPE_(Tuple, k5), GMOCK_FIELD_TYPE_(Tuple, k6), - GMOCK_FIELD_TYPE_(Tuple, k7), GMOCK_FIELD_TYPE_(Tuple, k8), - GMOCK_FIELD_TYPE_(Tuple, k9)> type; + typedef ::std::tuple<GMOCK_FIELD_TYPE_(Tuple, k0), GMOCK_FIELD_TYPE_(Tuple, + k1), GMOCK_FIELD_TYPE_(Tuple, k2), GMOCK_FIELD_TYPE_(Tuple, k3), + GMOCK_FIELD_TYPE_(Tuple, k4), GMOCK_FIELD_TYPE_(Tuple, k5), + GMOCK_FIELD_TYPE_(Tuple, k6), GMOCK_FIELD_TYPE_(Tuple, k7), + GMOCK_FIELD_TYPE_(Tuple, k8), GMOCK_FIELD_TYPE_(Tuple, k9)> type; static type GetSelectedFields(const Tuple& t) { - return type(get<k0>(t), get<k1>(t), get<k2>(t), get<k3>(t), get<k4>(t), - get<k5>(t), get<k6>(t), get<k7>(t), get<k8>(t), get<k9>(t)); + return type(std::get<k0>(t), std::get<k1>(t), std::get<k2>(t), + std::get<k3>(t), std::get<k4>(t), std::get<k5>(t), std::get<k6>(t), + std::get<k7>(t), std::get<k8>(t), std::get<k9>(t)); } }; @@ -89,7 +92,7 @@ class TupleFields { template <class Tuple> class TupleFields<Tuple, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1> { public: - typedef ::testing::tuple<> type; + typedef ::std::tuple<> type; static type GetSelectedFields(const Tuple& /* t */) { return type(); } @@ -98,77 +101,77 @@ class TupleFields<Tuple, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1> { template <class Tuple, int k0> class TupleFields<Tuple, k0, -1, -1, -1, -1, -1, -1, -1, -1, -1> { public: - typedef ::testing::tuple<GMOCK_FIELD_TYPE_(Tuple, k0)> type; + typedef ::std::tuple<GMOCK_FIELD_TYPE_(Tuple, k0)> type; static type GetSelectedFields(const Tuple& t) { - return type(get<k0>(t)); + return type(std::get<k0>(t)); } }; template <class Tuple, int k0, int k1> class TupleFields<Tuple, k0, k1, -1, -1, -1, -1, -1, -1, -1, -1> { public: - typedef ::testing::tuple<GMOCK_FIELD_TYPE_(Tuple, k0), - GMOCK_FIELD_TYPE_(Tuple, k1)> type; + typedef ::std::tuple<GMOCK_FIELD_TYPE_(Tuple, k0), GMOCK_FIELD_TYPE_(Tuple, + k1)> type; static type GetSelectedFields(const Tuple& t) { - return type(get<k0>(t), get<k1>(t)); + return type(std::get<k0>(t), std::get<k1>(t)); } }; template <class Tuple, int k0, int k1, int k2> class TupleFields<Tuple, k0, k1, k2, -1, -1, -1, -1, -1, -1, -1> { public: - typedef ::testing::tuple<GMOCK_FIELD_TYPE_(Tuple, k0), - GMOCK_FIELD_TYPE_(Tuple, k1), GMOCK_FIELD_TYPE_(Tuple, k2)> type; + typedef ::std::tuple<GMOCK_FIELD_TYPE_(Tuple, k0), GMOCK_FIELD_TYPE_(Tuple, + k1), GMOCK_FIELD_TYPE_(Tuple, k2)> type; static type GetSelectedFields(const Tuple& t) { - return type(get<k0>(t), get<k1>(t), get<k2>(t)); + return type(std::get<k0>(t), std::get<k1>(t), std::get<k2>(t)); } }; template <class Tuple, int k0, int k1, int k2, int k3> class TupleFields<Tuple, k0, k1, k2, k3, -1, -1, -1, -1, -1, -1> { public: - typedef ::testing::tuple<GMOCK_FIELD_TYPE_(Tuple, k0), - GMOCK_FIELD_TYPE_(Tuple, k1), GMOCK_FIELD_TYPE_(Tuple, k2), - GMOCK_FIELD_TYPE_(Tuple, k3)> type; + typedef ::std::tuple<GMOCK_FIELD_TYPE_(Tuple, k0), GMOCK_FIELD_TYPE_(Tuple, + k1), GMOCK_FIELD_TYPE_(Tuple, k2), GMOCK_FIELD_TYPE_(Tuple, k3)> type; static type GetSelectedFields(const Tuple& t) { - return type(get<k0>(t), get<k1>(t), get<k2>(t), get<k3>(t)); + return type(std::get<k0>(t), std::get<k1>(t), std::get<k2>(t), + std::get<k3>(t)); } }; template <class Tuple, int k0, int k1, int k2, int k3, int k4> class TupleFields<Tuple, k0, k1, k2, k3, k4, -1, -1, -1, -1, -1> { public: - typedef ::testing::tuple<GMOCK_FIELD_TYPE_(Tuple, k0), - GMOCK_FIELD_TYPE_(Tuple, k1), GMOCK_FIELD_TYPE_(Tuple, k2), - GMOCK_FIELD_TYPE_(Tuple, k3), GMOCK_FIELD_TYPE_(Tuple, k4)> type; + typedef ::std::tuple<GMOCK_FIELD_TYPE_(Tuple, k0), GMOCK_FIELD_TYPE_(Tuple, + k1), GMOCK_FIELD_TYPE_(Tuple, k2), GMOCK_FIELD_TYPE_(Tuple, k3), + GMOCK_FIELD_TYPE_(Tuple, k4)> type; static type GetSelectedFields(const Tuple& t) { - return type(get<k0>(t), get<k1>(t), get<k2>(t), get<k3>(t), get<k4>(t)); + return type(std::get<k0>(t), std::get<k1>(t), std::get<k2>(t), + std::get<k3>(t), std::get<k4>(t)); } }; template <class Tuple, int k0, int k1, int k2, int k3, int k4, int k5> class TupleFields<Tuple, k0, k1, k2, k3, k4, k5, -1, -1, -1, -1> { public: - typedef ::testing::tuple<GMOCK_FIELD_TYPE_(Tuple, k0), - GMOCK_FIELD_TYPE_(Tuple, k1), GMOCK_FIELD_TYPE_(Tuple, k2), - GMOCK_FIELD_TYPE_(Tuple, k3), GMOCK_FIELD_TYPE_(Tuple, k4), - GMOCK_FIELD_TYPE_(Tuple, k5)> type; + typedef ::std::tuple<GMOCK_FIELD_TYPE_(Tuple, k0), GMOCK_FIELD_TYPE_(Tuple, + k1), GMOCK_FIELD_TYPE_(Tuple, k2), GMOCK_FIELD_TYPE_(Tuple, k3), + GMOCK_FIELD_TYPE_(Tuple, k4), GMOCK_FIELD_TYPE_(Tuple, k5)> type; static type GetSelectedFields(const Tuple& t) { - return type(get<k0>(t), get<k1>(t), get<k2>(t), get<k3>(t), get<k4>(t), - get<k5>(t)); + return type(std::get<k0>(t), std::get<k1>(t), std::get<k2>(t), + std::get<k3>(t), std::get<k4>(t), std::get<k5>(t)); } }; template <class Tuple, int k0, int k1, int k2, int k3, int k4, int k5, int k6> class TupleFields<Tuple, k0, k1, k2, k3, k4, k5, k6, -1, -1, -1> { public: - typedef ::testing::tuple<GMOCK_FIELD_TYPE_(Tuple, k0), - GMOCK_FIELD_TYPE_(Tuple, k1), GMOCK_FIELD_TYPE_(Tuple, k2), - GMOCK_FIELD_TYPE_(Tuple, k3), GMOCK_FIELD_TYPE_(Tuple, k4), - GMOCK_FIELD_TYPE_(Tuple, k5), GMOCK_FIELD_TYPE_(Tuple, k6)> type; + typedef ::std::tuple<GMOCK_FIELD_TYPE_(Tuple, k0), GMOCK_FIELD_TYPE_(Tuple, + k1), GMOCK_FIELD_TYPE_(Tuple, k2), GMOCK_FIELD_TYPE_(Tuple, k3), + GMOCK_FIELD_TYPE_(Tuple, k4), GMOCK_FIELD_TYPE_(Tuple, k5), + GMOCK_FIELD_TYPE_(Tuple, k6)> type; static type GetSelectedFields(const Tuple& t) { - return type(get<k0>(t), get<k1>(t), get<k2>(t), get<k3>(t), get<k4>(t), - get<k5>(t), get<k6>(t)); + return type(std::get<k0>(t), std::get<k1>(t), std::get<k2>(t), + std::get<k3>(t), std::get<k4>(t), std::get<k5>(t), std::get<k6>(t)); } }; @@ -176,14 +179,14 @@ template <class Tuple, int k0, int k1, int k2, int k3, int k4, int k5, int k6, int k7> class TupleFields<Tuple, k0, k1, k2, k3, k4, k5, k6, k7, -1, -1> { public: - typedef ::testing::tuple<GMOCK_FIELD_TYPE_(Tuple, k0), - GMOCK_FIELD_TYPE_(Tuple, k1), GMOCK_FIELD_TYPE_(Tuple, k2), - GMOCK_FIELD_TYPE_(Tuple, k3), GMOCK_FIELD_TYPE_(Tuple, k4), - GMOCK_FIELD_TYPE_(Tuple, k5), GMOCK_FIELD_TYPE_(Tuple, k6), - GMOCK_FIELD_TYPE_(Tuple, k7)> type; + typedef ::std::tuple<GMOCK_FIELD_TYPE_(Tuple, k0), GMOCK_FIELD_TYPE_(Tuple, + k1), GMOCK_FIELD_TYPE_(Tuple, k2), GMOCK_FIELD_TYPE_(Tuple, k3), + GMOCK_FIELD_TYPE_(Tuple, k4), GMOCK_FIELD_TYPE_(Tuple, k5), + GMOCK_FIELD_TYPE_(Tuple, k6), GMOCK_FIELD_TYPE_(Tuple, k7)> type; static type GetSelectedFields(const Tuple& t) { - return type(get<k0>(t), get<k1>(t), get<k2>(t), get<k3>(t), get<k4>(t), - get<k5>(t), get<k6>(t), get<k7>(t)); + return type(std::get<k0>(t), std::get<k1>(t), std::get<k2>(t), + std::get<k3>(t), std::get<k4>(t), std::get<k5>(t), std::get<k6>(t), + std::get<k7>(t)); } }; @@ -191,14 +194,15 @@ template <class Tuple, int k0, int k1, int k2, int k3, int k4, int k5, int k6, int k7, int k8> class TupleFields<Tuple, k0, k1, k2, k3, k4, k5, k6, k7, k8, -1> { public: - typedef ::testing::tuple<GMOCK_FIELD_TYPE_(Tuple, k0), - GMOCK_FIELD_TYPE_(Tuple, k1), GMOCK_FIELD_TYPE_(Tuple, k2), - GMOCK_FIELD_TYPE_(Tuple, k3), GMOCK_FIELD_TYPE_(Tuple, k4), - GMOCK_FIELD_TYPE_(Tuple, k5), GMOCK_FIELD_TYPE_(Tuple, k6), - GMOCK_FIELD_TYPE_(Tuple, k7), GMOCK_FIELD_TYPE_(Tuple, k8)> type; + typedef ::std::tuple<GMOCK_FIELD_TYPE_(Tuple, k0), GMOCK_FIELD_TYPE_(Tuple, + k1), GMOCK_FIELD_TYPE_(Tuple, k2), GMOCK_FIELD_TYPE_(Tuple, k3), + GMOCK_FIELD_TYPE_(Tuple, k4), GMOCK_FIELD_TYPE_(Tuple, k5), + GMOCK_FIELD_TYPE_(Tuple, k6), GMOCK_FIELD_TYPE_(Tuple, k7), + GMOCK_FIELD_TYPE_(Tuple, k8)> type; static type GetSelectedFields(const Tuple& t) { - return type(get<k0>(t), get<k1>(t), get<k2>(t), get<k3>(t), get<k4>(t), - get<k5>(t), get<k6>(t), get<k7>(t), get<k8>(t)); + return type(std::get<k0>(t), std::get<k1>(t), std::get<k2>(t), + std::get<k3>(t), std::get<k4>(t), std::get<k5>(t), std::get<k6>(t), + std::get<k7>(t), std::get<k8>(t)); } }; @@ -295,182 +299,6 @@ class ArgsMatcher { GTEST_DISALLOW_ASSIGN_(ArgsMatcher); }; -// A set of metafunctions for computing the result type of AllOf. -// AllOf(m1, ..., mN) returns -// AllOfResultN<decltype(m1), ..., decltype(mN)>::type. - -// Although AllOf isn't defined for one argument, AllOfResult1 is defined -// to simplify the implementation. -template <typename M1> -struct AllOfResult1 { - typedef M1 type; -}; - -template <typename M1, typename M2> -struct AllOfResult2 { - typedef BothOfMatcher< - typename AllOfResult1<M1>::type, - typename AllOfResult1<M2>::type - > type; -}; - -template <typename M1, typename M2, typename M3> -struct AllOfResult3 { - typedef BothOfMatcher< - typename AllOfResult1<M1>::type, - typename AllOfResult2<M2, M3>::type - > type; -}; - -template <typename M1, typename M2, typename M3, typename M4> -struct AllOfResult4 { - typedef BothOfMatcher< - typename AllOfResult2<M1, M2>::type, - typename AllOfResult2<M3, M4>::type - > type; -}; - -template <typename M1, typename M2, typename M3, typename M4, typename M5> -struct AllOfResult5 { - typedef BothOfMatcher< - typename AllOfResult2<M1, M2>::type, - typename AllOfResult3<M3, M4, M5>::type - > type; -}; - -template <typename M1, typename M2, typename M3, typename M4, typename M5, - typename M6> -struct AllOfResult6 { - typedef BothOfMatcher< - typename AllOfResult3<M1, M2, M3>::type, - typename AllOfResult3<M4, M5, M6>::type - > type; -}; - -template <typename M1, typename M2, typename M3, typename M4, typename M5, - typename M6, typename M7> -struct AllOfResult7 { - typedef BothOfMatcher< - typename AllOfResult3<M1, M2, M3>::type, - typename AllOfResult4<M4, M5, M6, M7>::type - > type; -}; - -template <typename M1, typename M2, typename M3, typename M4, typename M5, - typename M6, typename M7, typename M8> -struct AllOfResult8 { - typedef BothOfMatcher< - typename AllOfResult4<M1, M2, M3, M4>::type, - typename AllOfResult4<M5, M6, M7, M8>::type - > type; -}; - -template <typename M1, typename M2, typename M3, typename M4, typename M5, - typename M6, typename M7, typename M8, typename M9> -struct AllOfResult9 { - typedef BothOfMatcher< - typename AllOfResult4<M1, M2, M3, M4>::type, - typename AllOfResult5<M5, M6, M7, M8, M9>::type - > type; -}; - -template <typename M1, typename M2, typename M3, typename M4, typename M5, - typename M6, typename M7, typename M8, typename M9, typename M10> -struct AllOfResult10 { - typedef BothOfMatcher< - typename AllOfResult5<M1, M2, M3, M4, M5>::type, - typename AllOfResult5<M6, M7, M8, M9, M10>::type - > type; -}; - -// A set of metafunctions for computing the result type of AnyOf. -// AnyOf(m1, ..., mN) returns -// AnyOfResultN<decltype(m1), ..., decltype(mN)>::type. - -// Although AnyOf isn't defined for one argument, AnyOfResult1 is defined -// to simplify the implementation. -template <typename M1> -struct AnyOfResult1 { - typedef M1 type; -}; - -template <typename M1, typename M2> -struct AnyOfResult2 { - typedef EitherOfMatcher< - typename AnyOfResult1<M1>::type, - typename AnyOfResult1<M2>::type - > type; -}; - -template <typename M1, typename M2, typename M3> -struct AnyOfResult3 { - typedef EitherOfMatcher< - typename AnyOfResult1<M1>::type, - typename AnyOfResult2<M2, M3>::type - > type; -}; - -template <typename M1, typename M2, typename M3, typename M4> -struct AnyOfResult4 { - typedef EitherOfMatcher< - typename AnyOfResult2<M1, M2>::type, - typename AnyOfResult2<M3, M4>::type - > type; -}; - -template <typename M1, typename M2, typename M3, typename M4, typename M5> -struct AnyOfResult5 { - typedef EitherOfMatcher< - typename AnyOfResult2<M1, M2>::type, - typename AnyOfResult3<M3, M4, M5>::type - > type; -}; - -template <typename M1, typename M2, typename M3, typename M4, typename M5, - typename M6> -struct AnyOfResult6 { - typedef EitherOfMatcher< - typename AnyOfResult3<M1, M2, M3>::type, - typename AnyOfResult3<M4, M5, M6>::type - > type; -}; - -template <typename M1, typename M2, typename M3, typename M4, typename M5, - typename M6, typename M7> -struct AnyOfResult7 { - typedef EitherOfMatcher< - typename AnyOfResult3<M1, M2, M3>::type, - typename AnyOfResult4<M4, M5, M6, M7>::type - > type; -}; - -template <typename M1, typename M2, typename M3, typename M4, typename M5, - typename M6, typename M7, typename M8> -struct AnyOfResult8 { - typedef EitherOfMatcher< - typename AnyOfResult4<M1, M2, M3, M4>::type, - typename AnyOfResult4<M5, M6, M7, M8>::type - > type; -}; - -template <typename M1, typename M2, typename M3, typename M4, typename M5, - typename M6, typename M7, typename M8, typename M9> -struct AnyOfResult9 { - typedef EitherOfMatcher< - typename AnyOfResult4<M1, M2, M3, M4>::type, - typename AnyOfResult5<M5, M6, M7, M8, M9>::type - > type; -}; - -template <typename M1, typename M2, typename M3, typename M4, typename M5, - typename M6, typename M7, typename M8, typename M9, typename M10> -struct AnyOfResult10 { - typedef EitherOfMatcher< - typename AnyOfResult5<M1, M2, M3, M4, M5>::type, - typename AnyOfResult5<M6, M7, M8, M9, M10>::type - > type; -}; - } // namespace internal // Args<N1, N2, ..., Nk>(a_matcher) matches a tuple if the selected @@ -551,614 +379,7 @@ Args(const InnerMatcher& matcher) { k9, k10>(matcher); } -// ElementsAre(e_1, e_2, ... e_n) matches an STL-style container with -// n elements, where the i-th element in the container must -// match the i-th argument in the list. Each argument of -// ElementsAre() can be either a value or a matcher. We support up to -// 10 arguments. -// -// The use of DecayArray in the implementation allows ElementsAre() -// to accept string literals, whose type is const char[N], but we -// want to treat them as const char*. -// -// NOTE: Since ElementsAre() cares about the order of the elements, it -// must not be used with containers whose elements's order is -// undefined (e.g. hash_map). - -inline internal::ElementsAreMatcher< - ::testing::tuple<> > -ElementsAre() { - typedef ::testing::tuple<> Args; - return internal::ElementsAreMatcher<Args>(Args()); -} - -template <typename T1> -inline internal::ElementsAreMatcher< - ::testing::tuple< - typename internal::DecayArray<T1>::type> > -ElementsAre(const T1& e1) { - typedef ::testing::tuple< - typename internal::DecayArray<T1>::type> Args; - return internal::ElementsAreMatcher<Args>(Args(e1)); -} - -template <typename T1, typename T2> -inline internal::ElementsAreMatcher< - ::testing::tuple< - typename internal::DecayArray<T1>::type, - typename internal::DecayArray<T2>::type> > -ElementsAre(const T1& e1, const T2& e2) { - typedef ::testing::tuple< - typename internal::DecayArray<T1>::type, - typename internal::DecayArray<T2>::type> Args; - return internal::ElementsAreMatcher<Args>(Args(e1, e2)); -} - -template <typename T1, typename T2, typename T3> -inline internal::ElementsAreMatcher< - ::testing::tuple< - typename internal::DecayArray<T1>::type, - typename internal::DecayArray<T2>::type, - typename internal::DecayArray<T3>::type> > -ElementsAre(const T1& e1, const T2& e2, const T3& e3) { - typedef ::testing::tuple< - typename internal::DecayArray<T1>::type, - typename internal::DecayArray<T2>::type, - typename internal::DecayArray<T3>::type> Args; - return internal::ElementsAreMatcher<Args>(Args(e1, e2, e3)); -} - -template <typename T1, typename T2, typename T3, typename T4> -inline internal::ElementsAreMatcher< - ::testing::tuple< - typename internal::DecayArray<T1>::type, - typename internal::DecayArray<T2>::type, - typename internal::DecayArray<T3>::type, - typename internal::DecayArray<T4>::type> > -ElementsAre(const T1& e1, const T2& e2, const T3& e3, const T4& e4) { - typedef ::testing::tuple< - typename internal::DecayArray<T1>::type, - typename internal::DecayArray<T2>::type, - typename internal::DecayArray<T3>::type, - typename internal::DecayArray<T4>::type> Args; - return internal::ElementsAreMatcher<Args>(Args(e1, e2, e3, e4)); -} - -template <typename T1, typename T2, typename T3, typename T4, typename T5> -inline internal::ElementsAreMatcher< - ::testing::tuple< - typename internal::DecayArray<T1>::type, - typename internal::DecayArray<T2>::type, - typename internal::DecayArray<T3>::type, - typename internal::DecayArray<T4>::type, - typename internal::DecayArray<T5>::type> > -ElementsAre(const T1& e1, const T2& e2, const T3& e3, const T4& e4, - const T5& e5) { - typedef ::testing::tuple< - typename internal::DecayArray<T1>::type, - typename internal::DecayArray<T2>::type, - typename internal::DecayArray<T3>::type, - typename internal::DecayArray<T4>::type, - typename internal::DecayArray<T5>::type> Args; - return internal::ElementsAreMatcher<Args>(Args(e1, e2, e3, e4, e5)); -} - -template <typename T1, typename T2, typename T3, typename T4, typename T5, - typename T6> -inline internal::ElementsAreMatcher< - ::testing::tuple< - typename internal::DecayArray<T1>::type, - typename internal::DecayArray<T2>::type, - typename internal::DecayArray<T3>::type, - typename internal::DecayArray<T4>::type, - typename internal::DecayArray<T5>::type, - typename internal::DecayArray<T6>::type> > -ElementsAre(const T1& e1, const T2& e2, const T3& e3, const T4& e4, - const T5& e5, const T6& e6) { - typedef ::testing::tuple< - typename internal::DecayArray<T1>::type, - typename internal::DecayArray<T2>::type, - typename internal::DecayArray<T3>::type, - typename internal::DecayArray<T4>::type, - typename internal::DecayArray<T5>::type, - typename internal::DecayArray<T6>::type> Args; - return internal::ElementsAreMatcher<Args>(Args(e1, e2, e3, e4, e5, e6)); -} - -template <typename T1, typename T2, typename T3, typename T4, typename T5, - typename T6, typename T7> -inline internal::ElementsAreMatcher< - ::testing::tuple< - typename internal::DecayArray<T1>::type, - typename internal::DecayArray<T2>::type, - typename internal::DecayArray<T3>::type, - typename internal::DecayArray<T4>::type, - typename internal::DecayArray<T5>::type, - typename internal::DecayArray<T6>::type, - typename internal::DecayArray<T7>::type> > -ElementsAre(const T1& e1, const T2& e2, const T3& e3, const T4& e4, - const T5& e5, const T6& e6, const T7& e7) { - typedef ::testing::tuple< - typename internal::DecayArray<T1>::type, - typename internal::DecayArray<T2>::type, - typename internal::DecayArray<T3>::type, - typename internal::DecayArray<T4>::type, - typename internal::DecayArray<T5>::type, - typename internal::DecayArray<T6>::type, - typename internal::DecayArray<T7>::type> Args; - return internal::ElementsAreMatcher<Args>(Args(e1, e2, e3, e4, e5, e6, e7)); -} - -template <typename T1, typename T2, typename T3, typename T4, typename T5, - typename T6, typename T7, typename T8> -inline internal::ElementsAreMatcher< - ::testing::tuple< - typename internal::DecayArray<T1>::type, - typename internal::DecayArray<T2>::type, - typename internal::DecayArray<T3>::type, - typename internal::DecayArray<T4>::type, - typename internal::DecayArray<T5>::type, - typename internal::DecayArray<T6>::type, - typename internal::DecayArray<T7>::type, - typename internal::DecayArray<T8>::type> > -ElementsAre(const T1& e1, const T2& e2, const T3& e3, const T4& e4, - const T5& e5, const T6& e6, const T7& e7, const T8& e8) { - typedef ::testing::tuple< - typename internal::DecayArray<T1>::type, - typename internal::DecayArray<T2>::type, - typename internal::DecayArray<T3>::type, - typename internal::DecayArray<T4>::type, - typename internal::DecayArray<T5>::type, - typename internal::DecayArray<T6>::type, - typename internal::DecayArray<T7>::type, - typename internal::DecayArray<T8>::type> Args; - return internal::ElementsAreMatcher<Args>(Args(e1, e2, e3, e4, e5, e6, e7, - e8)); -} - -template <typename T1, typename T2, typename T3, typename T4, typename T5, - typename T6, typename T7, typename T8, typename T9> -inline internal::ElementsAreMatcher< - ::testing::tuple< - typename internal::DecayArray<T1>::type, - typename internal::DecayArray<T2>::type, - typename internal::DecayArray<T3>::type, - typename internal::DecayArray<T4>::type, - typename internal::DecayArray<T5>::type, - typename internal::DecayArray<T6>::type, - typename internal::DecayArray<T7>::type, - typename internal::DecayArray<T8>::type, - typename internal::DecayArray<T9>::type> > -ElementsAre(const T1& e1, const T2& e2, const T3& e3, const T4& e4, - const T5& e5, const T6& e6, const T7& e7, const T8& e8, const T9& e9) { - typedef ::testing::tuple< - typename internal::DecayArray<T1>::type, - typename internal::DecayArray<T2>::type, - typename internal::DecayArray<T3>::type, - typename internal::DecayArray<T4>::type, - typename internal::DecayArray<T5>::type, - typename internal::DecayArray<T6>::type, - typename internal::DecayArray<T7>::type, - typename internal::DecayArray<T8>::type, - typename internal::DecayArray<T9>::type> Args; - return internal::ElementsAreMatcher<Args>(Args(e1, e2, e3, e4, e5, e6, e7, - e8, e9)); -} - -template <typename T1, typename T2, typename T3, typename T4, typename T5, - typename T6, typename T7, typename T8, typename T9, typename T10> -inline internal::ElementsAreMatcher< - ::testing::tuple< - typename internal::DecayArray<T1>::type, - typename internal::DecayArray<T2>::type, - typename internal::DecayArray<T3>::type, - typename internal::DecayArray<T4>::type, - typename internal::DecayArray<T5>::type, - typename internal::DecayArray<T6>::type, - typename internal::DecayArray<T7>::type, - typename internal::DecayArray<T8>::type, - typename internal::DecayArray<T9>::type, - typename internal::DecayArray<T10>::type> > -ElementsAre(const T1& e1, const T2& e2, const T3& e3, const T4& e4, - const T5& e5, const T6& e6, const T7& e7, const T8& e8, const T9& e9, - const T10& e10) { - typedef ::testing::tuple< - typename internal::DecayArray<T1>::type, - typename internal::DecayArray<T2>::type, - typename internal::DecayArray<T3>::type, - typename internal::DecayArray<T4>::type, - typename internal::DecayArray<T5>::type, - typename internal::DecayArray<T6>::type, - typename internal::DecayArray<T7>::type, - typename internal::DecayArray<T8>::type, - typename internal::DecayArray<T9>::type, - typename internal::DecayArray<T10>::type> Args; - return internal::ElementsAreMatcher<Args>(Args(e1, e2, e3, e4, e5, e6, e7, - e8, e9, e10)); -} - -// UnorderedElementsAre(e_1, e_2, ..., e_n) is an ElementsAre extension -// that matches n elements in any order. We support up to n=10 arguments. - -inline internal::UnorderedElementsAreMatcher< - ::testing::tuple<> > -UnorderedElementsAre() { - typedef ::testing::tuple<> Args; - return internal::UnorderedElementsAreMatcher<Args>(Args()); -} - -template <typename T1> -inline internal::UnorderedElementsAreMatcher< - ::testing::tuple< - typename internal::DecayArray<T1>::type> > -UnorderedElementsAre(const T1& e1) { - typedef ::testing::tuple< - typename internal::DecayArray<T1>::type> Args; - return internal::UnorderedElementsAreMatcher<Args>(Args(e1)); -} - -template <typename T1, typename T2> -inline internal::UnorderedElementsAreMatcher< - ::testing::tuple< - typename internal::DecayArray<T1>::type, - typename internal::DecayArray<T2>::type> > -UnorderedElementsAre(const T1& e1, const T2& e2) { - typedef ::testing::tuple< - typename internal::DecayArray<T1>::type, - typename internal::DecayArray<T2>::type> Args; - return internal::UnorderedElementsAreMatcher<Args>(Args(e1, e2)); -} - -template <typename T1, typename T2, typename T3> -inline internal::UnorderedElementsAreMatcher< - ::testing::tuple< - typename internal::DecayArray<T1>::type, - typename internal::DecayArray<T2>::type, - typename internal::DecayArray<T3>::type> > -UnorderedElementsAre(const T1& e1, const T2& e2, const T3& e3) { - typedef ::testing::tuple< - typename internal::DecayArray<T1>::type, - typename internal::DecayArray<T2>::type, - typename internal::DecayArray<T3>::type> Args; - return internal::UnorderedElementsAreMatcher<Args>(Args(e1, e2, e3)); -} - -template <typename T1, typename T2, typename T3, typename T4> -inline internal::UnorderedElementsAreMatcher< - ::testing::tuple< - typename internal::DecayArray<T1>::type, - typename internal::DecayArray<T2>::type, - typename internal::DecayArray<T3>::type, - typename internal::DecayArray<T4>::type> > -UnorderedElementsAre(const T1& e1, const T2& e2, const T3& e3, const T4& e4) { - typedef ::testing::tuple< - typename internal::DecayArray<T1>::type, - typename internal::DecayArray<T2>::type, - typename internal::DecayArray<T3>::type, - typename internal::DecayArray<T4>::type> Args; - return internal::UnorderedElementsAreMatcher<Args>(Args(e1, e2, e3, e4)); -} - -template <typename T1, typename T2, typename T3, typename T4, typename T5> -inline internal::UnorderedElementsAreMatcher< - ::testing::tuple< - typename internal::DecayArray<T1>::type, - typename internal::DecayArray<T2>::type, - typename internal::DecayArray<T3>::type, - typename internal::DecayArray<T4>::type, - typename internal::DecayArray<T5>::type> > -UnorderedElementsAre(const T1& e1, const T2& e2, const T3& e3, const T4& e4, - const T5& e5) { - typedef ::testing::tuple< - typename internal::DecayArray<T1>::type, - typename internal::DecayArray<T2>::type, - typename internal::DecayArray<T3>::type, - typename internal::DecayArray<T4>::type, - typename internal::DecayArray<T5>::type> Args; - return internal::UnorderedElementsAreMatcher<Args>(Args(e1, e2, e3, e4, e5)); -} - -template <typename T1, typename T2, typename T3, typename T4, typename T5, - typename T6> -inline internal::UnorderedElementsAreMatcher< - ::testing::tuple< - typename internal::DecayArray<T1>::type, - typename internal::DecayArray<T2>::type, - typename internal::DecayArray<T3>::type, - typename internal::DecayArray<T4>::type, - typename internal::DecayArray<T5>::type, - typename internal::DecayArray<T6>::type> > -UnorderedElementsAre(const T1& e1, const T2& e2, const T3& e3, const T4& e4, - const T5& e5, const T6& e6) { - typedef ::testing::tuple< - typename internal::DecayArray<T1>::type, - typename internal::DecayArray<T2>::type, - typename internal::DecayArray<T3>::type, - typename internal::DecayArray<T4>::type, - typename internal::DecayArray<T5>::type, - typename internal::DecayArray<T6>::type> Args; - return internal::UnorderedElementsAreMatcher<Args>(Args(e1, e2, e3, e4, e5, - e6)); -} - -template <typename T1, typename T2, typename T3, typename T4, typename T5, - typename T6, typename T7> -inline internal::UnorderedElementsAreMatcher< - ::testing::tuple< - typename internal::DecayArray<T1>::type, - typename internal::DecayArray<T2>::type, - typename internal::DecayArray<T3>::type, - typename internal::DecayArray<T4>::type, - typename internal::DecayArray<T5>::type, - typename internal::DecayArray<T6>::type, - typename internal::DecayArray<T7>::type> > -UnorderedElementsAre(const T1& e1, const T2& e2, const T3& e3, const T4& e4, - const T5& e5, const T6& e6, const T7& e7) { - typedef ::testing::tuple< - typename internal::DecayArray<T1>::type, - typename internal::DecayArray<T2>::type, - typename internal::DecayArray<T3>::type, - typename internal::DecayArray<T4>::type, - typename internal::DecayArray<T5>::type, - typename internal::DecayArray<T6>::type, - typename internal::DecayArray<T7>::type> Args; - return internal::UnorderedElementsAreMatcher<Args>(Args(e1, e2, e3, e4, e5, - e6, e7)); -} - -template <typename T1, typename T2, typename T3, typename T4, typename T5, - typename T6, typename T7, typename T8> -inline internal::UnorderedElementsAreMatcher< - ::testing::tuple< - typename internal::DecayArray<T1>::type, - typename internal::DecayArray<T2>::type, - typename internal::DecayArray<T3>::type, - typename internal::DecayArray<T4>::type, - typename internal::DecayArray<T5>::type, - typename internal::DecayArray<T6>::type, - typename internal::DecayArray<T7>::type, - typename internal::DecayArray<T8>::type> > -UnorderedElementsAre(const T1& e1, const T2& e2, const T3& e3, const T4& e4, - const T5& e5, const T6& e6, const T7& e7, const T8& e8) { - typedef ::testing::tuple< - typename internal::DecayArray<T1>::type, - typename internal::DecayArray<T2>::type, - typename internal::DecayArray<T3>::type, - typename internal::DecayArray<T4>::type, - typename internal::DecayArray<T5>::type, - typename internal::DecayArray<T6>::type, - typename internal::DecayArray<T7>::type, - typename internal::DecayArray<T8>::type> Args; - return internal::UnorderedElementsAreMatcher<Args>(Args(e1, e2, e3, e4, e5, - e6, e7, e8)); -} - -template <typename T1, typename T2, typename T3, typename T4, typename T5, - typename T6, typename T7, typename T8, typename T9> -inline internal::UnorderedElementsAreMatcher< - ::testing::tuple< - typename internal::DecayArray<T1>::type, - typename internal::DecayArray<T2>::type, - typename internal::DecayArray<T3>::type, - typename internal::DecayArray<T4>::type, - typename internal::DecayArray<T5>::type, - typename internal::DecayArray<T6>::type, - typename internal::DecayArray<T7>::type, - typename internal::DecayArray<T8>::type, - typename internal::DecayArray<T9>::type> > -UnorderedElementsAre(const T1& e1, const T2& e2, const T3& e3, const T4& e4, - const T5& e5, const T6& e6, const T7& e7, const T8& e8, const T9& e9) { - typedef ::testing::tuple< - typename internal::DecayArray<T1>::type, - typename internal::DecayArray<T2>::type, - typename internal::DecayArray<T3>::type, - typename internal::DecayArray<T4>::type, - typename internal::DecayArray<T5>::type, - typename internal::DecayArray<T6>::type, - typename internal::DecayArray<T7>::type, - typename internal::DecayArray<T8>::type, - typename internal::DecayArray<T9>::type> Args; - return internal::UnorderedElementsAreMatcher<Args>(Args(e1, e2, e3, e4, e5, - e6, e7, e8, e9)); -} - -template <typename T1, typename T2, typename T3, typename T4, typename T5, - typename T6, typename T7, typename T8, typename T9, typename T10> -inline internal::UnorderedElementsAreMatcher< - ::testing::tuple< - typename internal::DecayArray<T1>::type, - typename internal::DecayArray<T2>::type, - typename internal::DecayArray<T3>::type, - typename internal::DecayArray<T4>::type, - typename internal::DecayArray<T5>::type, - typename internal::DecayArray<T6>::type, - typename internal::DecayArray<T7>::type, - typename internal::DecayArray<T8>::type, - typename internal::DecayArray<T9>::type, - typename internal::DecayArray<T10>::type> > -UnorderedElementsAre(const T1& e1, const T2& e2, const T3& e3, const T4& e4, - const T5& e5, const T6& e6, const T7& e7, const T8& e8, const T9& e9, - const T10& e10) { - typedef ::testing::tuple< - typename internal::DecayArray<T1>::type, - typename internal::DecayArray<T2>::type, - typename internal::DecayArray<T3>::type, - typename internal::DecayArray<T4>::type, - typename internal::DecayArray<T5>::type, - typename internal::DecayArray<T6>::type, - typename internal::DecayArray<T7>::type, - typename internal::DecayArray<T8>::type, - typename internal::DecayArray<T9>::type, - typename internal::DecayArray<T10>::type> Args; - return internal::UnorderedElementsAreMatcher<Args>(Args(e1, e2, e3, e4, e5, - e6, e7, e8, e9, e10)); -} - -// AllOf(m1, m2, ..., mk) matches any value that matches all of the given -// sub-matchers. AllOf is called fully qualified to prevent ADL from firing. - -template <typename M1, typename M2> -inline typename internal::AllOfResult2<M1, M2>::type -AllOf(M1 m1, M2 m2) { - return typename internal::AllOfResult2<M1, M2>::type( - m1, - m2); -} - -template <typename M1, typename M2, typename M3> -inline typename internal::AllOfResult3<M1, M2, M3>::type -AllOf(M1 m1, M2 m2, M3 m3) { - return typename internal::AllOfResult3<M1, M2, M3>::type( - m1, - ::testing::AllOf(m2, m3)); -} - -template <typename M1, typename M2, typename M3, typename M4> -inline typename internal::AllOfResult4<M1, M2, M3, M4>::type -AllOf(M1 m1, M2 m2, M3 m3, M4 m4) { - return typename internal::AllOfResult4<M1, M2, M3, M4>::type( - ::testing::AllOf(m1, m2), - ::testing::AllOf(m3, m4)); -} - -template <typename M1, typename M2, typename M3, typename M4, typename M5> -inline typename internal::AllOfResult5<M1, M2, M3, M4, M5>::type -AllOf(M1 m1, M2 m2, M3 m3, M4 m4, M5 m5) { - return typename internal::AllOfResult5<M1, M2, M3, M4, M5>::type( - ::testing::AllOf(m1, m2), - ::testing::AllOf(m3, m4, m5)); -} - -template <typename M1, typename M2, typename M3, typename M4, typename M5, - typename M6> -inline typename internal::AllOfResult6<M1, M2, M3, M4, M5, M6>::type -AllOf(M1 m1, M2 m2, M3 m3, M4 m4, M5 m5, M6 m6) { - return typename internal::AllOfResult6<M1, M2, M3, M4, M5, M6>::type( - ::testing::AllOf(m1, m2, m3), - ::testing::AllOf(m4, m5, m6)); -} - -template <typename M1, typename M2, typename M3, typename M4, typename M5, - typename M6, typename M7> -inline typename internal::AllOfResult7<M1, M2, M3, M4, M5, M6, M7>::type -AllOf(M1 m1, M2 m2, M3 m3, M4 m4, M5 m5, M6 m6, M7 m7) { - return typename internal::AllOfResult7<M1, M2, M3, M4, M5, M6, M7>::type( - ::testing::AllOf(m1, m2, m3), - ::testing::AllOf(m4, m5, m6, m7)); -} - -template <typename M1, typename M2, typename M3, typename M4, typename M5, - typename M6, typename M7, typename M8> -inline typename internal::AllOfResult8<M1, M2, M3, M4, M5, M6, M7, M8>::type -AllOf(M1 m1, M2 m2, M3 m3, M4 m4, M5 m5, M6 m6, M7 m7, M8 m8) { - return typename internal::AllOfResult8<M1, M2, M3, M4, M5, M6, M7, M8>::type( - ::testing::AllOf(m1, m2, m3, m4), - ::testing::AllOf(m5, m6, m7, m8)); -} - -template <typename M1, typename M2, typename M3, typename M4, typename M5, - typename M6, typename M7, typename M8, typename M9> -inline typename internal::AllOfResult9<M1, M2, M3, M4, M5, M6, M7, M8, M9>::type -AllOf(M1 m1, M2 m2, M3 m3, M4 m4, M5 m5, M6 m6, M7 m7, M8 m8, M9 m9) { - return typename internal::AllOfResult9<M1, M2, M3, M4, M5, M6, M7, M8, - M9>::type( - ::testing::AllOf(m1, m2, m3, m4), - ::testing::AllOf(m5, m6, m7, m8, m9)); -} - -template <typename M1, typename M2, typename M3, typename M4, typename M5, - typename M6, typename M7, typename M8, typename M9, typename M10> -inline typename internal::AllOfResult10<M1, M2, M3, M4, M5, M6, M7, M8, M9, - M10>::type -AllOf(M1 m1, M2 m2, M3 m3, M4 m4, M5 m5, M6 m6, M7 m7, M8 m8, M9 m9, M10 m10) { - return typename internal::AllOfResult10<M1, M2, M3, M4, M5, M6, M7, M8, M9, - M10>::type( - ::testing::AllOf(m1, m2, m3, m4, m5), - ::testing::AllOf(m6, m7, m8, m9, m10)); -} - -// AnyOf(m1, m2, ..., mk) matches any value that matches any of the given -// sub-matchers. AnyOf is called fully qualified to prevent ADL from firing. - -template <typename M1, typename M2> -inline typename internal::AnyOfResult2<M1, M2>::type -AnyOf(M1 m1, M2 m2) { - return typename internal::AnyOfResult2<M1, M2>::type( - m1, - m2); -} -template <typename M1, typename M2, typename M3> -inline typename internal::AnyOfResult3<M1, M2, M3>::type -AnyOf(M1 m1, M2 m2, M3 m3) { - return typename internal::AnyOfResult3<M1, M2, M3>::type( - m1, - ::testing::AnyOf(m2, m3)); -} - -template <typename M1, typename M2, typename M3, typename M4> -inline typename internal::AnyOfResult4<M1, M2, M3, M4>::type -AnyOf(M1 m1, M2 m2, M3 m3, M4 m4) { - return typename internal::AnyOfResult4<M1, M2, M3, M4>::type( - ::testing::AnyOf(m1, m2), - ::testing::AnyOf(m3, m4)); -} - -template <typename M1, typename M2, typename M3, typename M4, typename M5> -inline typename internal::AnyOfResult5<M1, M2, M3, M4, M5>::type -AnyOf(M1 m1, M2 m2, M3 m3, M4 m4, M5 m5) { - return typename internal::AnyOfResult5<M1, M2, M3, M4, M5>::type( - ::testing::AnyOf(m1, m2), - ::testing::AnyOf(m3, m4, m5)); -} - -template <typename M1, typename M2, typename M3, typename M4, typename M5, - typename M6> -inline typename internal::AnyOfResult6<M1, M2, M3, M4, M5, M6>::type -AnyOf(M1 m1, M2 m2, M3 m3, M4 m4, M5 m5, M6 m6) { - return typename internal::AnyOfResult6<M1, M2, M3, M4, M5, M6>::type( - ::testing::AnyOf(m1, m2, m3), - ::testing::AnyOf(m4, m5, m6)); -} - -template <typename M1, typename M2, typename M3, typename M4, typename M5, - typename M6, typename M7> -inline typename internal::AnyOfResult7<M1, M2, M3, M4, M5, M6, M7>::type -AnyOf(M1 m1, M2 m2, M3 m3, M4 m4, M5 m5, M6 m6, M7 m7) { - return typename internal::AnyOfResult7<M1, M2, M3, M4, M5, M6, M7>::type( - ::testing::AnyOf(m1, m2, m3), - ::testing::AnyOf(m4, m5, m6, m7)); -} - -template <typename M1, typename M2, typename M3, typename M4, typename M5, - typename M6, typename M7, typename M8> -inline typename internal::AnyOfResult8<M1, M2, M3, M4, M5, M6, M7, M8>::type -AnyOf(M1 m1, M2 m2, M3 m3, M4 m4, M5 m5, M6 m6, M7 m7, M8 m8) { - return typename internal::AnyOfResult8<M1, M2, M3, M4, M5, M6, M7, M8>::type( - ::testing::AnyOf(m1, m2, m3, m4), - ::testing::AnyOf(m5, m6, m7, m8)); -} - -template <typename M1, typename M2, typename M3, typename M4, typename M5, - typename M6, typename M7, typename M8, typename M9> -inline typename internal::AnyOfResult9<M1, M2, M3, M4, M5, M6, M7, M8, M9>::type -AnyOf(M1 m1, M2 m2, M3 m3, M4 m4, M5 m5, M6 m6, M7 m7, M8 m8, M9 m9) { - return typename internal::AnyOfResult9<M1, M2, M3, M4, M5, M6, M7, M8, - M9>::type( - ::testing::AnyOf(m1, m2, m3, m4), - ::testing::AnyOf(m5, m6, m7, m8, m9)); -} - -template <typename M1, typename M2, typename M3, typename M4, typename M5, - typename M6, typename M7, typename M8, typename M9, typename M10> -inline typename internal::AnyOfResult10<M1, M2, M3, M4, M5, M6, M7, M8, M9, - M10>::type -AnyOf(M1 m1, M2 m2, M3 m3, M4 m4, M5 m5, M6 m6, M7 m7, M8 m8, M9 m9, M10 m10) { - return typename internal::AnyOfResult10<M1, M2, M3, M4, M5, M6, M7, M8, M9, - M10>::type( - ::testing::AnyOf(m1, m2, m3, m4, m5), - ::testing::AnyOf(m6, m7, m8, m9, m10)); -} } // namespace testing @@ -1268,7 +489,7 @@ AnyOf(M1 m1, M2 m2, M3 m3, M4 m4, M5 m5, M6 m6, M7 m7, M8 m8, M9 m9, M10 m10) { // using testing::PrintToString; // // MATCHER_P2(InClosedRange, low, hi, -// string(negation ? "is not" : "is") + " in range [" + +// std::string(negation ? "is not" : "is") + " in range [" + // PrintToString(low) + ", " + PrintToString(hi) + "]") { // return low <= arg && arg <= hi; // } @@ -1376,18 +597,21 @@ AnyOf(M1 m1, M2 m2, M3 m3, M4 m4, M5 m5, M6 m6, M7 m7, M8 m8, M9 m9, M10 m10) { // ================ // // To learn more about using these macros, please search for 'MATCHER' -// on http://code.google.com/p/googlemock/wiki/CookBook. +// on +// https://github.com/google/googletest/blob/master/googlemock/docs/CookBook.md #define MATCHER(name, description)\ class name##Matcher {\ public:\ template <typename arg_type>\ - class gmock_Impl : public ::testing::MatcherInterface<arg_type> {\ + class gmock_Impl : public ::testing::MatcherInterface<\ + GTEST_REFERENCE_TO_CONST_(arg_type)> {\ public:\ gmock_Impl()\ {}\ virtual bool MatchAndExplain(\ - arg_type arg, ::testing::MatchResultListener* result_listener) const;\ + GTEST_REFERENCE_TO_CONST_(arg_type) arg,\ + ::testing::MatchResultListener* result_listener) const;\ virtual void DescribeTo(::std::ostream* gmock_os) const {\ *gmock_os << FormatDescription(false);\ }\ @@ -1395,16 +619,16 @@ AnyOf(M1 m1, M2 m2, M3 m3, M4 m4, M5 m5, M6 m6, M7 m7, M8 m8, M9 m9, M10 m10) { *gmock_os << FormatDescription(true);\ }\ private:\ - ::testing::internal::string FormatDescription(bool negation) const {\ - const ::testing::internal::string gmock_description = (description);\ - if (!gmock_description.empty())\ + ::std::string FormatDescription(bool negation) const {\ + ::std::string gmock_description = (description);\ + if (!gmock_description.empty()) {\ return gmock_description;\ + }\ return ::testing::internal::FormatMatcherDescription(\ negation, #name, \ ::testing::internal::UniversalTersePrintTupleFieldsToStrings(\ - ::testing::tuple<>()));\ + ::std::tuple<>()));\ }\ - GTEST_DISALLOW_ASSIGN_(gmock_Impl);\ };\ template <typename arg_type>\ operator ::testing::Matcher<arg_type>() const {\ @@ -1414,14 +638,13 @@ AnyOf(M1 m1, M2 m2, M3 m3, M4 m4, M5 m5, M6 m6, M7 m7, M8 m8, M9 m9, M10 m10) { name##Matcher() {\ }\ private:\ - GTEST_DISALLOW_ASSIGN_(name##Matcher);\ };\ inline name##Matcher name() {\ return name##Matcher();\ }\ template <typename arg_type>\ bool name##Matcher::gmock_Impl<arg_type>::MatchAndExplain(\ - arg_type arg, \ + GTEST_REFERENCE_TO_CONST_(arg_type) arg,\ ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\ const @@ -1430,41 +653,43 @@ AnyOf(M1 m1, M2 m2, M3 m3, M4 m4, M5 m5, M6 m6, M7 m7, M8 m8, M9 m9, M10 m10) { class name##MatcherP {\ public:\ template <typename arg_type>\ - class gmock_Impl : public ::testing::MatcherInterface<arg_type> {\ + class gmock_Impl : public ::testing::MatcherInterface<\ + GTEST_REFERENCE_TO_CONST_(arg_type)> {\ public:\ explicit gmock_Impl(p0##_type gmock_p0)\ - : p0(gmock_p0) {}\ + : p0(::testing::internal::move(gmock_p0)) {}\ virtual bool MatchAndExplain(\ - arg_type arg, ::testing::MatchResultListener* result_listener) const;\ + GTEST_REFERENCE_TO_CONST_(arg_type) arg,\ + ::testing::MatchResultListener* result_listener) const;\ virtual void DescribeTo(::std::ostream* gmock_os) const {\ *gmock_os << FormatDescription(false);\ }\ virtual void DescribeNegationTo(::std::ostream* gmock_os) const {\ *gmock_os << FormatDescription(true);\ }\ - p0##_type p0;\ + p0##_type const p0;\ private:\ - ::testing::internal::string FormatDescription(bool negation) const {\ - const ::testing::internal::string gmock_description = (description);\ - if (!gmock_description.empty())\ + ::std::string FormatDescription(bool negation) const {\ + ::std::string gmock_description = (description);\ + if (!gmock_description.empty()) {\ return gmock_description;\ + }\ return ::testing::internal::FormatMatcherDescription(\ negation, #name, \ ::testing::internal::UniversalTersePrintTupleFieldsToStrings(\ - ::testing::tuple<p0##_type>(p0)));\ + ::std::tuple<p0##_type>(p0)));\ }\ - GTEST_DISALLOW_ASSIGN_(gmock_Impl);\ };\ template <typename arg_type>\ operator ::testing::Matcher<arg_type>() const {\ return ::testing::Matcher<arg_type>(\ new gmock_Impl<arg_type>(p0));\ }\ - explicit name##MatcherP(p0##_type gmock_p0) : p0(gmock_p0) {\ + explicit name##MatcherP(p0##_type gmock_p0) : \ + p0(::testing::internal::move(gmock_p0)) {\ }\ - p0##_type p0;\ + p0##_type const p0;\ private:\ - GTEST_DISALLOW_ASSIGN_(name##MatcherP);\ };\ template <typename p0##_type>\ inline name##MatcherP<p0##_type> name(p0##_type p0) {\ @@ -1473,7 +698,7 @@ AnyOf(M1 m1, M2 m2, M3 m3, M4 m4, M5 m5, M6 m6, M7 m7, M8 m8, M9 m9, M10 m10) { template <typename p0##_type>\ template <typename arg_type>\ bool name##MatcherP<p0##_type>::gmock_Impl<arg_type>::MatchAndExplain(\ - arg_type arg, \ + GTEST_REFERENCE_TO_CONST_(arg_type) arg,\ ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\ const @@ -1482,44 +707,47 @@ AnyOf(M1 m1, M2 m2, M3 m3, M4 m4, M5 m5, M6 m6, M7 m7, M8 m8, M9 m9, M10 m10) { class name##MatcherP2 {\ public:\ template <typename arg_type>\ - class gmock_Impl : public ::testing::MatcherInterface<arg_type> {\ + class gmock_Impl : public ::testing::MatcherInterface<\ + GTEST_REFERENCE_TO_CONST_(arg_type)> {\ public:\ gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1)\ - : p0(gmock_p0), p1(gmock_p1) {}\ + : p0(::testing::internal::move(gmock_p0)), \ + p1(::testing::internal::move(gmock_p1)) {}\ virtual bool MatchAndExplain(\ - arg_type arg, ::testing::MatchResultListener* result_listener) const;\ + GTEST_REFERENCE_TO_CONST_(arg_type) arg,\ + ::testing::MatchResultListener* result_listener) const;\ virtual void DescribeTo(::std::ostream* gmock_os) const {\ *gmock_os << FormatDescription(false);\ }\ virtual void DescribeNegationTo(::std::ostream* gmock_os) const {\ *gmock_os << FormatDescription(true);\ }\ - p0##_type p0;\ - p1##_type p1;\ + p0##_type const p0;\ + p1##_type const p1;\ private:\ - ::testing::internal::string FormatDescription(bool negation) const {\ - const ::testing::internal::string gmock_description = (description);\ - if (!gmock_description.empty())\ + ::std::string FormatDescription(bool negation) const {\ + ::std::string gmock_description = (description);\ + if (!gmock_description.empty()) {\ return gmock_description;\ + }\ return ::testing::internal::FormatMatcherDescription(\ negation, #name, \ ::testing::internal::UniversalTersePrintTupleFieldsToStrings(\ - ::testing::tuple<p0##_type, p1##_type>(p0, p1)));\ + ::std::tuple<p0##_type, p1##_type>(p0, p1)));\ }\ - GTEST_DISALLOW_ASSIGN_(gmock_Impl);\ };\ template <typename arg_type>\ operator ::testing::Matcher<arg_type>() const {\ return ::testing::Matcher<arg_type>(\ new gmock_Impl<arg_type>(p0, p1));\ }\ - name##MatcherP2(p0##_type gmock_p0, p1##_type gmock_p1) : p0(gmock_p0), \ - p1(gmock_p1) {\ + name##MatcherP2(p0##_type gmock_p0, \ + p1##_type gmock_p1) : p0(::testing::internal::move(gmock_p0)), \ + p1(::testing::internal::move(gmock_p1)) {\ }\ - p0##_type p0;\ - p1##_type p1;\ + p0##_type const p0;\ + p1##_type const p1;\ private:\ - GTEST_DISALLOW_ASSIGN_(name##MatcherP2);\ };\ template <typename p0##_type, typename p1##_type>\ inline name##MatcherP2<p0##_type, p1##_type> name(p0##_type p0, \ @@ -1530,7 +758,7 @@ AnyOf(M1 m1, M2 m2, M3 m3, M4 m4, M5 m5, M6 m6, M7 m7, M8 m8, M9 m9, M10 m10) { template <typename arg_type>\ bool name##MatcherP2<p0##_type, \ p1##_type>::gmock_Impl<arg_type>::MatchAndExplain(\ - arg_type arg, \ + GTEST_REFERENCE_TO_CONST_(arg_type) arg,\ ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\ const @@ -1539,33 +767,36 @@ AnyOf(M1 m1, M2 m2, M3 m3, M4 m4, M5 m5, M6 m6, M7 m7, M8 m8, M9 m9, M10 m10) { class name##MatcherP3 {\ public:\ template <typename arg_type>\ - class gmock_Impl : public ::testing::MatcherInterface<arg_type> {\ + class gmock_Impl : public ::testing::MatcherInterface<\ + GTEST_REFERENCE_TO_CONST_(arg_type)> {\ public:\ gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2)\ - : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2) {}\ + : p0(::testing::internal::move(gmock_p0)), \ + p1(::testing::internal::move(gmock_p1)), \ + p2(::testing::internal::move(gmock_p2)) {}\ virtual bool MatchAndExplain(\ - arg_type arg, ::testing::MatchResultListener* result_listener) const;\ + GTEST_REFERENCE_TO_CONST_(arg_type) arg,\ + ::testing::MatchResultListener* result_listener) const;\ virtual void DescribeTo(::std::ostream* gmock_os) const {\ *gmock_os << FormatDescription(false);\ }\ virtual void DescribeNegationTo(::std::ostream* gmock_os) const {\ *gmock_os << FormatDescription(true);\ }\ - p0##_type p0;\ - p1##_type p1;\ - p2##_type p2;\ + p0##_type const p0;\ + p1##_type const p1;\ + p2##_type const p2;\ private:\ - ::testing::internal::string FormatDescription(bool negation) const {\ - const ::testing::internal::string gmock_description = (description);\ - if (!gmock_description.empty())\ + ::std::string FormatDescription(bool negation) const {\ + ::std::string gmock_description = (description);\ + if (!gmock_description.empty()) {\ return gmock_description;\ + }\ return ::testing::internal::FormatMatcherDescription(\ negation, #name, \ ::testing::internal::UniversalTersePrintTupleFieldsToStrings(\ - ::testing::tuple<p0##_type, p1##_type, p2##_type>(p0, p1, \ - p2)));\ + ::std::tuple<p0##_type, p1##_type, p2##_type>(p0, p1, p2)));\ }\ - GTEST_DISALLOW_ASSIGN_(gmock_Impl);\ };\ template <typename arg_type>\ operator ::testing::Matcher<arg_type>() const {\ @@ -1573,13 +804,14 @@ AnyOf(M1 m1, M2 m2, M3 m3, M4 m4, M5 m5, M6 m6, M7 m7, M8 m8, M9 m9, M10 m10) { new gmock_Impl<arg_type>(p0, p1, p2));\ }\ name##MatcherP3(p0##_type gmock_p0, p1##_type gmock_p1, \ - p2##_type gmock_p2) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2) {\ + p2##_type gmock_p2) : p0(::testing::internal::move(gmock_p0)), \ + p1(::testing::internal::move(gmock_p1)), \ + p2(::testing::internal::move(gmock_p2)) {\ }\ - p0##_type p0;\ - p1##_type p1;\ - p2##_type p2;\ + p0##_type const p0;\ + p1##_type const p1;\ + p2##_type const p2;\ private:\ - GTEST_DISALLOW_ASSIGN_(name##MatcherP3);\ };\ template <typename p0##_type, typename p1##_type, typename p2##_type>\ inline name##MatcherP3<p0##_type, p1##_type, p2##_type> name(p0##_type p0, \ @@ -1590,7 +822,7 @@ AnyOf(M1 m1, M2 m2, M3 m3, M4 m4, M5 m5, M6 m6, M7 m7, M8 m8, M9 m9, M10 m10) { template <typename arg_type>\ bool name##MatcherP3<p0##_type, p1##_type, \ p2##_type>::gmock_Impl<arg_type>::MatchAndExplain(\ - arg_type arg, \ + GTEST_REFERENCE_TO_CONST_(arg_type) arg,\ ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\ const @@ -1600,35 +832,40 @@ AnyOf(M1 m1, M2 m2, M3 m3, M4 m4, M5 m5, M6 m6, M7 m7, M8 m8, M9 m9, M10 m10) { class name##MatcherP4 {\ public:\ template <typename arg_type>\ - class gmock_Impl : public ::testing::MatcherInterface<arg_type> {\ + class gmock_Impl : public ::testing::MatcherInterface<\ + GTEST_REFERENCE_TO_CONST_(arg_type)> {\ public:\ gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ p3##_type gmock_p3)\ - : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), p3(gmock_p3) {}\ + : p0(::testing::internal::move(gmock_p0)), \ + p1(::testing::internal::move(gmock_p1)), \ + p2(::testing::internal::move(gmock_p2)), \ + p3(::testing::internal::move(gmock_p3)) {}\ virtual bool MatchAndExplain(\ - arg_type arg, ::testing::MatchResultListener* result_listener) const;\ + GTEST_REFERENCE_TO_CONST_(arg_type) arg,\ + ::testing::MatchResultListener* result_listener) const;\ virtual void DescribeTo(::std::ostream* gmock_os) const {\ *gmock_os << FormatDescription(false);\ }\ virtual void DescribeNegationTo(::std::ostream* gmock_os) const {\ *gmock_os << FormatDescription(true);\ }\ - p0##_type p0;\ - p1##_type p1;\ - p2##_type p2;\ - p3##_type p3;\ + p0##_type const p0;\ + p1##_type const p1;\ + p2##_type const p2;\ + p3##_type const p3;\ private:\ - ::testing::internal::string FormatDescription(bool negation) const {\ - const ::testing::internal::string gmock_description = (description);\ - if (!gmock_description.empty())\ + ::std::string FormatDescription(bool negation) const {\ + ::std::string gmock_description = (description);\ + if (!gmock_description.empty()) {\ return gmock_description;\ + }\ return ::testing::internal::FormatMatcherDescription(\ negation, #name, \ ::testing::internal::UniversalTersePrintTupleFieldsToStrings(\ - ::testing::tuple<p0##_type, p1##_type, p2##_type, \ - p3##_type>(p0, p1, p2, p3)));\ + ::std::tuple<p0##_type, p1##_type, p2##_type, p3##_type>(p0, \ + p1, p2, p3)));\ }\ - GTEST_DISALLOW_ASSIGN_(gmock_Impl);\ };\ template <typename arg_type>\ operator ::testing::Matcher<arg_type>() const {\ @@ -1636,15 +873,17 @@ AnyOf(M1 m1, M2 m2, M3 m3, M4 m4, M5 m5, M6 m6, M7 m7, M8 m8, M9 m9, M10 m10) { new gmock_Impl<arg_type>(p0, p1, p2, p3));\ }\ name##MatcherP4(p0##_type gmock_p0, p1##_type gmock_p1, \ - p2##_type gmock_p2, p3##_type gmock_p3) : p0(gmock_p0), p1(gmock_p1), \ - p2(gmock_p2), p3(gmock_p3) {\ + p2##_type gmock_p2, \ + p3##_type gmock_p3) : p0(::testing::internal::move(gmock_p0)), \ + p1(::testing::internal::move(gmock_p1)), \ + p2(::testing::internal::move(gmock_p2)), \ + p3(::testing::internal::move(gmock_p3)) {\ }\ - p0##_type p0;\ - p1##_type p1;\ - p2##_type p2;\ - p3##_type p3;\ + p0##_type const p0;\ + p1##_type const p1;\ + p2##_type const p2;\ + p3##_type const p3;\ private:\ - GTEST_DISALLOW_ASSIGN_(name##MatcherP4);\ };\ template <typename p0##_type, typename p1##_type, typename p2##_type, \ typename p3##_type>\ @@ -1659,7 +898,7 @@ AnyOf(M1 m1, M2 m2, M3 m3, M4 m4, M5 m5, M6 m6, M7 m7, M8 m8, M9 m9, M10 m10) { template <typename arg_type>\ bool name##MatcherP4<p0##_type, p1##_type, p2##_type, \ p3##_type>::gmock_Impl<arg_type>::MatchAndExplain(\ - arg_type arg, \ + GTEST_REFERENCE_TO_CONST_(arg_type) arg,\ ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\ const @@ -1669,37 +908,42 @@ AnyOf(M1 m1, M2 m2, M3 m3, M4 m4, M5 m5, M6 m6, M7 m7, M8 m8, M9 m9, M10 m10) { class name##MatcherP5 {\ public:\ template <typename arg_type>\ - class gmock_Impl : public ::testing::MatcherInterface<arg_type> {\ + class gmock_Impl : public ::testing::MatcherInterface<\ + GTEST_REFERENCE_TO_CONST_(arg_type)> {\ public:\ gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ p3##_type gmock_p3, p4##_type gmock_p4)\ - : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), p3(gmock_p3), \ - p4(gmock_p4) {}\ + : p0(::testing::internal::move(gmock_p0)), \ + p1(::testing::internal::move(gmock_p1)), \ + p2(::testing::internal::move(gmock_p2)), \ + p3(::testing::internal::move(gmock_p3)), \ + p4(::testing::internal::move(gmock_p4)) {}\ virtual bool MatchAndExplain(\ - arg_type arg, ::testing::MatchResultListener* result_listener) const;\ + GTEST_REFERENCE_TO_CONST_(arg_type) arg,\ + ::testing::MatchResultListener* result_listener) const;\ virtual void DescribeTo(::std::ostream* gmock_os) const {\ *gmock_os << FormatDescription(false);\ }\ virtual void DescribeNegationTo(::std::ostream* gmock_os) const {\ *gmock_os << FormatDescription(true);\ }\ - p0##_type p0;\ - p1##_type p1;\ - p2##_type p2;\ - p3##_type p3;\ - p4##_type p4;\ + p0##_type const p0;\ + p1##_type const p1;\ + p2##_type const p2;\ + p3##_type const p3;\ + p4##_type const p4;\ private:\ - ::testing::internal::string FormatDescription(bool negation) const {\ - const ::testing::internal::string gmock_description = (description);\ - if (!gmock_description.empty())\ + ::std::string FormatDescription(bool negation) const {\ + ::std::string gmock_description = (description);\ + if (!gmock_description.empty()) {\ return gmock_description;\ + }\ return ::testing::internal::FormatMatcherDescription(\ negation, #name, \ ::testing::internal::UniversalTersePrintTupleFieldsToStrings(\ - ::testing::tuple<p0##_type, p1##_type, p2##_type, p3##_type, \ + ::std::tuple<p0##_type, p1##_type, p2##_type, p3##_type, \ p4##_type>(p0, p1, p2, p3, p4)));\ }\ - GTEST_DISALLOW_ASSIGN_(gmock_Impl);\ };\ template <typename arg_type>\ operator ::testing::Matcher<arg_type>() const {\ @@ -1708,16 +952,18 @@ AnyOf(M1 m1, M2 m2, M3 m3, M4 m4, M5 m5, M6 m6, M7 m7, M8 m8, M9 m9, M10 m10) { }\ name##MatcherP5(p0##_type gmock_p0, p1##_type gmock_p1, \ p2##_type gmock_p2, p3##_type gmock_p3, \ - p4##_type gmock_p4) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), \ - p3(gmock_p3), p4(gmock_p4) {\ + p4##_type gmock_p4) : p0(::testing::internal::move(gmock_p0)), \ + p1(::testing::internal::move(gmock_p1)), \ + p2(::testing::internal::move(gmock_p2)), \ + p3(::testing::internal::move(gmock_p3)), \ + p4(::testing::internal::move(gmock_p4)) {\ }\ - p0##_type p0;\ - p1##_type p1;\ - p2##_type p2;\ - p3##_type p3;\ - p4##_type p4;\ + p0##_type const p0;\ + p1##_type const p1;\ + p2##_type const p2;\ + p3##_type const p3;\ + p4##_type const p4;\ private:\ - GTEST_DISALLOW_ASSIGN_(name##MatcherP5);\ };\ template <typename p0##_type, typename p1##_type, typename p2##_type, \ typename p3##_type, typename p4##_type>\ @@ -1732,7 +978,7 @@ AnyOf(M1 m1, M2 m2, M3 m3, M4 m4, M5 m5, M6 m6, M7 m7, M8 m8, M9 m9, M10 m10) { template <typename arg_type>\ bool name##MatcherP5<p0##_type, p1##_type, p2##_type, p3##_type, \ p4##_type>::gmock_Impl<arg_type>::MatchAndExplain(\ - arg_type arg, \ + GTEST_REFERENCE_TO_CONST_(arg_type) arg,\ ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\ const @@ -1742,38 +988,44 @@ AnyOf(M1 m1, M2 m2, M3 m3, M4 m4, M5 m5, M6 m6, M7 m7, M8 m8, M9 m9, M10 m10) { class name##MatcherP6 {\ public:\ template <typename arg_type>\ - class gmock_Impl : public ::testing::MatcherInterface<arg_type> {\ + class gmock_Impl : public ::testing::MatcherInterface<\ + GTEST_REFERENCE_TO_CONST_(arg_type)> {\ public:\ gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5)\ - : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), p3(gmock_p3), \ - p4(gmock_p4), p5(gmock_p5) {}\ + : p0(::testing::internal::move(gmock_p0)), \ + p1(::testing::internal::move(gmock_p1)), \ + p2(::testing::internal::move(gmock_p2)), \ + p3(::testing::internal::move(gmock_p3)), \ + p4(::testing::internal::move(gmock_p4)), \ + p5(::testing::internal::move(gmock_p5)) {}\ virtual bool MatchAndExplain(\ - arg_type arg, ::testing::MatchResultListener* result_listener) const;\ + GTEST_REFERENCE_TO_CONST_(arg_type) arg,\ + ::testing::MatchResultListener* result_listener) const;\ virtual void DescribeTo(::std::ostream* gmock_os) const {\ *gmock_os << FormatDescription(false);\ }\ virtual void DescribeNegationTo(::std::ostream* gmock_os) const {\ *gmock_os << FormatDescription(true);\ }\ - p0##_type p0;\ - p1##_type p1;\ - p2##_type p2;\ - p3##_type p3;\ - p4##_type p4;\ - p5##_type p5;\ + p0##_type const p0;\ + p1##_type const p1;\ + p2##_type const p2;\ + p3##_type const p3;\ + p4##_type const p4;\ + p5##_type const p5;\ private:\ - ::testing::internal::string FormatDescription(bool negation) const {\ - const ::testing::internal::string gmock_description = (description);\ - if (!gmock_description.empty())\ + ::std::string FormatDescription(bool negation) const {\ + ::std::string gmock_description = (description);\ + if (!gmock_description.empty()) {\ return gmock_description;\ + }\ return ::testing::internal::FormatMatcherDescription(\ negation, #name, \ ::testing::internal::UniversalTersePrintTupleFieldsToStrings(\ - ::testing::tuple<p0##_type, p1##_type, p2##_type, p3##_type, \ + ::std::tuple<p0##_type, p1##_type, p2##_type, p3##_type, \ p4##_type, p5##_type>(p0, p1, p2, p3, p4, p5)));\ }\ - GTEST_DISALLOW_ASSIGN_(gmock_Impl);\ };\ template <typename arg_type>\ operator ::testing::Matcher<arg_type>() const {\ @@ -1782,17 +1034,20 @@ AnyOf(M1 m1, M2 m2, M3 m3, M4 m4, M5 m5, M6 m6, M7 m7, M8 m8, M9 m9, M10 m10) { }\ name##MatcherP6(p0##_type gmock_p0, p1##_type gmock_p1, \ p2##_type gmock_p2, p3##_type gmock_p3, p4##_type gmock_p4, \ - p5##_type gmock_p5) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), \ - p3(gmock_p3), p4(gmock_p4), p5(gmock_p5) {\ + p5##_type gmock_p5) : p0(::testing::internal::move(gmock_p0)), \ + p1(::testing::internal::move(gmock_p1)), \ + p2(::testing::internal::move(gmock_p2)), \ + p3(::testing::internal::move(gmock_p3)), \ + p4(::testing::internal::move(gmock_p4)), \ + p5(::testing::internal::move(gmock_p5)) {\ }\ - p0##_type p0;\ - p1##_type p1;\ - p2##_type p2;\ - p3##_type p3;\ - p4##_type p4;\ - p5##_type p5;\ + p0##_type const p0;\ + p1##_type const p1;\ + p2##_type const p2;\ + p3##_type const p3;\ + p4##_type const p4;\ + p5##_type const p5;\ private:\ - GTEST_DISALLOW_ASSIGN_(name##MatcherP6);\ };\ template <typename p0##_type, typename p1##_type, typename p2##_type, \ typename p3##_type, typename p4##_type, typename p5##_type>\ @@ -1807,7 +1062,7 @@ AnyOf(M1 m1, M2 m2, M3 m3, M4 m4, M5 m5, M6 m6, M7 m7, M8 m8, M9 m9, M10 m10) { template <typename arg_type>\ bool name##MatcherP6<p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, \ p5##_type>::gmock_Impl<arg_type>::MatchAndExplain(\ - arg_type arg, \ + GTEST_REFERENCE_TO_CONST_(arg_type) arg,\ ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\ const @@ -1818,41 +1073,48 @@ AnyOf(M1 m1, M2 m2, M3 m3, M4 m4, M5 m5, M6 m6, M7 m7, M8 m8, M9 m9, M10 m10) { class name##MatcherP7 {\ public:\ template <typename arg_type>\ - class gmock_Impl : public ::testing::MatcherInterface<arg_type> {\ + class gmock_Impl : public ::testing::MatcherInterface<\ + GTEST_REFERENCE_TO_CONST_(arg_type)> {\ public:\ gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \ p6##_type gmock_p6)\ - : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), p3(gmock_p3), \ - p4(gmock_p4), p5(gmock_p5), p6(gmock_p6) {}\ + : p0(::testing::internal::move(gmock_p0)), \ + p1(::testing::internal::move(gmock_p1)), \ + p2(::testing::internal::move(gmock_p2)), \ + p3(::testing::internal::move(gmock_p3)), \ + p4(::testing::internal::move(gmock_p4)), \ + p5(::testing::internal::move(gmock_p5)), \ + p6(::testing::internal::move(gmock_p6)) {}\ virtual bool MatchAndExplain(\ - arg_type arg, ::testing::MatchResultListener* result_listener) const;\ + GTEST_REFERENCE_TO_CONST_(arg_type) arg,\ + ::testing::MatchResultListener* result_listener) const;\ virtual void DescribeTo(::std::ostream* gmock_os) const {\ *gmock_os << FormatDescription(false);\ }\ virtual void DescribeNegationTo(::std::ostream* gmock_os) const {\ *gmock_os << FormatDescription(true);\ }\ - p0##_type p0;\ - p1##_type p1;\ - p2##_type p2;\ - p3##_type p3;\ - p4##_type p4;\ - p5##_type p5;\ - p6##_type p6;\ + p0##_type const p0;\ + p1##_type const p1;\ + p2##_type const p2;\ + p3##_type const p3;\ + p4##_type const p4;\ + p5##_type const p5;\ + p6##_type const p6;\ private:\ - ::testing::internal::string FormatDescription(bool negation) const {\ - const ::testing::internal::string gmock_description = (description);\ - if (!gmock_description.empty())\ + ::std::string FormatDescription(bool negation) const {\ + ::std::string gmock_description = (description);\ + if (!gmock_description.empty()) {\ return gmock_description;\ + }\ return ::testing::internal::FormatMatcherDescription(\ negation, #name, \ ::testing::internal::UniversalTersePrintTupleFieldsToStrings(\ - ::testing::tuple<p0##_type, p1##_type, p2##_type, p3##_type, \ + ::std::tuple<p0##_type, p1##_type, p2##_type, p3##_type, \ p4##_type, p5##_type, p6##_type>(p0, p1, p2, p3, p4, p5, \ p6)));\ }\ - GTEST_DISALLOW_ASSIGN_(gmock_Impl);\ };\ template <typename arg_type>\ operator ::testing::Matcher<arg_type>() const {\ @@ -1861,19 +1123,23 @@ AnyOf(M1 m1, M2 m2, M3 m3, M4 m4, M5 m5, M6 m6, M7 m7, M8 m8, M9 m9, M10 m10) { }\ name##MatcherP7(p0##_type gmock_p0, p1##_type gmock_p1, \ p2##_type gmock_p2, p3##_type gmock_p3, p4##_type gmock_p4, \ - p5##_type gmock_p5, p6##_type gmock_p6) : p0(gmock_p0), p1(gmock_p1), \ - p2(gmock_p2), p3(gmock_p3), p4(gmock_p4), p5(gmock_p5), \ - p6(gmock_p6) {\ + p5##_type gmock_p5, \ + p6##_type gmock_p6) : p0(::testing::internal::move(gmock_p0)), \ + p1(::testing::internal::move(gmock_p1)), \ + p2(::testing::internal::move(gmock_p2)), \ + p3(::testing::internal::move(gmock_p3)), \ + p4(::testing::internal::move(gmock_p4)), \ + p5(::testing::internal::move(gmock_p5)), \ + p6(::testing::internal::move(gmock_p6)) {\ }\ - p0##_type p0;\ - p1##_type p1;\ - p2##_type p2;\ - p3##_type p3;\ - p4##_type p4;\ - p5##_type p5;\ - p6##_type p6;\ + p0##_type const p0;\ + p1##_type const p1;\ + p2##_type const p2;\ + p3##_type const p3;\ + p4##_type const p4;\ + p5##_type const p5;\ + p6##_type const p6;\ private:\ - GTEST_DISALLOW_ASSIGN_(name##MatcherP7);\ };\ template <typename p0##_type, typename p1##_type, typename p2##_type, \ typename p3##_type, typename p4##_type, typename p5##_type, \ @@ -1891,7 +1157,7 @@ AnyOf(M1 m1, M2 m2, M3 m3, M4 m4, M5 m5, M6 m6, M7 m7, M8 m8, M9 m9, M10 m10) { template <typename arg_type>\ bool name##MatcherP7<p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, \ p5##_type, p6##_type>::gmock_Impl<arg_type>::MatchAndExplain(\ - arg_type arg, \ + GTEST_REFERENCE_TO_CONST_(arg_type) arg,\ ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\ const @@ -1902,42 +1168,50 @@ AnyOf(M1 m1, M2 m2, M3 m3, M4 m4, M5 m5, M6 m6, M7 m7, M8 m8, M9 m9, M10 m10) { class name##MatcherP8 {\ public:\ template <typename arg_type>\ - class gmock_Impl : public ::testing::MatcherInterface<arg_type> {\ + class gmock_Impl : public ::testing::MatcherInterface<\ + GTEST_REFERENCE_TO_CONST_(arg_type)> {\ public:\ gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \ p6##_type gmock_p6, p7##_type gmock_p7)\ - : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), p3(gmock_p3), \ - p4(gmock_p4), p5(gmock_p5), p6(gmock_p6), p7(gmock_p7) {}\ + : p0(::testing::internal::move(gmock_p0)), \ + p1(::testing::internal::move(gmock_p1)), \ + p2(::testing::internal::move(gmock_p2)), \ + p3(::testing::internal::move(gmock_p3)), \ + p4(::testing::internal::move(gmock_p4)), \ + p5(::testing::internal::move(gmock_p5)), \ + p6(::testing::internal::move(gmock_p6)), \ + p7(::testing::internal::move(gmock_p7)) {}\ virtual bool MatchAndExplain(\ - arg_type arg, ::testing::MatchResultListener* result_listener) const;\ + GTEST_REFERENCE_TO_CONST_(arg_type) arg,\ + ::testing::MatchResultListener* result_listener) const;\ virtual void DescribeTo(::std::ostream* gmock_os) const {\ *gmock_os << FormatDescription(false);\ }\ virtual void DescribeNegationTo(::std::ostream* gmock_os) const {\ *gmock_os << FormatDescription(true);\ }\ - p0##_type p0;\ - p1##_type p1;\ - p2##_type p2;\ - p3##_type p3;\ - p4##_type p4;\ - p5##_type p5;\ - p6##_type p6;\ - p7##_type p7;\ + p0##_type const p0;\ + p1##_type const p1;\ + p2##_type const p2;\ + p3##_type const p3;\ + p4##_type const p4;\ + p5##_type const p5;\ + p6##_type const p6;\ + p7##_type const p7;\ private:\ - ::testing::internal::string FormatDescription(bool negation) const {\ - const ::testing::internal::string gmock_description = (description);\ - if (!gmock_description.empty())\ + ::std::string FormatDescription(bool negation) const {\ + ::std::string gmock_description = (description);\ + if (!gmock_description.empty()) {\ return gmock_description;\ + }\ return ::testing::internal::FormatMatcherDescription(\ negation, #name, \ ::testing::internal::UniversalTersePrintTupleFieldsToStrings(\ - ::testing::tuple<p0##_type, p1##_type, p2##_type, p3##_type, \ + ::std::tuple<p0##_type, p1##_type, p2##_type, p3##_type, \ p4##_type, p5##_type, p6##_type, p7##_type>(p0, p1, p2, \ p3, p4, p5, p6, p7)));\ }\ - GTEST_DISALLOW_ASSIGN_(gmock_Impl);\ };\ template <typename arg_type>\ operator ::testing::Matcher<arg_type>() const {\ @@ -1947,20 +1221,24 @@ AnyOf(M1 m1, M2 m2, M3 m3, M4 m4, M5 m5, M6 m6, M7 m7, M8 m8, M9 m9, M10 m10) { name##MatcherP8(p0##_type gmock_p0, p1##_type gmock_p1, \ p2##_type gmock_p2, p3##_type gmock_p3, p4##_type gmock_p4, \ p5##_type gmock_p5, p6##_type gmock_p6, \ - p7##_type gmock_p7) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), \ - p3(gmock_p3), p4(gmock_p4), p5(gmock_p5), p6(gmock_p6), \ - p7(gmock_p7) {\ + p7##_type gmock_p7) : p0(::testing::internal::move(gmock_p0)), \ + p1(::testing::internal::move(gmock_p1)), \ + p2(::testing::internal::move(gmock_p2)), \ + p3(::testing::internal::move(gmock_p3)), \ + p4(::testing::internal::move(gmock_p4)), \ + p5(::testing::internal::move(gmock_p5)), \ + p6(::testing::internal::move(gmock_p6)), \ + p7(::testing::internal::move(gmock_p7)) {\ }\ - p0##_type p0;\ - p1##_type p1;\ - p2##_type p2;\ - p3##_type p3;\ - p4##_type p4;\ - p5##_type p5;\ - p6##_type p6;\ - p7##_type p7;\ + p0##_type const p0;\ + p1##_type const p1;\ + p2##_type const p2;\ + p3##_type const p3;\ + p4##_type const p4;\ + p5##_type const p5;\ + p6##_type const p6;\ + p7##_type const p7;\ private:\ - GTEST_DISALLOW_ASSIGN_(name##MatcherP8);\ };\ template <typename p0##_type, typename p1##_type, typename p2##_type, \ typename p3##_type, typename p4##_type, typename p5##_type, \ @@ -1980,7 +1258,7 @@ AnyOf(M1 m1, M2 m2, M3 m3, M4 m4, M5 m5, M6 m6, M7 m7, M8 m8, M9 m9, M10 m10) { bool name##MatcherP8<p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, \ p5##_type, p6##_type, \ p7##_type>::gmock_Impl<arg_type>::MatchAndExplain(\ - arg_type arg, \ + GTEST_REFERENCE_TO_CONST_(arg_type) arg,\ ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\ const @@ -1991,44 +1269,52 @@ AnyOf(M1 m1, M2 m2, M3 m3, M4 m4, M5 m5, M6 m6, M7 m7, M8 m8, M9 m9, M10 m10) { class name##MatcherP9 {\ public:\ template <typename arg_type>\ - class gmock_Impl : public ::testing::MatcherInterface<arg_type> {\ + class gmock_Impl : public ::testing::MatcherInterface<\ + GTEST_REFERENCE_TO_CONST_(arg_type)> {\ public:\ gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \ p6##_type gmock_p6, p7##_type gmock_p7, p8##_type gmock_p8)\ - : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), p3(gmock_p3), \ - p4(gmock_p4), p5(gmock_p5), p6(gmock_p6), p7(gmock_p7), \ - p8(gmock_p8) {}\ + : p0(::testing::internal::move(gmock_p0)), \ + p1(::testing::internal::move(gmock_p1)), \ + p2(::testing::internal::move(gmock_p2)), \ + p3(::testing::internal::move(gmock_p3)), \ + p4(::testing::internal::move(gmock_p4)), \ + p5(::testing::internal::move(gmock_p5)), \ + p6(::testing::internal::move(gmock_p6)), \ + p7(::testing::internal::move(gmock_p7)), \ + p8(::testing::internal::move(gmock_p8)) {}\ virtual bool MatchAndExplain(\ - arg_type arg, ::testing::MatchResultListener* result_listener) const;\ + GTEST_REFERENCE_TO_CONST_(arg_type) arg,\ + ::testing::MatchResultListener* result_listener) const;\ virtual void DescribeTo(::std::ostream* gmock_os) const {\ *gmock_os << FormatDescription(false);\ }\ virtual void DescribeNegationTo(::std::ostream* gmock_os) const {\ *gmock_os << FormatDescription(true);\ }\ - p0##_type p0;\ - p1##_type p1;\ - p2##_type p2;\ - p3##_type p3;\ - p4##_type p4;\ - p5##_type p5;\ - p6##_type p6;\ - p7##_type p7;\ - p8##_type p8;\ + p0##_type const p0;\ + p1##_type const p1;\ + p2##_type const p2;\ + p3##_type const p3;\ + p4##_type const p4;\ + p5##_type const p5;\ + p6##_type const p6;\ + p7##_type const p7;\ + p8##_type const p8;\ private:\ - ::testing::internal::string FormatDescription(bool negation) const {\ - const ::testing::internal::string gmock_description = (description);\ - if (!gmock_description.empty())\ + ::std::string FormatDescription(bool negation) const {\ + ::std::string gmock_description = (description);\ + if (!gmock_description.empty()) {\ return gmock_description;\ + }\ return ::testing::internal::FormatMatcherDescription(\ negation, #name, \ ::testing::internal::UniversalTersePrintTupleFieldsToStrings(\ - ::testing::tuple<p0##_type, p1##_type, p2##_type, p3##_type, \ + ::std::tuple<p0##_type, p1##_type, p2##_type, p3##_type, \ p4##_type, p5##_type, p6##_type, p7##_type, \ p8##_type>(p0, p1, p2, p3, p4, p5, p6, p7, p8)));\ }\ - GTEST_DISALLOW_ASSIGN_(gmock_Impl);\ };\ template <typename arg_type>\ operator ::testing::Matcher<arg_type>() const {\ @@ -2038,21 +1324,26 @@ AnyOf(M1 m1, M2 m2, M3 m3, M4 m4, M5 m5, M6 m6, M7 m7, M8 m8, M9 m9, M10 m10) { name##MatcherP9(p0##_type gmock_p0, p1##_type gmock_p1, \ p2##_type gmock_p2, p3##_type gmock_p3, p4##_type gmock_p4, \ p5##_type gmock_p5, p6##_type gmock_p6, p7##_type gmock_p7, \ - p8##_type gmock_p8) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), \ - p3(gmock_p3), p4(gmock_p4), p5(gmock_p5), p6(gmock_p6), p7(gmock_p7), \ - p8(gmock_p8) {\ + p8##_type gmock_p8) : p0(::testing::internal::move(gmock_p0)), \ + p1(::testing::internal::move(gmock_p1)), \ + p2(::testing::internal::move(gmock_p2)), \ + p3(::testing::internal::move(gmock_p3)), \ + p4(::testing::internal::move(gmock_p4)), \ + p5(::testing::internal::move(gmock_p5)), \ + p6(::testing::internal::move(gmock_p6)), \ + p7(::testing::internal::move(gmock_p7)), \ + p8(::testing::internal::move(gmock_p8)) {\ }\ - p0##_type p0;\ - p1##_type p1;\ - p2##_type p2;\ - p3##_type p3;\ - p4##_type p4;\ - p5##_type p5;\ - p6##_type p6;\ - p7##_type p7;\ - p8##_type p8;\ + p0##_type const p0;\ + p1##_type const p1;\ + p2##_type const p2;\ + p3##_type const p3;\ + p4##_type const p4;\ + p5##_type const p5;\ + p6##_type const p6;\ + p7##_type const p7;\ + p8##_type const p8;\ private:\ - GTEST_DISALLOW_ASSIGN_(name##MatcherP9);\ };\ template <typename p0##_type, typename p1##_type, typename p2##_type, \ typename p3##_type, typename p4##_type, typename p5##_type, \ @@ -2073,7 +1364,7 @@ AnyOf(M1 m1, M2 m2, M3 m3, M4 m4, M5 m5, M6 m6, M7 m7, M8 m8, M9 m9, M10 m10) { bool name##MatcherP9<p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, \ p5##_type, p6##_type, p7##_type, \ p8##_type>::gmock_Impl<arg_type>::MatchAndExplain(\ - arg_type arg, \ + GTEST_REFERENCE_TO_CONST_(arg_type) arg,\ ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\ const @@ -2085,46 +1376,55 @@ AnyOf(M1 m1, M2 m2, M3 m3, M4 m4, M5 m5, M6 m6, M7 m7, M8 m8, M9 m9, M10 m10) { class name##MatcherP10 {\ public:\ template <typename arg_type>\ - class gmock_Impl : public ::testing::MatcherInterface<arg_type> {\ + class gmock_Impl : public ::testing::MatcherInterface<\ + GTEST_REFERENCE_TO_CONST_(arg_type)> {\ public:\ gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \ p6##_type gmock_p6, p7##_type gmock_p7, p8##_type gmock_p8, \ p9##_type gmock_p9)\ - : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), p3(gmock_p3), \ - p4(gmock_p4), p5(gmock_p5), p6(gmock_p6), p7(gmock_p7), \ - p8(gmock_p8), p9(gmock_p9) {}\ + : p0(::testing::internal::move(gmock_p0)), \ + p1(::testing::internal::move(gmock_p1)), \ + p2(::testing::internal::move(gmock_p2)), \ + p3(::testing::internal::move(gmock_p3)), \ + p4(::testing::internal::move(gmock_p4)), \ + p5(::testing::internal::move(gmock_p5)), \ + p6(::testing::internal::move(gmock_p6)), \ + p7(::testing::internal::move(gmock_p7)), \ + p8(::testing::internal::move(gmock_p8)), \ + p9(::testing::internal::move(gmock_p9)) {}\ virtual bool MatchAndExplain(\ - arg_type arg, ::testing::MatchResultListener* result_listener) const;\ + GTEST_REFERENCE_TO_CONST_(arg_type) arg,\ + ::testing::MatchResultListener* result_listener) const;\ virtual void DescribeTo(::std::ostream* gmock_os) const {\ *gmock_os << FormatDescription(false);\ }\ virtual void DescribeNegationTo(::std::ostream* gmock_os) const {\ *gmock_os << FormatDescription(true);\ }\ - p0##_type p0;\ - p1##_type p1;\ - p2##_type p2;\ - p3##_type p3;\ - p4##_type p4;\ - p5##_type p5;\ - p6##_type p6;\ - p7##_type p7;\ - p8##_type p8;\ - p9##_type p9;\ + p0##_type const p0;\ + p1##_type const p1;\ + p2##_type const p2;\ + p3##_type const p3;\ + p4##_type const p4;\ + p5##_type const p5;\ + p6##_type const p6;\ + p7##_type const p7;\ + p8##_type const p8;\ + p9##_type const p9;\ private:\ - ::testing::internal::string FormatDescription(bool negation) const {\ - const ::testing::internal::string gmock_description = (description);\ - if (!gmock_description.empty())\ + ::std::string FormatDescription(bool negation) const {\ + ::std::string gmock_description = (description);\ + if (!gmock_description.empty()) {\ return gmock_description;\ + }\ return ::testing::internal::FormatMatcherDescription(\ negation, #name, \ ::testing::internal::UniversalTersePrintTupleFieldsToStrings(\ - ::testing::tuple<p0##_type, p1##_type, p2##_type, p3##_type, \ + ::std::tuple<p0##_type, p1##_type, p2##_type, p3##_type, \ p4##_type, p5##_type, p6##_type, p7##_type, p8##_type, \ p9##_type>(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9)));\ }\ - GTEST_DISALLOW_ASSIGN_(gmock_Impl);\ };\ template <typename arg_type>\ operator ::testing::Matcher<arg_type>() const {\ @@ -2134,22 +1434,29 @@ AnyOf(M1 m1, M2 m2, M3 m3, M4 m4, M5 m5, M6 m6, M7 m7, M8 m8, M9 m9, M10 m10) { name##MatcherP10(p0##_type gmock_p0, p1##_type gmock_p1, \ p2##_type gmock_p2, p3##_type gmock_p3, p4##_type gmock_p4, \ p5##_type gmock_p5, p6##_type gmock_p6, p7##_type gmock_p7, \ - p8##_type gmock_p8, p9##_type gmock_p9) : p0(gmock_p0), p1(gmock_p1), \ - p2(gmock_p2), p3(gmock_p3), p4(gmock_p4), p5(gmock_p5), p6(gmock_p6), \ - p7(gmock_p7), p8(gmock_p8), p9(gmock_p9) {\ + p8##_type gmock_p8, \ + p9##_type gmock_p9) : p0(::testing::internal::move(gmock_p0)), \ + p1(::testing::internal::move(gmock_p1)), \ + p2(::testing::internal::move(gmock_p2)), \ + p3(::testing::internal::move(gmock_p3)), \ + p4(::testing::internal::move(gmock_p4)), \ + p5(::testing::internal::move(gmock_p5)), \ + p6(::testing::internal::move(gmock_p6)), \ + p7(::testing::internal::move(gmock_p7)), \ + p8(::testing::internal::move(gmock_p8)), \ + p9(::testing::internal::move(gmock_p9)) {\ }\ - p0##_type p0;\ - p1##_type p1;\ - p2##_type p2;\ - p3##_type p3;\ - p4##_type p4;\ - p5##_type p5;\ - p6##_type p6;\ - p7##_type p7;\ - p8##_type p8;\ - p9##_type p9;\ + p0##_type const p0;\ + p1##_type const p1;\ + p2##_type const p2;\ + p3##_type const p3;\ + p4##_type const p4;\ + p5##_type const p5;\ + p6##_type const p6;\ + p7##_type const p7;\ + p8##_type const p8;\ + p9##_type const p9;\ private:\ - GTEST_DISALLOW_ASSIGN_(name##MatcherP10);\ };\ template <typename p0##_type, typename p1##_type, typename p2##_type, \ typename p3##_type, typename p4##_type, typename p5##_type, \ @@ -2172,7 +1479,7 @@ AnyOf(M1 m1, M2 m2, M3 m3, M4 m4, M5 m5, M6 m6, M7 m7, M8 m8, M9 m9, M10 m10) { bool name##MatcherP10<p0##_type, p1##_type, p2##_type, p3##_type, \ p4##_type, p5##_type, p6##_type, p7##_type, p8##_type, \ p9##_type>::gmock_Impl<arg_type>::MatchAndExplain(\ - arg_type arg, \ + GTEST_REFERENCE_TO_CONST_(arg_type) arg,\ ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\ const diff --git a/googlemock/include/gmock/gmock-generated-matchers.h.pump b/googlemock/include/gmock/gmock-generated-matchers.h.pump index de30c2c..29b004d 100644 --- a/googlemock/include/gmock/gmock-generated-matchers.h.pump +++ b/googlemock/include/gmock/gmock-generated-matchers.h.pump @@ -1,6 +1,6 @@ $$ -*- mode: c++; -*- -$$ This is a Pump source file. Please use Pump to convert it to -$$ gmock-generated-actions.h. +$$ This is a Pump source file. Please use Pump to convert +$$ it to gmock-generated-matchers.h. $$ $var n = 10 $$ The maximum arity we support. $$ }} This line fixes auto-indentation of the following code in Emacs. @@ -37,6 +37,8 @@ $$ }} This line fixes auto-indentation of the following code in Emacs. // // This file implements some commonly used variadic matchers. +// GOOGLETEST_CM0002 DO NOT DELETE + #ifndef GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_MATCHERS_H_ #define GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_MATCHERS_H_ @@ -53,7 +55,7 @@ $range i 0..n-1 // The type of the i-th (0-based) field of Tuple. #define GMOCK_FIELD_TYPE_(Tuple, i) \ - typename ::testing::tuple_element<i, Tuple>::type + typename ::std::tuple_element<i, Tuple>::type // TupleFields<Tuple, k0, ..., kn> is for selecting fields from a // tuple of type Tuple. It has two members: @@ -61,10 +63,11 @@ $range i 0..n-1 // type: a tuple type whose i-th field is the ki-th field of Tuple. // GetSelectedFields(t): returns fields k0, ..., and kn of t as a tuple. // -// For example, in class TupleFields<tuple<bool, char, int>, 2, 0>, we have: +// For example, in class TupleFields<std::tuple<bool, char, int>, 2, 0>, +// we have: // -// type is tuple<int, bool>, and -// GetSelectedFields(make_tuple(true, 'a', 42)) is (42, true). +// type is std::tuple<int, bool>, and +// GetSelectedFields(std::make_tuple(true, 'a', 42)) is (42, true). template <class Tuple$for i [[, int k$i = -1]]> class TupleFields; @@ -73,9 +76,9 @@ class TupleFields; template <class Tuple$for i [[, int k$i]]> class TupleFields { public: - typedef ::testing::tuple<$for i, [[GMOCK_FIELD_TYPE_(Tuple, k$i)]]> type; + typedef ::std::tuple<$for i, [[GMOCK_FIELD_TYPE_(Tuple, k$i)]]> type; static type GetSelectedFields(const Tuple& t) { - return type($for i, [[get<k$i>(t)]]); + return type($for i, [[std::get<k$i>(t)]]); } }; @@ -89,9 +92,9 @@ $range k 0..n-1 template <class Tuple$for j [[, int k$j]]> class TupleFields<Tuple, $for k, [[$if k < i [[k$k]] $else [[-1]]]]> { public: - typedef ::testing::tuple<$for j, [[GMOCK_FIELD_TYPE_(Tuple, k$j)]]> type; + typedef ::std::tuple<$for j, [[GMOCK_FIELD_TYPE_(Tuple, k$j)]]> type; static type GetSelectedFields(const Tuple& $if i==0 [[/* t */]] $else [[t]]) { - return type($for j, [[get<k$j>(t)]]); + return type($for j, [[std::get<k$j>(t)]]); } }; @@ -185,66 +188,6 @@ class ArgsMatcher { GTEST_DISALLOW_ASSIGN_(ArgsMatcher); }; -// A set of metafunctions for computing the result type of AllOf. -// AllOf(m1, ..., mN) returns -// AllOfResultN<decltype(m1), ..., decltype(mN)>::type. - -// Although AllOf isn't defined for one argument, AllOfResult1 is defined -// to simplify the implementation. -template <typename M1> -struct AllOfResult1 { - typedef M1 type; -}; - -$range i 1..n - -$range i 2..n -$for i [[ -$range j 2..i -$var m = i/2 -$range k 1..m -$range t m+1..i - -template <typename M1$for j [[, typename M$j]]> -struct AllOfResult$i { - typedef BothOfMatcher< - typename AllOfResult$m<$for k, [[M$k]]>::type, - typename AllOfResult$(i-m)<$for t, [[M$t]]>::type - > type; -}; - -]] - -// A set of metafunctions for computing the result type of AnyOf. -// AnyOf(m1, ..., mN) returns -// AnyOfResultN<decltype(m1), ..., decltype(mN)>::type. - -// Although AnyOf isn't defined for one argument, AnyOfResult1 is defined -// to simplify the implementation. -template <typename M1> -struct AnyOfResult1 { - typedef M1 type; -}; - -$range i 1..n - -$range i 2..n -$for i [[ -$range j 2..i -$var m = i/2 -$range k 1..m -$range t m+1..i - -template <typename M1$for j [[, typename M$j]]> -struct AnyOfResult$i { - typedef EitherOfMatcher< - typename AnyOfResult$m<$for k, [[M$k]]>::type, - typename AnyOfResult$(i-m)<$for t, [[M$t]]>::type - > type; -}; - -]] - } // namespace internal // Args<N1, N2, ..., Nk>(a_matcher) matches a tuple if the selected @@ -262,112 +205,6 @@ Args(const InnerMatcher& matcher) { ]] -// ElementsAre(e_1, e_2, ... e_n) matches an STL-style container with -// n elements, where the i-th element in the container must -// match the i-th argument in the list. Each argument of -// ElementsAre() can be either a value or a matcher. We support up to -// $n arguments. -// -// The use of DecayArray in the implementation allows ElementsAre() -// to accept string literals, whose type is const char[N], but we -// want to treat them as const char*. -// -// NOTE: Since ElementsAre() cares about the order of the elements, it -// must not be used with containers whose elements's order is -// undefined (e.g. hash_map). - -$range i 0..n -$for i [[ - -$range j 1..i - -$if i>0 [[ - -template <$for j, [[typename T$j]]> -]] - -inline internal::ElementsAreMatcher< - ::testing::tuple< -$for j, [[ - - typename internal::DecayArray<T$j[[]]>::type]]> > -ElementsAre($for j, [[const T$j& e$j]]) { - typedef ::testing::tuple< -$for j, [[ - - typename internal::DecayArray<T$j[[]]>::type]]> Args; - return internal::ElementsAreMatcher<Args>(Args($for j, [[e$j]])); -} - -]] - -// UnorderedElementsAre(e_1, e_2, ..., e_n) is an ElementsAre extension -// that matches n elements in any order. We support up to n=$n arguments. - -$range i 0..n -$for i [[ - -$range j 1..i - -$if i>0 [[ - -template <$for j, [[typename T$j]]> -]] - -inline internal::UnorderedElementsAreMatcher< - ::testing::tuple< -$for j, [[ - - typename internal::DecayArray<T$j[[]]>::type]]> > -UnorderedElementsAre($for j, [[const T$j& e$j]]) { - typedef ::testing::tuple< -$for j, [[ - - typename internal::DecayArray<T$j[[]]>::type]]> Args; - return internal::UnorderedElementsAreMatcher<Args>(Args($for j, [[e$j]])); -} - -]] - -// AllOf(m1, m2, ..., mk) matches any value that matches all of the given -// sub-matchers. AllOf is called fully qualified to prevent ADL from firing. - -$range i 2..n -$for i [[ -$range j 1..i -$var m = i/2 -$range k 1..m -$range t m+1..i - -template <$for j, [[typename M$j]]> -inline typename internal::AllOfResult$i<$for j, [[M$j]]>::type -AllOf($for j, [[M$j m$j]]) { - return typename internal::AllOfResult$i<$for j, [[M$j]]>::type( - $if m == 1 [[m1]] $else [[::testing::AllOf($for k, [[m$k]])]], - $if m+1 == i [[m$i]] $else [[::testing::AllOf($for t, [[m$t]])]]); -} - -]] - -// AnyOf(m1, m2, ..., mk) matches any value that matches any of the given -// sub-matchers. AnyOf is called fully qualified to prevent ADL from firing. - -$range i 2..n -$for i [[ -$range j 1..i -$var m = i/2 -$range k 1..m -$range t m+1..i - -template <$for j, [[typename M$j]]> -inline typename internal::AnyOfResult$i<$for j, [[M$j]]>::type -AnyOf($for j, [[M$j m$j]]) { - return typename internal::AnyOfResult$i<$for j, [[M$j]]>::type( - $if m == 1 [[m1]] $else [[::testing::AnyOf($for k, [[m$k]])]], - $if m+1 == i [[m$i]] $else [[::testing::AnyOf($for t, [[m$t]])]]); -} - -]] } // namespace testing $$ } // This Pump meta comment fixes auto-indentation in Emacs. It will not @@ -479,7 +316,7 @@ $$ // show up in the generated code. // using testing::PrintToString; // // MATCHER_P2(InClosedRange, low, hi, -// string(negation ? "is not" : "is") + " in range [" + +// std::string(negation ? "is not" : "is") + " in range [" + // PrintToString(low) + ", " + PrintToString(hi) + "]") { // return low <= arg && arg <= hi; // } @@ -587,7 +424,8 @@ $$ // show up in the generated code. // ================ // // To learn more about using these macros, please search for 'MATCHER' -// on http://code.google.com/p/googlemock/wiki/CookBook. +// on +// https://github.com/google/googletest/blob/master/googlemock/docs/CookBook.md $range i 0..n $for i @@ -604,32 +442,34 @@ $var template = [[$if i==0 [[]] $else [[ ]]]] $var ctor_param_list = [[$for j, [[p$j##_type gmock_p$j]]]] $var impl_ctor_param_list = [[$for j, [[p$j##_type gmock_p$j]]]] -$var impl_inits = [[$if i==0 [[]] $else [[ : $for j, [[p$j(gmock_p$j)]]]]]] -$var inits = [[$if i==0 [[]] $else [[ : $for j, [[p$j(gmock_p$j)]]]]]] +$var impl_inits = [[$if i==0 [[]] $else [[ : $for j, [[p$j(::testing::internal::move(gmock_p$j))]]]]]] +$var inits = [[$if i==0 [[]] $else [[ : $for j, [[p$j(::testing::internal::move(gmock_p$j))]]]]]] $var params = [[$for j, [[p$j]]]] $var param_types = [[$if i==0 [[]] $else [[<$for j, [[p$j##_type]]>]]]] $var param_types_and_names = [[$for j, [[p$j##_type p$j]]]] $var param_field_decls = [[$for j [[ - p$j##_type p$j;\ + p$j##_type const p$j;\ ]]]] $var param_field_decls2 = [[$for j [[ - p$j##_type p$j;\ + p$j##_type const p$j;\ ]]]] #define $macro_name(name$for j [[, p$j]], description)\$template class $class_name {\ public:\ template <typename arg_type>\ - class gmock_Impl : public ::testing::MatcherInterface<arg_type> {\ + class gmock_Impl : public ::testing::MatcherInterface<\ + GTEST_REFERENCE_TO_CONST_(arg_type)> {\ public:\ [[$if i==1 [[explicit ]]]]gmock_Impl($impl_ctor_param_list)\ $impl_inits {}\ virtual bool MatchAndExplain(\ - arg_type arg, ::testing::MatchResultListener* result_listener) const;\ + GTEST_REFERENCE_TO_CONST_(arg_type) arg,\ + ::testing::MatchResultListener* result_listener) const;\ virtual void DescribeTo(::std::ostream* gmock_os) const {\ *gmock_os << FormatDescription(false);\ }\ @@ -637,16 +477,16 @@ $var param_field_decls2 = [[$for j *gmock_os << FormatDescription(true);\ }\$param_field_decls private:\ - ::testing::internal::string FormatDescription(bool negation) const {\ - const ::testing::internal::string gmock_description = (description);\ - if (!gmock_description.empty())\ + ::std::string FormatDescription(bool negation) const {\ + ::std::string gmock_description = (description);\ + if (!gmock_description.empty()) {\ return gmock_description;\ + }\ return ::testing::internal::FormatMatcherDescription(\ negation, #name, \ ::testing::internal::UniversalTersePrintTupleFieldsToStrings(\ - ::testing::tuple<$for j, [[p$j##_type]]>($for j, [[p$j]])));\ + ::std::tuple<$for j, [[p$j##_type]]>($for j, [[p$j]])));\ }\ - GTEST_DISALLOW_ASSIGN_(gmock_Impl);\ };\ template <typename arg_type>\ operator ::testing::Matcher<arg_type>() const {\ @@ -656,14 +496,13 @@ $var param_field_decls2 = [[$for j [[$if i==1 [[explicit ]]]]$class_name($ctor_param_list)$inits {\ }\$param_field_decls2 private:\ - GTEST_DISALLOW_ASSIGN_($class_name);\ };\$template inline $class_name$param_types name($param_types_and_names) {\ return $class_name$param_types($params);\ }\$template template <typename arg_type>\ bool $class_name$param_types::gmock_Impl<arg_type>::MatchAndExplain(\ - arg_type arg, \ + GTEST_REFERENCE_TO_CONST_(arg_type) arg,\ ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\ const ]] diff --git a/googlemock/include/gmock/gmock-generated-nice-strict.h b/googlemock/include/gmock/gmock-generated-nice-strict.h index 4095f4d..91ba1d9 100644 --- a/googlemock/include/gmock/gmock-generated-nice-strict.h +++ b/googlemock/include/gmock/gmock-generated-nice-strict.h @@ -30,8 +30,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // Implements class templates NiceMock, NaggyMock, and StrictMock. // @@ -51,10 +50,9 @@ // NiceMock<MockFoo>. // // NiceMock, NaggyMock, and StrictMock "inherit" the constructors of -// their respective base class, with up-to 10 arguments. Therefore -// you can write NiceMock<MockFoo>(5, "a") to construct a nice mock -// where MockFoo has a constructor that accepts (int, const char*), -// for example. +// their respective base class. Therefore you can write +// NiceMock<MockFoo>(5, "a") to construct a nice mock where MockFoo +// has a constructor that accepts (int, const char*), for example. // // A known limitation is that NiceMock<MockFoo>, NaggyMock<MockFoo>, // and StrictMock<MockFoo> only works for mock methods defined using @@ -63,10 +61,8 @@ // or "strict" modifier may not affect it, depending on the compiler. // In particular, nesting NiceMock, NaggyMock, and StrictMock is NOT // supported. -// -// Another known limitation is that the constructors of the base mock -// cannot have arguments passed by non-const reference, which are -// banned by the Google C++ style guide anyway. + +// GOOGLETEST_CM0002 DO NOT DELETE #ifndef GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_NICE_STRICT_H_ #define GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_NICE_STRICT_H_ @@ -79,15 +75,35 @@ namespace testing { template <class MockClass> class NiceMock : public MockClass { public: - // We don't factor out the constructor body to a common method, as - // we have to avoid a possible clash with members of MockClass. - NiceMock() { + NiceMock() : MockClass() { + ::testing::Mock::AllowUninterestingCalls( + internal::ImplicitCast_<MockClass*>(this)); + } + +#if GTEST_LANG_CXX11 + // Ideally, we would inherit base class's constructors through a using + // declaration, which would preserve their visibility. However, many existing + // tests rely on the fact that current implementation reexports protected + // constructors as public. These tests would need to be cleaned up first. + + // Single argument constructor is special-cased so that it can be + // made explicit. + template <typename A> + explicit NiceMock(A&& arg) : MockClass(std::forward<A>(arg)) { ::testing::Mock::AllowUninterestingCalls( internal::ImplicitCast_<MockClass*>(this)); } - // C++ doesn't (yet) allow inheritance of constructors, so we have - // to define it for each arity. + template <typename A1, typename A2, typename... An> + NiceMock(A1&& arg1, A2&& arg2, An&&... args) + : MockClass(std::forward<A1>(arg1), std::forward<A2>(arg2), + std::forward<An>(args)...) { + ::testing::Mock::AllowUninterestingCalls( + internal::ImplicitCast_<MockClass*>(this)); + } +#else + // C++98 doesn't have variadic templates, so we have to define one + // for each arity. template <typename A1> explicit NiceMock(const A1& a1) : MockClass(a1) { ::testing::Mock::AllowUninterestingCalls( @@ -163,7 +179,9 @@ class NiceMock : public MockClass { internal::ImplicitCast_<MockClass*>(this)); } - virtual ~NiceMock() { +#endif // GTEST_LANG_CXX11 + + ~NiceMock() { ::testing::Mock::UnregisterCallReaction( internal::ImplicitCast_<MockClass*>(this)); } @@ -175,15 +193,35 @@ class NiceMock : public MockClass { template <class MockClass> class NaggyMock : public MockClass { public: - // We don't factor out the constructor body to a common method, as - // we have to avoid a possible clash with members of MockClass. - NaggyMock() { + NaggyMock() : MockClass() { ::testing::Mock::WarnUninterestingCalls( internal::ImplicitCast_<MockClass*>(this)); } - // C++ doesn't (yet) allow inheritance of constructors, so we have - // to define it for each arity. +#if GTEST_LANG_CXX11 + // Ideally, we would inherit base class's constructors through a using + // declaration, which would preserve their visibility. However, many existing + // tests rely on the fact that current implementation reexports protected + // constructors as public. These tests would need to be cleaned up first. + + // Single argument constructor is special-cased so that it can be + // made explicit. + template <typename A> + explicit NaggyMock(A&& arg) : MockClass(std::forward<A>(arg)) { + ::testing::Mock::WarnUninterestingCalls( + internal::ImplicitCast_<MockClass*>(this)); + } + + template <typename A1, typename A2, typename... An> + NaggyMock(A1&& arg1, A2&& arg2, An&&... args) + : MockClass(std::forward<A1>(arg1), std::forward<A2>(arg2), + std::forward<An>(args)...) { + ::testing::Mock::WarnUninterestingCalls( + internal::ImplicitCast_<MockClass*>(this)); + } +#else + // C++98 doesn't have variadic templates, so we have to define one + // for each arity. template <typename A1> explicit NaggyMock(const A1& a1) : MockClass(a1) { ::testing::Mock::WarnUninterestingCalls( @@ -259,7 +297,9 @@ class NaggyMock : public MockClass { internal::ImplicitCast_<MockClass*>(this)); } - virtual ~NaggyMock() { +#endif // GTEST_LANG_CXX11 + + ~NaggyMock() { ::testing::Mock::UnregisterCallReaction( internal::ImplicitCast_<MockClass*>(this)); } @@ -271,15 +311,35 @@ class NaggyMock : public MockClass { template <class MockClass> class StrictMock : public MockClass { public: - // We don't factor out the constructor body to a common method, as - // we have to avoid a possible clash with members of MockClass. - StrictMock() { + StrictMock() : MockClass() { ::testing::Mock::FailUninterestingCalls( internal::ImplicitCast_<MockClass*>(this)); } - // C++ doesn't (yet) allow inheritance of constructors, so we have - // to define it for each arity. +#if GTEST_LANG_CXX11 + // Ideally, we would inherit base class's constructors through a using + // declaration, which would preserve their visibility. However, many existing + // tests rely on the fact that current implementation reexports protected + // constructors as public. These tests would need to be cleaned up first. + + // Single argument constructor is special-cased so that it can be + // made explicit. + template <typename A> + explicit StrictMock(A&& arg) : MockClass(std::forward<A>(arg)) { + ::testing::Mock::FailUninterestingCalls( + internal::ImplicitCast_<MockClass*>(this)); + } + + template <typename A1, typename A2, typename... An> + StrictMock(A1&& arg1, A2&& arg2, An&&... args) + : MockClass(std::forward<A1>(arg1), std::forward<A2>(arg2), + std::forward<An>(args)...) { + ::testing::Mock::FailUninterestingCalls( + internal::ImplicitCast_<MockClass*>(this)); + } +#else + // C++98 doesn't have variadic templates, so we have to define one + // for each arity. template <typename A1> explicit StrictMock(const A1& a1) : MockClass(a1) { ::testing::Mock::FailUninterestingCalls( @@ -355,7 +415,9 @@ class StrictMock : public MockClass { internal::ImplicitCast_<MockClass*>(this)); } - virtual ~StrictMock() { +#endif // GTEST_LANG_CXX11 + + ~StrictMock() { ::testing::Mock::UnregisterCallReaction( internal::ImplicitCast_<MockClass*>(this)); } diff --git a/googlemock/include/gmock/gmock-generated-nice-strict.h.pump b/googlemock/include/gmock/gmock-generated-nice-strict.h.pump index 3ee1ce7..ed49f4a 100644 --- a/googlemock/include/gmock/gmock-generated-nice-strict.h.pump +++ b/googlemock/include/gmock/gmock-generated-nice-strict.h.pump @@ -1,6 +1,6 @@ $$ -*- mode: c++; -*- -$$ This is a Pump source file. Please use Pump to convert it to -$$ gmock-generated-nice-strict.h. +$$ This is a Pump source file. Please use Pump to convert +$$ it to gmock-generated-nice-strict.h. $$ $var n = 10 $$ The maximum arity we support. // Copyright 2008, Google Inc. @@ -31,8 +31,7 @@ $var n = 10 $$ The maximum arity we support. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // Implements class templates NiceMock, NaggyMock, and StrictMock. // @@ -52,10 +51,9 @@ $var n = 10 $$ The maximum arity we support. // NiceMock<MockFoo>. // // NiceMock, NaggyMock, and StrictMock "inherit" the constructors of -// their respective base class, with up-to $n arguments. Therefore -// you can write NiceMock<MockFoo>(5, "a") to construct a nice mock -// where MockFoo has a constructor that accepts (int, const char*), -// for example. +// their respective base class. Therefore you can write +// NiceMock<MockFoo>(5, "a") to construct a nice mock where MockFoo +// has a constructor that accepts (int, const char*), for example. // // A known limitation is that NiceMock<MockFoo>, NaggyMock<MockFoo>, // and StrictMock<MockFoo> only works for mock methods defined using @@ -64,10 +62,8 @@ $var n = 10 $$ The maximum arity we support. // or "strict" modifier may not affect it, depending on the compiler. // In particular, nesting NiceMock, NaggyMock, and StrictMock is NOT // supported. -// -// Another known limitation is that the constructors of the base mock -// cannot have arguments passed by non-const reference, which are -// banned by the Google C++ style guide anyway. + +// GOOGLETEST_CM0002 DO NOT DELETE #ifndef GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_NICE_STRICT_H_ #define GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_NICE_STRICT_H_ @@ -91,15 +87,35 @@ $var method=[[$if kind==0 [[AllowUninterestingCalls]] template <class MockClass> class $clazz : public MockClass { public: - // We don't factor out the constructor body to a common method, as - // we have to avoid a possible clash with members of MockClass. - $clazz() { + $clazz() : MockClass() { ::testing::Mock::$method( internal::ImplicitCast_<MockClass*>(this)); } - // C++ doesn't (yet) allow inheritance of constructors, so we have - // to define it for each arity. +#if GTEST_LANG_CXX11 + // Ideally, we would inherit base class's constructors through a using + // declaration, which would preserve their visibility. However, many existing + // tests rely on the fact that current implementation reexports protected + // constructors as public. These tests would need to be cleaned up first. + + // Single argument constructor is special-cased so that it can be + // made explicit. + template <typename A> + explicit $clazz(A&& arg) : MockClass(std::forward<A>(arg)) { + ::testing::Mock::$method( + internal::ImplicitCast_<MockClass*>(this)); + } + + template <typename A1, typename A2, typename... An> + $clazz(A1&& arg1, A2&& arg2, An&&... args) + : MockClass(std::forward<A1>(arg1), std::forward<A2>(arg2), + std::forward<An>(args)...) { + ::testing::Mock::$method( + internal::ImplicitCast_<MockClass*>(this)); + } +#else + // C++98 doesn't have variadic templates, so we have to define one + // for each arity. template <typename A1> explicit $clazz(const A1& a1) : MockClass(a1) { ::testing::Mock::$method( @@ -117,7 +133,9 @@ $range j 1..i ]] - virtual ~$clazz() { +#endif // GTEST_LANG_CXX11 + + ~$clazz() { ::testing::Mock::UnregisterCallReaction( internal::ImplicitCast_<MockClass*>(this)); } diff --git a/googlemock/include/gmock/gmock-matchers.h b/googlemock/include/gmock/gmock-matchers.h index 33b37a7..cdb7367 100644 --- a/googlemock/include/gmock/gmock-matchers.h +++ b/googlemock/include/gmock/gmock-matchers.h @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // Google Mock - a framework for writing C++ mock classes. // @@ -35,6 +34,8 @@ // matchers can be defined by the user implementing the // MatcherInterface<T> interface if necessary. +// GOOGLETEST_CM0002 DO NOT DELETE + #ifndef GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_ #define GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_ @@ -47,15 +48,19 @@ #include <string> #include <utility> #include <vector> - +#include "gtest/gtest.h" #include "gmock/internal/gmock-internal-utils.h" #include "gmock/internal/gmock-port.h" -#include "gtest/gtest.h" #if GTEST_HAS_STD_INITIALIZER_LIST_ # include <initializer_list> // NOLINT -- must be after gtest.h #endif +GTEST_DISABLE_MSC_WARNINGS_PUSH_( + 4251 5046 /* class A needs to have dll-interface to be used by clients of + class B */ + /* Symbol involving type with internal linkage not defined */) + namespace testing { // To implement a matcher Foo for type T, define: @@ -73,7 +78,7 @@ namespace testing { // MatchResultListener is an abstract class. Its << operator can be // used by a matcher to explain why a value matches or doesn't match. // -// TODO(wan@google.com): add method +// FIXME: add method // bool InterestedInWhy(bool result) const; // to indicate whether the listener is interested in why the match // result is 'result'. @@ -89,8 +94,7 @@ class MatchResultListener { // is NULL. template <typename T> MatchResultListener& operator<<(const T& x) { - if (stream_ != NULL) - *stream_ << x; + if (stream_ != nullptr) *stream_ << x; return *this; } @@ -101,7 +105,7 @@ class MatchResultListener { // the match result. A matcher's MatchAndExplain() method can use // this information to avoid generating the explanation when no one // intends to hear it. - bool IsInterested() const { return stream_ != NULL; } + bool IsInterested() const { return stream_ != nullptr; } private: ::std::ostream* const stream_; @@ -180,13 +184,42 @@ class MatcherInterface : public MatcherDescriberInterface { // virtual void DescribeNegationTo(::std::ostream* os) const; }; +namespace internal { + +// Converts a MatcherInterface<T> to a MatcherInterface<const T&>. +template <typename T> +class MatcherInterfaceAdapter : public MatcherInterface<const T&> { + public: + explicit MatcherInterfaceAdapter(const MatcherInterface<T>* impl) + : impl_(impl) {} + virtual ~MatcherInterfaceAdapter() { delete impl_; } + + virtual void DescribeTo(::std::ostream* os) const { impl_->DescribeTo(os); } + + virtual void DescribeNegationTo(::std::ostream* os) const { + impl_->DescribeNegationTo(os); + } + + virtual bool MatchAndExplain(const T& x, + MatchResultListener* listener) const { + return impl_->MatchAndExplain(x, listener); + } + + private: + const MatcherInterface<T>* const impl_; + + GTEST_DISALLOW_COPY_AND_ASSIGN_(MatcherInterfaceAdapter); +}; + +} // namespace internal + // A match result listener that stores the explanation in a string. class StringMatchResultListener : public MatchResultListener { public: StringMatchResultListener() : MatchResultListener(&ss_) {} // Returns the explanation accumulated so far. - internal::string str() const { return ss_.str(); } + std::string str() const { return ss_.str(); } // Clears the explanation accumulated so far. void Clear() { ss_.str(""); } @@ -227,7 +260,7 @@ struct AnyGe { // A match result listener that ignores the explanation. class DummyMatchResultListener : public MatchResultListener { public: - DummyMatchResultListener() : MatchResultListener(NULL) {} + DummyMatchResultListener() : MatchResultListener(nullptr) {} private: GTEST_DISALLOW_COPY_AND_ASSIGN_(DummyMatchResultListener); @@ -253,12 +286,13 @@ class MatcherBase { public: // Returns true iff the matcher matches x; also explains the match // result to 'listener'. - bool MatchAndExplain(T x, MatchResultListener* listener) const { + bool MatchAndExplain(GTEST_REFERENCE_TO_CONST_(T) x, + MatchResultListener* listener) const { return impl_->MatchAndExplain(x, listener); } // Returns true iff this matcher matches x. - bool Matches(T x) const { + bool Matches(GTEST_REFERENCE_TO_CONST_(T) x) const { DummyMatchResultListener dummy; return MatchAndExplain(x, &dummy); } @@ -272,7 +306,8 @@ class MatcherBase { } // Explains why x matches, or doesn't match, the matcher. - void ExplainMatchResultTo(T x, ::std::ostream* os) const { + void ExplainMatchResultTo(GTEST_REFERENCE_TO_CONST_(T) x, + ::std::ostream* os) const { StreamMatchResultListener listener(os); MatchAndExplain(x, &listener); } @@ -288,9 +323,18 @@ class MatcherBase { MatcherBase() {} // Constructs a matcher from its implementation. - explicit MatcherBase(const MatcherInterface<T>* impl) + explicit MatcherBase( + const MatcherInterface<GTEST_REFERENCE_TO_CONST_(T)>* impl) : impl_(impl) {} + template <typename U> + explicit MatcherBase( + const MatcherInterface<U>* impl, + typename internal::EnableIf< + !internal::IsSame<U, GTEST_REFERENCE_TO_CONST_(U)>::value>::type* = + nullptr) + : impl_(new internal::MatcherInterfaceAdapter<U>(impl)) {} + virtual ~MatcherBase() {} private: @@ -305,7 +349,9 @@ class MatcherBase { // // If performance becomes a problem, we should see if using // shared_ptr helps. - ::testing::internal::linked_ptr<const MatcherInterface<T> > impl_; + ::testing::internal::linked_ptr< + const MatcherInterface<GTEST_REFERENCE_TO_CONST_(T)> > + impl_; }; } // namespace internal @@ -324,7 +370,15 @@ class Matcher : public internal::MatcherBase<T> { explicit Matcher() {} // NOLINT // Constructs a matcher from its implementation. - explicit Matcher(const MatcherInterface<T>* impl) + explicit Matcher(const MatcherInterface<GTEST_REFERENCE_TO_CONST_(T)>* impl) + : internal::MatcherBase<T>(impl) {} + + template <typename U> + explicit Matcher( + const MatcherInterface<U>* impl, + typename internal::EnableIf< + !internal::IsSame<U, GTEST_REFERENCE_TO_CONST_(U)>::value>::type* = + nullptr) : internal::MatcherBase<T>(impl) {} // Implicit constructor here allows people to write @@ -333,86 +387,170 @@ class Matcher : public internal::MatcherBase<T> { }; // The following two specializations allow the user to write str -// instead of Eq(str) and "foo" instead of Eq("foo") when a string +// instead of Eq(str) and "foo" instead of Eq("foo") when a std::string // matcher is expected. template <> -class GTEST_API_ Matcher<const internal::string&> - : public internal::MatcherBase<const internal::string&> { +class GTEST_API_ Matcher<const std::string&> + : public internal::MatcherBase<const std::string&> { public: Matcher() {} - explicit Matcher(const MatcherInterface<const internal::string&>* impl) - : internal::MatcherBase<const internal::string&>(impl) {} + explicit Matcher(const MatcherInterface<const std::string&>* impl) + : internal::MatcherBase<const std::string&>(impl) {} // Allows the user to write str instead of Eq(str) sometimes, where - // str is a string object. - Matcher(const internal::string& s); // NOLINT + // str is a std::string object. + Matcher(const std::string& s); // NOLINT + +#if GTEST_HAS_GLOBAL_STRING + // Allows the user to write str instead of Eq(str) sometimes, where + // str is a ::string object. + Matcher(const ::string& s); // NOLINT +#endif // GTEST_HAS_GLOBAL_STRING // Allows the user to write "foo" instead of Eq("foo") sometimes. Matcher(const char* s); // NOLINT }; template <> -class GTEST_API_ Matcher<internal::string> - : public internal::MatcherBase<internal::string> { +class GTEST_API_ Matcher<std::string> + : public internal::MatcherBase<std::string> { public: Matcher() {} - explicit Matcher(const MatcherInterface<internal::string>* impl) - : internal::MatcherBase<internal::string>(impl) {} + explicit Matcher(const MatcherInterface<const std::string&>* impl) + : internal::MatcherBase<std::string>(impl) {} + explicit Matcher(const MatcherInterface<std::string>* impl) + : internal::MatcherBase<std::string>(impl) {} // Allows the user to write str instead of Eq(str) sometimes, where // str is a string object. - Matcher(const internal::string& s); // NOLINT + Matcher(const std::string& s); // NOLINT + +#if GTEST_HAS_GLOBAL_STRING + // Allows the user to write str instead of Eq(str) sometimes, where + // str is a ::string object. + Matcher(const ::string& s); // NOLINT +#endif // GTEST_HAS_GLOBAL_STRING // Allows the user to write "foo" instead of Eq("foo") sometimes. Matcher(const char* s); // NOLINT }; -#if GTEST_HAS_STRING_PIECE_ +#if GTEST_HAS_GLOBAL_STRING // The following two specializations allow the user to write str -// instead of Eq(str) and "foo" instead of Eq("foo") when a StringPiece +// instead of Eq(str) and "foo" instead of Eq("foo") when a ::string // matcher is expected. template <> -class GTEST_API_ Matcher<const StringPiece&> - : public internal::MatcherBase<const StringPiece&> { +class GTEST_API_ Matcher<const ::string&> + : public internal::MatcherBase<const ::string&> { public: Matcher() {} - explicit Matcher(const MatcherInterface<const StringPiece&>* impl) - : internal::MatcherBase<const StringPiece&>(impl) {} + explicit Matcher(const MatcherInterface<const ::string&>* impl) + : internal::MatcherBase<const ::string&>(impl) {} // Allows the user to write str instead of Eq(str) sometimes, where - // str is a string object. - Matcher(const internal::string& s); // NOLINT + // str is a std::string object. + Matcher(const std::string& s); // NOLINT + + // Allows the user to write str instead of Eq(str) sometimes, where + // str is a ::string object. + Matcher(const ::string& s); // NOLINT // Allows the user to write "foo" instead of Eq("foo") sometimes. Matcher(const char* s); // NOLINT +}; + +template <> +class GTEST_API_ Matcher< ::string> + : public internal::MatcherBase< ::string> { + public: + Matcher() {} + + explicit Matcher(const MatcherInterface<const ::string&>* impl) + : internal::MatcherBase< ::string>(impl) {} + explicit Matcher(const MatcherInterface< ::string>* impl) + : internal::MatcherBase< ::string>(impl) {} + + // Allows the user to write str instead of Eq(str) sometimes, where + // str is a std::string object. + Matcher(const std::string& s); // NOLINT - // Allows the user to pass StringPieces directly. - Matcher(StringPiece s); // NOLINT + // Allows the user to write str instead of Eq(str) sometimes, where + // str is a ::string object. + Matcher(const ::string& s); // NOLINT + + // Allows the user to write "foo" instead of Eq("foo") sometimes. + Matcher(const char* s); // NOLINT }; +#endif // GTEST_HAS_GLOBAL_STRING +#if GTEST_HAS_ABSL +// The following two specializations allow the user to write str +// instead of Eq(str) and "foo" instead of Eq("foo") when a absl::string_view +// matcher is expected. template <> -class GTEST_API_ Matcher<StringPiece> - : public internal::MatcherBase<StringPiece> { +class GTEST_API_ Matcher<const absl::string_view&> + : public internal::MatcherBase<const absl::string_view&> { public: Matcher() {} - explicit Matcher(const MatcherInterface<StringPiece>* impl) - : internal::MatcherBase<StringPiece>(impl) {} + explicit Matcher(const MatcherInterface<const absl::string_view&>* impl) + : internal::MatcherBase<const absl::string_view&>(impl) {} // Allows the user to write str instead of Eq(str) sometimes, where - // str is a string object. - Matcher(const internal::string& s); // NOLINT + // str is a std::string object. + Matcher(const std::string& s); // NOLINT + +#if GTEST_HAS_GLOBAL_STRING + // Allows the user to write str instead of Eq(str) sometimes, where + // str is a ::string object. + Matcher(const ::string& s); // NOLINT +#endif // GTEST_HAS_GLOBAL_STRING // Allows the user to write "foo" instead of Eq("foo") sometimes. Matcher(const char* s); // NOLINT - // Allows the user to pass StringPieces directly. - Matcher(StringPiece s); // NOLINT + // Allows the user to pass absl::string_views directly. + Matcher(absl::string_view s); // NOLINT }; -#endif // GTEST_HAS_STRING_PIECE_ + +template <> +class GTEST_API_ Matcher<absl::string_view> + : public internal::MatcherBase<absl::string_view> { + public: + Matcher() {} + + explicit Matcher(const MatcherInterface<const absl::string_view&>* impl) + : internal::MatcherBase<absl::string_view>(impl) {} + explicit Matcher(const MatcherInterface<absl::string_view>* impl) + : internal::MatcherBase<absl::string_view>(impl) {} + + // Allows the user to write str instead of Eq(str) sometimes, where + // str is a std::string object. + Matcher(const std::string& s); // NOLINT + +#if GTEST_HAS_GLOBAL_STRING + // Allows the user to write str instead of Eq(str) sometimes, where + // str is a ::string object. + Matcher(const ::string& s); // NOLINT +#endif // GTEST_HAS_GLOBAL_STRING + + // Allows the user to write "foo" instead of Eq("foo") sometimes. + Matcher(const char* s); // NOLINT + + // Allows the user to pass absl::string_views directly. + Matcher(absl::string_view s); // NOLINT +}; +#endif // GTEST_HAS_ABSL + +// Prints a matcher in a human-readable format. +template <typename T> +std::ostream& operator<<(std::ostream& os, const Matcher<T>& matcher) { + matcher.DescribeTo(&os); + return os; +} // The PolymorphicMatcher class template makes it easy to implement a // polymorphic matcher (i.e. a matcher that can match values of more @@ -441,7 +579,7 @@ class PolymorphicMatcher { template <typename T> operator Matcher<T>() const { - return Matcher<T>(new MonomorphicImpl<T>(impl_)); + return Matcher<T>(new MonomorphicImpl<GTEST_REFERENCE_TO_CONST_(T)>(impl_)); } private: @@ -515,7 +653,7 @@ template <typename T, typename M> class MatcherCastImpl { public: static Matcher<T> Cast(const M& polymorphic_matcher_or_value) { - // M can be a polymorhic matcher, in which case we want to use + // M can be a polymorphic matcher, in which case we want to use // its conversion operator to create Matcher<T>. Or it can be a value // that should be passed to the Matcher<T>'s constructor. // @@ -531,21 +669,18 @@ class MatcherCastImpl { return CastImpl( polymorphic_matcher_or_value, BooleanConstant< - internal::ImplicitlyConvertible<M, Matcher<T> >::value>()); + internal::ImplicitlyConvertible<M, Matcher<T> >::value>(), + BooleanConstant< + internal::ImplicitlyConvertible<M, T>::value>()); } private: - static Matcher<T> CastImpl(const M& value, BooleanConstant<false>) { - // M can't be implicitly converted to Matcher<T>, so M isn't a polymorphic - // matcher. It must be a value then. Use direct initialization to create - // a matcher. - return Matcher<T>(ImplicitCast_<T>(value)); - } - + template <bool Ignore> static Matcher<T> CastImpl(const M& polymorphic_matcher_or_value, - BooleanConstant<true>) { + BooleanConstant<true> /* convertible_to_matcher */, + BooleanConstant<Ignore>) { // M is implicitly convertible to Matcher<T>, which means that either - // M is a polymorhpic matcher or Matcher<T> has an implicit constructor + // M is a polymorphic matcher or Matcher<T> has an implicit constructor // from M. In both cases using the implicit conversion will produce a // matcher. // @@ -554,6 +689,29 @@ class MatcherCastImpl { // (first to create T from M and then to create Matcher<T> from T). return polymorphic_matcher_or_value; } + + // M can't be implicitly converted to Matcher<T>, so M isn't a polymorphic + // matcher. It's a value of a type implicitly convertible to T. Use direct + // initialization to create a matcher. + static Matcher<T> CastImpl( + const M& value, BooleanConstant<false> /* convertible_to_matcher */, + BooleanConstant<true> /* convertible_to_T */) { + return Matcher<T>(ImplicitCast_<T>(value)); + } + + // M can't be implicitly converted to either Matcher<T> or T. Attempt to use + // polymorphic matcher Eq(value) in this case. + // + // Note that we first attempt to perform an implicit cast on the value and + // only fall back to the polymorphic Eq() matcher afterwards because the + // latter calls bool operator==(const Lhs& lhs, const Rhs& rhs) in the end + // which might be undefined even when Rhs is implicitly convertible to Lhs + // (e.g. std::pair<const int, int> vs. std::pair<int, int>). + // + // We don't define this method inline as we need the declaration of Eq(). + static Matcher<T> CastImpl( + const M& value, BooleanConstant<false> /* convertible_to_matcher */, + BooleanConstant<false> /* convertible_to_T */); }; // This more specialized version is used when MatcherCast()'s argument @@ -574,6 +732,22 @@ class MatcherCastImpl<T, Matcher<U> > { // We delegate the matching logic to the source matcher. virtual bool MatchAndExplain(T x, MatchResultListener* listener) const { +#if GTEST_LANG_CXX11 + using FromType = typename std::remove_cv<typename std::remove_pointer< + typename std::remove_reference<T>::type>::type>::type; + using ToType = typename std::remove_cv<typename std::remove_pointer< + typename std::remove_reference<U>::type>::type>::type; + // Do not allow implicitly converting base*/& to derived*/&. + static_assert( + // Do not trigger if only one of them is a pointer. That implies a + // regular conversion and not a down_cast. + (std::is_pointer<typename std::remove_reference<T>::type>::value != + std::is_pointer<typename std::remove_reference<U>::type>::value) || + std::is_same<FromType, ToType>::value || + !std::is_base_of<FromType, ToType>::value, + "Can't implicitly convert from <base> to <derived>"); +#endif // GTEST_LANG_CXX11 + return source_matcher_.MatchAndExplain(static_cast<U>(x), listener); } @@ -646,7 +820,7 @@ class SafeMatcherCastImpl { // type U. GTEST_COMPILE_ASSERT_( internal::is_reference<T>::value || !internal::is_reference<U>::value, - cannot_convert_non_referentce_arg_to_reference); + cannot_convert_non_reference_arg_to_reference); // In case both T and U are arithmetic types, enforce that the // conversion is not lossy. typedef GTEST_REMOVE_REFERENCE_AND_CONST_(T) RawT; @@ -675,9 +849,9 @@ Matcher<T> A(); namespace internal { // If the explanation is not empty, prints it to the ostream. -inline void PrintIfNotEmpty(const internal::string& explanation, +inline void PrintIfNotEmpty(const std::string& explanation, ::std::ostream* os) { - if (explanation != "" && os != NULL) { + if (explanation != "" && os != nullptr) { *os << ", " << explanation; } } @@ -685,11 +859,11 @@ inline void PrintIfNotEmpty(const internal::string& explanation, // Returns true if the given type name is easy to read by a human. // This is used to decide whether printing the type of a value might // be helpful. -inline bool IsReadableTypeName(const string& type_name) { +inline bool IsReadableTypeName(const std::string& type_name) { // We consider a type name readable if it's short or doesn't contain // a template or function type. return (type_name.length() <= 20 || - type_name.find_first_of("<(") == string::npos); + type_name.find_first_of("<(") == std::string::npos); } // Matches the value against the given matcher, prints the value and explains @@ -711,7 +885,7 @@ bool MatchPrintAndExplain(Value& value, const Matcher<T>& matcher, UniversalPrint(value, listener->stream()); #if GTEST_HAS_RTTI - const string& type_name = GetTypeName<Value>(); + const std::string& type_name = GetTypeName<Value>(); if (IsReadableTypeName(type_name)) *listener->stream() << " (of type " << type_name << ")"; #endif @@ -731,8 +905,8 @@ class TuplePrefix { template <typename MatcherTuple, typename ValueTuple> static bool Matches(const MatcherTuple& matcher_tuple, const ValueTuple& value_tuple) { - return TuplePrefix<N - 1>::Matches(matcher_tuple, value_tuple) - && get<N - 1>(matcher_tuple).Matches(get<N - 1>(value_tuple)); + return TuplePrefix<N - 1>::Matches(matcher_tuple, value_tuple) && + std::get<N - 1>(matcher_tuple).Matches(std::get<N - 1>(value_tuple)); } // TuplePrefix<N>::ExplainMatchFailuresTo(matchers, values, os) @@ -748,16 +922,16 @@ class TuplePrefix { // Then describes the failure (if any) in the (N - 1)-th (0-based) // field. - typename tuple_element<N - 1, MatcherTuple>::type matcher = - get<N - 1>(matchers); - typedef typename tuple_element<N - 1, ValueTuple>::type Value; - Value value = get<N - 1>(values); + typename std::tuple_element<N - 1, MatcherTuple>::type matcher = + std::get<N - 1>(matchers); + typedef typename std::tuple_element<N - 1, ValueTuple>::type Value; + GTEST_REFERENCE_TO_CONST_(Value) value = std::get<N - 1>(values); StringMatchResultListener listener; if (!matcher.MatchAndExplain(value, &listener)) { - // TODO(wan): include in the message the name of the parameter + // FIXME: include in the message the name of the parameter // as used in MOCK_METHOD*() when possible. *os << " Expected arg #" << N - 1 << ": "; - get<N - 1>(matchers).DescribeTo(os); + std::get<N - 1>(matchers).DescribeTo(os); *os << "\n Actual: "; // We remove the reference in type Value to prevent the // universal printer from printing the address of value, which @@ -797,11 +971,11 @@ bool TupleMatches(const MatcherTuple& matcher_tuple, const ValueTuple& value_tuple) { // Makes sure that matcher_tuple and value_tuple have the same // number of fields. - GTEST_COMPILE_ASSERT_(tuple_size<MatcherTuple>::value == - tuple_size<ValueTuple>::value, + GTEST_COMPILE_ASSERT_(std::tuple_size<MatcherTuple>::value == + std::tuple_size<ValueTuple>::value, matcher_and_value_have_different_numbers_of_fields); - return TuplePrefix<tuple_size<ValueTuple>::value>:: - Matches(matcher_tuple, value_tuple); + return TuplePrefix<std::tuple_size<ValueTuple>::value>::Matches(matcher_tuple, + value_tuple); } // Describes failures in matching matchers against values. If there @@ -810,7 +984,7 @@ template <typename MatcherTuple, typename ValueTuple> void ExplainMatchFailureTupleTo(const MatcherTuple& matchers, const ValueTuple& values, ::std::ostream* os) { - TuplePrefix<tuple_size<MatcherTuple>::value>::ExplainMatchFailuresTo( + TuplePrefix<std::tuple_size<MatcherTuple>::value>::ExplainMatchFailuresTo( matchers, values, os); } @@ -821,7 +995,7 @@ void ExplainMatchFailureTupleTo(const MatcherTuple& matchers, template <typename Tuple, typename Func, typename OutIter> class TransformTupleValuesHelper { private: - typedef ::testing::tuple_size<Tuple> TupleSize; + typedef ::std::tuple_size<Tuple> TupleSize; public: // For each member of tuple 't', taken in order, evaluates '*out++ = f(t)'. @@ -834,7 +1008,7 @@ class TransformTupleValuesHelper { template <typename Tup, size_t kRemainingSize> struct IterateOverTuple { OutIter operator() (Func f, const Tup& t, OutIter out) const { - *out++ = f(::testing::get<TupleSize::value - kRemainingSize>(t)); + *out++ = f(::std::get<TupleSize::value - kRemainingSize>(t)); return IterateOverTuple<Tup, kRemainingSize - 1>()(f, t, out); } }; @@ -856,10 +1030,12 @@ OutIter TransformTupleValues(Func f, const Tuple& t, OutIter out) { // Implements A<T>(). template <typename T> -class AnyMatcherImpl : public MatcherInterface<T> { +class AnyMatcherImpl : public MatcherInterface<GTEST_REFERENCE_TO_CONST_(T)> { public: - virtual bool MatchAndExplain( - T /* x */, MatchResultListener* /* listener */) const { return true; } + virtual bool MatchAndExplain(GTEST_REFERENCE_TO_CONST_(T) /* x */, + MatchResultListener* /* listener */) const { + return true; + } virtual void DescribeTo(::std::ostream* os) const { *os << "is anything"; } virtual void DescribeNegationTo(::std::ostream* os) const { // This is mostly for completeness' safe, as it's not very useful @@ -1129,6 +1305,16 @@ class StrEqualityMatcher { bool case_sensitive) : string_(str), expect_eq_(expect_eq), case_sensitive_(case_sensitive) {} +#if GTEST_HAS_ABSL + bool MatchAndExplain(const absl::string_view& s, + MatchResultListener* listener) const { + // This should fail to compile if absl::string_view is used with wide + // strings. + const StringType& str = string(s); + return MatchAndExplain(str, listener); + } +#endif // GTEST_HAS_ABSL + // Accepts pointer types, particularly: // const char* // char* @@ -1136,7 +1322,7 @@ class StrEqualityMatcher { // wchar_t* template <typename CharType> bool MatchAndExplain(CharType* s, MatchResultListener* listener) const { - if (s == NULL) { + if (s == nullptr) { return !expect_eq_; } return MatchAndExplain(StringType(s), listener); @@ -1145,7 +1331,7 @@ class StrEqualityMatcher { // Matches anything that can convert to StringType. // // This is a template, not just a plain function with const StringType&, - // because StringPiece has some interfering non-explicit constructors. + // because absl::string_view has some interfering non-explicit constructors. template <typename MatcheeStringType> bool MatchAndExplain(const MatcheeStringType& s, MatchResultListener* /* listener */) const { @@ -1189,6 +1375,16 @@ class HasSubstrMatcher { explicit HasSubstrMatcher(const StringType& substring) : substring_(substring) {} +#if GTEST_HAS_ABSL + bool MatchAndExplain(const absl::string_view& s, + MatchResultListener* listener) const { + // This should fail to compile if absl::string_view is used with wide + // strings. + const StringType& str = string(s); + return MatchAndExplain(str, listener); + } +#endif // GTEST_HAS_ABSL + // Accepts pointer types, particularly: // const char* // char* @@ -1196,13 +1392,13 @@ class HasSubstrMatcher { // wchar_t* template <typename CharType> bool MatchAndExplain(CharType* s, MatchResultListener* listener) const { - return s != NULL && MatchAndExplain(StringType(s), listener); + return s != nullptr && MatchAndExplain(StringType(s), listener); } // Matches anything that can convert to StringType. // // This is a template, not just a plain function with const StringType&, - // because StringPiece has some interfering non-explicit constructors. + // because absl::string_view has some interfering non-explicit constructors. template <typename MatcheeStringType> bool MatchAndExplain(const MatcheeStringType& s, MatchResultListener* /* listener */) const { @@ -1236,6 +1432,16 @@ class StartsWithMatcher { explicit StartsWithMatcher(const StringType& prefix) : prefix_(prefix) { } +#if GTEST_HAS_ABSL + bool MatchAndExplain(const absl::string_view& s, + MatchResultListener* listener) const { + // This should fail to compile if absl::string_view is used with wide + // strings. + const StringType& str = string(s); + return MatchAndExplain(str, listener); + } +#endif // GTEST_HAS_ABSL + // Accepts pointer types, particularly: // const char* // char* @@ -1243,13 +1449,13 @@ class StartsWithMatcher { // wchar_t* template <typename CharType> bool MatchAndExplain(CharType* s, MatchResultListener* listener) const { - return s != NULL && MatchAndExplain(StringType(s), listener); + return s != nullptr && MatchAndExplain(StringType(s), listener); } // Matches anything that can convert to StringType. // // This is a template, not just a plain function with const StringType&, - // because StringPiece has some interfering non-explicit constructors. + // because absl::string_view has some interfering non-explicit constructors. template <typename MatcheeStringType> bool MatchAndExplain(const MatcheeStringType& s, MatchResultListener* /* listener */) const { @@ -1282,6 +1488,16 @@ class EndsWithMatcher { public: explicit EndsWithMatcher(const StringType& suffix) : suffix_(suffix) {} +#if GTEST_HAS_ABSL + bool MatchAndExplain(const absl::string_view& s, + MatchResultListener* listener) const { + // This should fail to compile if absl::string_view is used with wide + // strings. + const StringType& str = string(s); + return MatchAndExplain(str, listener); + } +#endif // GTEST_HAS_ABSL + // Accepts pointer types, particularly: // const char* // char* @@ -1289,13 +1505,13 @@ class EndsWithMatcher { // wchar_t* template <typename CharType> bool MatchAndExplain(CharType* s, MatchResultListener* listener) const { - return s != NULL && MatchAndExplain(StringType(s), listener); + return s != nullptr && MatchAndExplain(StringType(s), listener); } // Matches anything that can convert to StringType. // // This is a template, not just a plain function with const StringType&, - // because StringPiece has some interfering non-explicit constructors. + // because absl::string_view has some interfering non-explicit constructors. template <typename MatcheeStringType> bool MatchAndExplain(const MatcheeStringType& s, MatchResultListener* /* listener */) const { @@ -1328,6 +1544,13 @@ class MatchesRegexMatcher { MatchesRegexMatcher(const RE* regex, bool full_match) : regex_(regex), full_match_(full_match) {} +#if GTEST_HAS_ABSL + bool MatchAndExplain(const absl::string_view& s, + MatchResultListener* listener) const { + return MatchAndExplain(string(s), listener); + } +#endif // GTEST_HAS_ABSL + // Accepts pointer types, particularly: // const char* // char* @@ -1335,17 +1558,17 @@ class MatchesRegexMatcher { // wchar_t* template <typename CharType> bool MatchAndExplain(CharType* s, MatchResultListener* listener) const { - return s != NULL && MatchAndExplain(internal::string(s), listener); + return s != nullptr && MatchAndExplain(std::string(s), listener); } - // Matches anything that can convert to internal::string. + // Matches anything that can convert to std::string. // - // This is a template, not just a plain function with const internal::string&, - // because StringPiece has some interfering non-explicit constructors. + // This is a template, not just a plain function with const std::string&, + // because absl::string_view has some interfering non-explicit constructors. template <class MatcheeStringType> bool MatchAndExplain(const MatcheeStringType& s, MatchResultListener* /* listener */) const { - const internal::string& s2(s); + const std::string& s2(s); return full_match_ ? RE::FullMatch(s2, *regex_) : RE::PartialMatch(s2, *regex_); } @@ -1353,13 +1576,13 @@ class MatchesRegexMatcher { void DescribeTo(::std::ostream* os) const { *os << (full_match_ ? "matches" : "contains") << " regular expression "; - UniversalPrinter<internal::string>::Print(regex_->pattern(), os); + UniversalPrinter<std::string>::Print(regex_->pattern(), os); } void DescribeNegationTo(::std::ostream* os) const { *os << "doesn't " << (full_match_ ? "match" : "contain") << " regular expression "; - UniversalPrinter<internal::string>::Print(regex_->pattern(), os); + UniversalPrinter<std::string>::Print(regex_->pattern(), os); } private: @@ -1374,19 +1597,19 @@ class MatchesRegexMatcher { // compared don't have to have the same type. // // The matcher defined here is polymorphic (for example, Eq() can be -// used to match a tuple<int, short>, a tuple<const long&, double>, +// used to match a std::tuple<int, short>, a std::tuple<const long&, double>, // etc). Therefore we use a template type conversion operator in the // implementation. template <typename D, typename Op> class PairMatchBase { public: template <typename T1, typename T2> - operator Matcher< ::testing::tuple<T1, T2> >() const { - return MakeMatcher(new Impl< ::testing::tuple<T1, T2> >); + operator Matcher<::std::tuple<T1, T2>>() const { + return MakeMatcher(new Impl<::std::tuple<T1, T2>>); } template <typename T1, typename T2> - operator Matcher<const ::testing::tuple<T1, T2>&>() const { - return MakeMatcher(new Impl<const ::testing::tuple<T1, T2>&>); + operator Matcher<const ::std::tuple<T1, T2>&>() const { + return MakeMatcher(new Impl<const ::std::tuple<T1, T2>&>); } private: @@ -1400,7 +1623,7 @@ class PairMatchBase { virtual bool MatchAndExplain( Tuple args, MatchResultListener* /* listener */) const { - return Op()(::testing::get<0>(args), ::testing::get<1>(args)); + return Op()(::std::get<0>(args), ::std::get<1>(args)); } virtual void DescribeTo(::std::ostream* os) const { *os << "are " << GetDesc; @@ -1441,12 +1664,13 @@ class Ge2Matcher : public PairMatchBase<Ge2Matcher, AnyGe> { // will prevent different instantiations of NotMatcher from sharing // the same NotMatcherImpl<T> class. template <typename T> -class NotMatcherImpl : public MatcherInterface<T> { +class NotMatcherImpl : public MatcherInterface<GTEST_REFERENCE_TO_CONST_(T)> { public: explicit NotMatcherImpl(const Matcher<T>& matcher) : matcher_(matcher) {} - virtual bool MatchAndExplain(T x, MatchResultListener* listener) const { + virtual bool MatchAndExplain(GTEST_REFERENCE_TO_CONST_(T) x, + MatchResultListener* listener) const { return !matcher_.MatchAndExplain(x, listener); } @@ -1489,115 +1713,63 @@ class NotMatcher { // that will prevent different instantiations of BothOfMatcher from // sharing the same BothOfMatcherImpl<T> class. template <typename T> -class BothOfMatcherImpl : public MatcherInterface<T> { +class AllOfMatcherImpl + : public MatcherInterface<GTEST_REFERENCE_TO_CONST_(T)> { public: - BothOfMatcherImpl(const Matcher<T>& matcher1, const Matcher<T>& matcher2) - : matcher1_(matcher1), matcher2_(matcher2) {} + explicit AllOfMatcherImpl(std::vector<Matcher<T> > matchers) + : matchers_(internal::move(matchers)) {} virtual void DescribeTo(::std::ostream* os) const { *os << "("; - matcher1_.DescribeTo(os); - *os << ") and ("; - matcher2_.DescribeTo(os); + for (size_t i = 0; i < matchers_.size(); ++i) { + if (i != 0) *os << ") and ("; + matchers_[i].DescribeTo(os); + } *os << ")"; } virtual void DescribeNegationTo(::std::ostream* os) const { *os << "("; - matcher1_.DescribeNegationTo(os); - *os << ") or ("; - matcher2_.DescribeNegationTo(os); + for (size_t i = 0; i < matchers_.size(); ++i) { + if (i != 0) *os << ") or ("; + matchers_[i].DescribeNegationTo(os); + } *os << ")"; } - virtual bool MatchAndExplain(T x, MatchResultListener* listener) const { + virtual bool MatchAndExplain(GTEST_REFERENCE_TO_CONST_(T) x, + MatchResultListener* listener) const { // If either matcher1_ or matcher2_ doesn't match x, we only need // to explain why one of them fails. - StringMatchResultListener listener1; - if (!matcher1_.MatchAndExplain(x, &listener1)) { - *listener << listener1.str(); - return false; - } + std::string all_match_result; - StringMatchResultListener listener2; - if (!matcher2_.MatchAndExplain(x, &listener2)) { - *listener << listener2.str(); - return false; + for (size_t i = 0; i < matchers_.size(); ++i) { + StringMatchResultListener slistener; + if (matchers_[i].MatchAndExplain(x, &slistener)) { + if (all_match_result.empty()) { + all_match_result = slistener.str(); + } else { + std::string result = slistener.str(); + if (!result.empty()) { + all_match_result += ", and "; + all_match_result += result; + } + } + } else { + *listener << slistener.str(); + return false; + } } // Otherwise we need to explain why *both* of them match. - const internal::string s1 = listener1.str(); - const internal::string s2 = listener2.str(); - - if (s1 == "") { - *listener << s2; - } else { - *listener << s1; - if (s2 != "") { - *listener << ", and " << s2; - } - } + *listener << all_match_result; return true; } private: - const Matcher<T> matcher1_; - const Matcher<T> matcher2_; - - GTEST_DISALLOW_ASSIGN_(BothOfMatcherImpl); -}; - -#if GTEST_LANG_CXX11 -// MatcherList provides mechanisms for storing a variable number of matchers in -// a list structure (ListType) and creating a combining matcher from such a -// list. -// The template is defined recursively using the following template paramters: -// * kSize is the length of the MatcherList. -// * Head is the type of the first matcher of the list. -// * Tail denotes the types of the remaining matchers of the list. -template <int kSize, typename Head, typename... Tail> -struct MatcherList { - typedef MatcherList<kSize - 1, Tail...> MatcherListTail; - typedef ::std::pair<Head, typename MatcherListTail::ListType> ListType; - - // BuildList stores variadic type values in a nested pair structure. - // Example: - // MatcherList<3, int, string, float>::BuildList(5, "foo", 2.0) will return - // the corresponding result of type pair<int, pair<string, float>>. - static ListType BuildList(const Head& matcher, const Tail&... tail) { - return ListType(matcher, MatcherListTail::BuildList(tail...)); - } - - // CreateMatcher<T> creates a Matcher<T> from a given list of matchers (built - // by BuildList()). CombiningMatcher<T> is used to combine the matchers of the - // list. CombiningMatcher<T> must implement MatcherInterface<T> and have a - // constructor taking two Matcher<T>s as input. - template <typename T, template <typename /* T */> class CombiningMatcher> - static Matcher<T> CreateMatcher(const ListType& matchers) { - return Matcher<T>(new CombiningMatcher<T>( - SafeMatcherCast<T>(matchers.first), - MatcherListTail::template CreateMatcher<T, CombiningMatcher>( - matchers.second))); - } -}; - -// The following defines the base case for the recursive definition of -// MatcherList. -template <typename Matcher1, typename Matcher2> -struct MatcherList<2, Matcher1, Matcher2> { - typedef ::std::pair<Matcher1, Matcher2> ListType; + const std::vector<Matcher<T> > matchers_; - static ListType BuildList(const Matcher1& matcher1, - const Matcher2& matcher2) { - return ::std::pair<Matcher1, Matcher2>(matcher1, matcher2); - } - - template <typename T, template <typename /* T */> class CombiningMatcher> - static Matcher<T> CreateMatcher(const ListType& matchers) { - return Matcher<T>(new CombiningMatcher<T>( - SafeMatcherCast<T>(matchers.first), - SafeMatcherCast<T>(matchers.second))); - } + GTEST_DISALLOW_ASSIGN_(AllOfMatcherImpl); }; // VariadicMatcher is used for the variadic implementation of @@ -1608,148 +1780,108 @@ template <template <typename T> class CombiningMatcher, typename... Args> class VariadicMatcher { public: VariadicMatcher(const Args&... matchers) // NOLINT - : matchers_(MatcherListType::BuildList(matchers...)) {} + : matchers_(matchers...) { + static_assert(sizeof...(Args) > 0, "Must have at least one matcher."); + } // This template type conversion operator allows an // VariadicMatcher<Matcher1, Matcher2...> object to match any type that // all of the provided matchers (Matcher1, Matcher2, ...) can match. template <typename T> operator Matcher<T>() const { - return MatcherListType::template CreateMatcher<T, CombiningMatcher>( - matchers_); + std::vector<Matcher<T> > values; + CreateVariadicMatcher<T>(&values, std::integral_constant<size_t, 0>()); + return Matcher<T>(new CombiningMatcher<T>(internal::move(values))); } private: - typedef MatcherList<sizeof...(Args), Args...> MatcherListType; + template <typename T, size_t I> + void CreateVariadicMatcher(std::vector<Matcher<T> >* values, + std::integral_constant<size_t, I>) const { + values->push_back(SafeMatcherCast<T>(std::get<I>(matchers_))); + CreateVariadicMatcher<T>(values, std::integral_constant<size_t, I + 1>()); + } - const typename MatcherListType::ListType matchers_; + template <typename T> + void CreateVariadicMatcher( + std::vector<Matcher<T> >*, + std::integral_constant<size_t, sizeof...(Args)>) const {} + + std::tuple<Args...> matchers_; GTEST_DISALLOW_ASSIGN_(VariadicMatcher); }; template <typename... Args> -using AllOfMatcher = VariadicMatcher<BothOfMatcherImpl, Args...>; - -#endif // GTEST_LANG_CXX11 - -// Used for implementing the AllOf(m_1, ..., m_n) matcher, which -// matches a value that matches all of the matchers m_1, ..., and m_n. -template <typename Matcher1, typename Matcher2> -class BothOfMatcher { - public: - BothOfMatcher(Matcher1 matcher1, Matcher2 matcher2) - : matcher1_(matcher1), matcher2_(matcher2) {} - - // This template type conversion operator allows a - // BothOfMatcher<Matcher1, Matcher2> object to match any type that - // both Matcher1 and Matcher2 can match. - template <typename T> - operator Matcher<T>() const { - return Matcher<T>(new BothOfMatcherImpl<T>(SafeMatcherCast<T>(matcher1_), - SafeMatcherCast<T>(matcher2_))); - } - - private: - Matcher1 matcher1_; - Matcher2 matcher2_; - - GTEST_DISALLOW_ASSIGN_(BothOfMatcher); -}; +using AllOfMatcher = VariadicMatcher<AllOfMatcherImpl, Args...>; // Implements the AnyOf(m1, m2) matcher for a particular argument type // T. We do not nest it inside the AnyOfMatcher class template, as // that will prevent different instantiations of AnyOfMatcher from // sharing the same EitherOfMatcherImpl<T> class. template <typename T> -class EitherOfMatcherImpl : public MatcherInterface<T> { +class AnyOfMatcherImpl + : public MatcherInterface<GTEST_REFERENCE_TO_CONST_(T)> { public: - EitherOfMatcherImpl(const Matcher<T>& matcher1, const Matcher<T>& matcher2) - : matcher1_(matcher1), matcher2_(matcher2) {} + explicit AnyOfMatcherImpl(std::vector<Matcher<T> > matchers) + : matchers_(internal::move(matchers)) {} virtual void DescribeTo(::std::ostream* os) const { *os << "("; - matcher1_.DescribeTo(os); - *os << ") or ("; - matcher2_.DescribeTo(os); + for (size_t i = 0; i < matchers_.size(); ++i) { + if (i != 0) *os << ") or ("; + matchers_[i].DescribeTo(os); + } *os << ")"; } virtual void DescribeNegationTo(::std::ostream* os) const { *os << "("; - matcher1_.DescribeNegationTo(os); - *os << ") and ("; - matcher2_.DescribeNegationTo(os); + for (size_t i = 0; i < matchers_.size(); ++i) { + if (i != 0) *os << ") and ("; + matchers_[i].DescribeNegationTo(os); + } *os << ")"; } - virtual bool MatchAndExplain(T x, MatchResultListener* listener) const { + virtual bool MatchAndExplain(GTEST_REFERENCE_TO_CONST_(T) x, + MatchResultListener* listener) const { + std::string no_match_result; + // If either matcher1_ or matcher2_ matches x, we just need to // explain why *one* of them matches. - StringMatchResultListener listener1; - if (matcher1_.MatchAndExplain(x, &listener1)) { - *listener << listener1.str(); - return true; - } - - StringMatchResultListener listener2; - if (matcher2_.MatchAndExplain(x, &listener2)) { - *listener << listener2.str(); - return true; + for (size_t i = 0; i < matchers_.size(); ++i) { + StringMatchResultListener slistener; + if (matchers_[i].MatchAndExplain(x, &slistener)) { + *listener << slistener.str(); + return true; + } else { + if (no_match_result.empty()) { + no_match_result = slistener.str(); + } else { + std::string result = slistener.str(); + if (!result.empty()) { + no_match_result += ", and "; + no_match_result += result; + } + } + } } // Otherwise we need to explain why *both* of them fail. - const internal::string s1 = listener1.str(); - const internal::string s2 = listener2.str(); - - if (s1 == "") { - *listener << s2; - } else { - *listener << s1; - if (s2 != "") { - *listener << ", and " << s2; - } - } + *listener << no_match_result; return false; } private: - const Matcher<T> matcher1_; - const Matcher<T> matcher2_; + const std::vector<Matcher<T> > matchers_; - GTEST_DISALLOW_ASSIGN_(EitherOfMatcherImpl); + GTEST_DISALLOW_ASSIGN_(AnyOfMatcherImpl); }; -#if GTEST_LANG_CXX11 // AnyOfMatcher is used for the variadic implementation of AnyOf(m_1, m_2, ...). template <typename... Args> -using AnyOfMatcher = VariadicMatcher<EitherOfMatcherImpl, Args...>; - -#endif // GTEST_LANG_CXX11 - -// Used for implementing the AnyOf(m_1, ..., m_n) matcher, which -// matches a value that matches at least one of the matchers m_1, ..., -// and m_n. -template <typename Matcher1, typename Matcher2> -class EitherOfMatcher { - public: - EitherOfMatcher(Matcher1 matcher1, Matcher2 matcher2) - : matcher1_(matcher1), matcher2_(matcher2) {} - - // This template type conversion operator allows a - // EitherOfMatcher<Matcher1, Matcher2> object to match any type that - // both Matcher1 and Matcher2 can match. - template <typename T> - operator Matcher<T>() const { - return Matcher<T>(new EitherOfMatcherImpl<T>( - SafeMatcherCast<T>(matcher1_), SafeMatcherCast<T>(matcher2_))); - } - - private: - Matcher1 matcher1_; - Matcher2 matcher2_; - - GTEST_DISALLOW_ASSIGN_(EitherOfMatcher); -}; +using AnyOfMatcher = VariadicMatcher<AnyOfMatcherImpl, Args...>; // Used for implementing Truly(pred), which turns a predicate into a // matcher. @@ -2037,6 +2169,82 @@ class FloatingEqMatcher { GTEST_DISALLOW_ASSIGN_(FloatingEqMatcher); }; +// A 2-tuple ("binary") wrapper around FloatingEqMatcher: +// FloatingEq2Matcher() matches (x, y) by matching FloatingEqMatcher(x, false) +// against y, and FloatingEq2Matcher(e) matches FloatingEqMatcher(x, false, e) +// against y. The former implements "Eq", the latter "Near". At present, there +// is no version that compares NaNs as equal. +template <typename FloatType> +class FloatingEq2Matcher { + public: + FloatingEq2Matcher() { Init(-1, false); } + + explicit FloatingEq2Matcher(bool nan_eq_nan) { Init(-1, nan_eq_nan); } + + explicit FloatingEq2Matcher(FloatType max_abs_error) { + Init(max_abs_error, false); + } + + FloatingEq2Matcher(FloatType max_abs_error, bool nan_eq_nan) { + Init(max_abs_error, nan_eq_nan); + } + + template <typename T1, typename T2> + operator Matcher<::std::tuple<T1, T2>>() const { + return MakeMatcher( + new Impl<::std::tuple<T1, T2>>(max_abs_error_, nan_eq_nan_)); + } + template <typename T1, typename T2> + operator Matcher<const ::std::tuple<T1, T2>&>() const { + return MakeMatcher( + new Impl<const ::std::tuple<T1, T2>&>(max_abs_error_, nan_eq_nan_)); + } + + private: + static ::std::ostream& GetDesc(::std::ostream& os) { // NOLINT + return os << "an almost-equal pair"; + } + + template <typename Tuple> + class Impl : public MatcherInterface<Tuple> { + public: + Impl(FloatType max_abs_error, bool nan_eq_nan) : + max_abs_error_(max_abs_error), + nan_eq_nan_(nan_eq_nan) {} + + virtual bool MatchAndExplain(Tuple args, + MatchResultListener* listener) const { + if (max_abs_error_ == -1) { + FloatingEqMatcher<FloatType> fm(::std::get<0>(args), nan_eq_nan_); + return static_cast<Matcher<FloatType>>(fm).MatchAndExplain( + ::std::get<1>(args), listener); + } else { + FloatingEqMatcher<FloatType> fm(::std::get<0>(args), nan_eq_nan_, + max_abs_error_); + return static_cast<Matcher<FloatType>>(fm).MatchAndExplain( + ::std::get<1>(args), listener); + } + } + virtual void DescribeTo(::std::ostream* os) const { + *os << "are " << GetDesc; + } + virtual void DescribeNegationTo(::std::ostream* os) const { + *os << "aren't " << GetDesc; + } + + private: + FloatType max_abs_error_; + const bool nan_eq_nan_; + }; + + void Init(FloatType max_abs_error_val, bool nan_eq_nan_val) { + max_abs_error_ = max_abs_error_val; + nan_eq_nan_ = nan_eq_nan_val; + } + FloatType max_abs_error_; + bool nan_eq_nan_; +}; + // Implements the Pointee(m) matcher for matching a pointer whose // pointee matches matcher m. The pointer can be either raw or smart. template <typename InnerMatcher> @@ -2054,7 +2262,8 @@ class PointeeMatcher { // enough for implementing the DescribeTo() method of Pointee(). template <typename Pointer> operator Matcher<Pointer>() const { - return MakeMatcher(new Impl<Pointer>(matcher_)); + return Matcher<Pointer>( + new Impl<GTEST_REFERENCE_TO_CONST_(Pointer)>(matcher_)); } private: @@ -2080,8 +2289,7 @@ class PointeeMatcher { virtual bool MatchAndExplain(Pointer pointer, MatchResultListener* listener) const { - if (GetRawPointer(pointer) == NULL) - return false; + if (GetRawPointer(pointer) == nullptr) return false; *listener << "which points to "; return MatchPrintAndExplain(*pointer, matcher_, listener); @@ -2098,6 +2306,7 @@ class PointeeMatcher { GTEST_DISALLOW_ASSIGN_(PointeeMatcher); }; +#if GTEST_HAS_RTTI // Implements the WhenDynamicCastTo<T>(m) matcher that matches a pointer or // reference that matches inner_matcher when dynamic_cast<T> is applied. // The result of dynamic_cast<To> is forwarded to the inner matcher. @@ -2123,12 +2332,8 @@ class WhenDynamicCastToMatcherBase { protected: const Matcher<To> matcher_; - static string GetToName() { -#if GTEST_HAS_RTTI + static std::string GetToName() { return GetTypeName<To>(); -#else // GTEST_HAS_RTTI - return "the target type"; -#endif // GTEST_HAS_RTTI } private: @@ -2149,7 +2354,7 @@ class WhenDynamicCastToMatcher : public WhenDynamicCastToMatcherBase<To> { template <typename From> bool MatchAndExplain(From from, MatchResultListener* listener) const { - // TODO(sbenza): Add more detail on failures. ie did the dyn_cast fail? + // FIXME: Add more detail on failures. ie did the dyn_cast fail? To to = dynamic_cast<To>(from); return MatchPrintAndExplain(to, this->matcher_, listener); } @@ -2167,13 +2372,14 @@ class WhenDynamicCastToMatcher<To&> : public WhenDynamicCastToMatcherBase<To&> { bool MatchAndExplain(From& from, MatchResultListener* listener) const { // We don't want an std::bad_cast here, so do the cast with pointers. To* to = dynamic_cast<To*>(&from); - if (to == NULL) { + if (to == nullptr) { *listener << "which cannot be dynamic_cast to " << this->GetToName(); return false; } return MatchPrintAndExplain(*to, this->matcher_, listener); } }; +#endif // GTEST_HAS_RTTI // Implements the Field() matcher for matching a field (i.e. member // variable) of an object. @@ -2182,15 +2388,21 @@ class FieldMatcher { public: FieldMatcher(FieldType Class::*field, const Matcher<const FieldType&>& matcher) - : field_(field), matcher_(matcher) {} + : field_(field), matcher_(matcher), whose_field_("whose given field ") {} + + FieldMatcher(const std::string& field_name, FieldType Class::*field, + const Matcher<const FieldType&>& matcher) + : field_(field), + matcher_(matcher), + whose_field_("whose field `" + field_name + "` ") {} void DescribeTo(::std::ostream* os) const { - *os << "is an object whose given field "; + *os << "is an object " << whose_field_; matcher_.DescribeTo(os); } void DescribeNegationTo(::std::ostream* os) const { - *os << "is an object whose given field "; + *os << "is an object " << whose_field_; matcher_.DescribeNegationTo(os); } @@ -2208,14 +2420,13 @@ class FieldMatcher { // true_type iff the Field() matcher is used to match a pointer. bool MatchAndExplainImpl(false_type /* is_not_pointer */, const Class& obj, MatchResultListener* listener) const { - *listener << "whose given field is "; + *listener << whose_field_ << "is "; return MatchPrintAndExplain(obj.*field_, matcher_, listener); } bool MatchAndExplainImpl(true_type /* is_pointer */, const Class* p, MatchResultListener* listener) const { - if (p == NULL) - return false; + if (p == nullptr) return false; *listener << "which points to an object "; // Since *p has a field, it must be a class/struct/union type and @@ -2227,12 +2438,19 @@ class FieldMatcher { const FieldType Class::*field_; const Matcher<const FieldType&> matcher_; + // Contains either "whose given field " if the name of the field is unknown + // or "whose field `name_of_field` " if the name is known. + const std::string whose_field_; + GTEST_DISALLOW_ASSIGN_(FieldMatcher); }; // Implements the Property() matcher for matching a property // (i.e. return value of a getter method) of an object. -template <typename Class, typename PropertyType> +// +// Property is a const-qualified member function of Class returning +// PropertyType. +template <typename Class, typename PropertyType, typename Property> class PropertyMatcher { public: // The property may have a reference type, so 'const PropertyType&' @@ -2241,17 +2459,24 @@ class PropertyMatcher { // PropertyType being a reference or not. typedef GTEST_REFERENCE_TO_CONST_(PropertyType) RefToConstProperty; - PropertyMatcher(PropertyType (Class::*property)() const, + PropertyMatcher(Property property, const Matcher<RefToConstProperty>& matcher) + : property_(property), + matcher_(matcher), + whose_property_("whose given property ") {} + + PropertyMatcher(const std::string& property_name, Property property, const Matcher<RefToConstProperty>& matcher) - : property_(property), matcher_(matcher) {} + : property_(property), + matcher_(matcher), + whose_property_("whose property `" + property_name + "` ") {} void DescribeTo(::std::ostream* os) const { - *os << "is an object whose given property "; + *os << "is an object " << whose_property_; matcher_.DescribeTo(os); } void DescribeNegationTo(::std::ostream* os) const { - *os << "is an object whose given property "; + *os << "is an object " << whose_property_; matcher_.DescribeNegationTo(os); } @@ -2269,7 +2494,7 @@ class PropertyMatcher { // true_type iff the Property() matcher is used to match a pointer. bool MatchAndExplainImpl(false_type /* is_not_pointer */, const Class& obj, MatchResultListener* listener) const { - *listener << "whose given property is "; + *listener << whose_property_ << "is "; // Cannot pass the return value (for example, int) to MatchPrintAndExplain, // which takes a non-const reference as argument. #if defined(_PREFAST_ ) && _MSC_VER == 1800 @@ -2285,8 +2510,7 @@ class PropertyMatcher { bool MatchAndExplainImpl(true_type /* is_pointer */, const Class* p, MatchResultListener* listener) const { - if (p == NULL) - return false; + if (p == nullptr) return false; *listener << "which points to an object "; // Since *p has a property method, it must be a class/struct/union @@ -2295,24 +2519,32 @@ class PropertyMatcher { return MatchAndExplainImpl(false_type(), *p, listener); } - PropertyType (Class::*property_)() const; + Property property_; const Matcher<RefToConstProperty> matcher_; + // Contains either "whose given property " if the name of the property is + // unknown or "whose property `name_of_property` " if the name is known. + const std::string whose_property_; + GTEST_DISALLOW_ASSIGN_(PropertyMatcher); }; // Type traits specifying various features of different functors for ResultOf. // The default template specifies features for functor objects. -// Functor classes have to typedef argument_type and result_type -// to be compatible with ResultOf. template <typename Functor> struct CallableTraits { - typedef typename Functor::result_type ResultType; typedef Functor StorageType; static void CheckIsValid(Functor /* functor */) {} + +#if GTEST_LANG_CXX11 + template <typename T> + static auto Invoke(Functor f, T arg) -> decltype(f(arg)) { return f(arg); } +#else + typedef typename Functor::result_type ResultType; template <typename T> static ResultType Invoke(Functor f, T arg) { return f(arg); } +#endif }; // Specialization for function pointers. @@ -2322,7 +2554,7 @@ struct CallableTraits<ResType(*)(ArgType)> { typedef ResType(*StorageType)(ArgType); static void CheckIsValid(ResType(*f)(ArgType)) { - GTEST_CHECK_(f != NULL) + GTEST_CHECK_(f != nullptr) << "NULL function pointer is passed into ResultOf()."; } template <typename T> @@ -2333,13 +2565,11 @@ struct CallableTraits<ResType(*)(ArgType)> { // Implements the ResultOf() matcher for matching a return value of a // unary function of an object. -template <typename Callable> +template <typename Callable, typename InnerMatcher> class ResultOfMatcher { public: - typedef typename CallableTraits<Callable>::ResultType ResultType; - - ResultOfMatcher(Callable callable, const Matcher<ResultType>& matcher) - : callable_(callable), matcher_(matcher) { + ResultOfMatcher(Callable callable, InnerMatcher matcher) + : callable_(internal::move(callable)), matcher_(internal::move(matcher)) { CallableTraits<Callable>::CheckIsValid(callable_); } @@ -2353,9 +2583,17 @@ class ResultOfMatcher { template <typename T> class Impl : public MatcherInterface<T> { +#if GTEST_LANG_CXX11 + using ResultType = decltype(CallableTraits<Callable>::template Invoke<T>( + std::declval<CallableStorageType>(), std::declval<T>())); +#else + typedef typename CallableTraits<Callable>::ResultType ResultType; +#endif + public: - Impl(CallableStorageType callable, const Matcher<ResultType>& matcher) - : callable_(callable), matcher_(matcher) {} + template <typename M> + Impl(const CallableStorageType& callable, const M& matcher) + : callable_(callable), matcher_(MatcherCast<ResultType>(matcher)) {} virtual void DescribeTo(::std::ostream* os) const { *os << "is mapped by the given callable to a value that "; @@ -2369,8 +2607,10 @@ class ResultOfMatcher { virtual bool MatchAndExplain(T obj, MatchResultListener* listener) const { *listener << "which is mapped by the given callable to "; - // Cannot pass the return value (for example, int) to - // MatchPrintAndExplain, which takes a non-const reference as argument. + // Cannot pass the return value directly to MatchPrintAndExplain, which + // takes a non-const reference as argument. + // Also, specifying template argument explicitly is needed because T could + // be a non-const reference (e.g. Matcher<Uncopyable&>). ResultType result = CallableTraits<Callable>::template Invoke<T>(callable_, obj); return MatchPrintAndExplain(result, matcher_, listener); @@ -2378,9 +2618,9 @@ class ResultOfMatcher { private: // Functors often define operator() as non-const method even though - // they are actualy stateless. But we need to use them even when + // they are actually stateless. But we need to use them even when // 'this' is a const pointer. It's the user's responsibility not to - // use stateful callables with ResultOf(), which does't guarantee + // use stateful callables with ResultOf(), which doesn't guarantee // how many times the callable will be invoked. mutable CallableStorageType callable_; const Matcher<ResultType> matcher_; @@ -2389,7 +2629,7 @@ class ResultOfMatcher { }; // class Impl const CallableStorageType callable_; - const Matcher<ResultType> matcher_; + const InnerMatcher matcher_; GTEST_DISALLOW_ASSIGN_(ResultOfMatcher); }; @@ -2556,7 +2796,7 @@ class ContainerEqMatcher { return true; ::std::ostream* const os = listener->stream(); - if (os != NULL) { + if (os != nullptr) { // Something is different. Check for extra values first. bool printed_header = false; for (typename LhsStlContainer::const_iterator it = @@ -2686,11 +2926,15 @@ class WhenSortedByMatcher { }; // Implements Pointwise(tuple_matcher, rhs_container). tuple_matcher -// must be able to be safely cast to Matcher<tuple<const T1&, const +// must be able to be safely cast to Matcher<std::tuple<const T1&, const // T2&> >, where T1 and T2 are the types of elements in the LHS // container and the RHS container respectively. template <typename TupleMatcher, typename RhsContainer> class PointwiseMatcher { + GTEST_COMPILE_ASSERT_( + !IsHashTable<GTEST_REMOVE_REFERENCE_AND_CONST_(RhsContainer)>::value, + use_UnorderedPointwise_with_hash_tables); + public: typedef internal::StlContainerView<RhsContainer> RhsView; typedef typename RhsView::type RhsStlContainer; @@ -2708,6 +2952,10 @@ class PointwiseMatcher { template <typename LhsContainer> operator Matcher<LhsContainer>() const { + GTEST_COMPILE_ASSERT_( + !IsHashTable<GTEST_REMOVE_REFERENCE_AND_CONST_(LhsContainer)>::value, + use_UnorderedPointwise_with_hash_tables); + return MakeMatcher(new Impl<LhsContainer>(tuple_matcher_, rhs_)); } @@ -2723,7 +2971,7 @@ class PointwiseMatcher { // reference, as they may be expensive to copy. We must use tuple // instead of pair here, as a pair cannot hold references (C++ 98, // 20.2.2 [lib.pairs]). - typedef ::testing::tuple<const LhsValue&, const RhsValue&> InnerMatcherArg; + typedef ::std::tuple<const LhsValue&, const RhsValue&> InnerMatcherArg; Impl(const TupleMatcher& tuple_matcher, const RhsStlContainer& rhs) // mono_tuple_matcher_ holds a monomorphic version of the tuple matcher. @@ -2758,12 +3006,15 @@ class PointwiseMatcher { typename LhsStlContainer::const_iterator left = lhs_stl_container.begin(); typename RhsStlContainer::const_iterator right = rhs_.begin(); for (size_t i = 0; i != actual_size; ++i, ++left, ++right) { - const InnerMatcherArg value_pair(*left, *right); - if (listener->IsInterested()) { StringMatchResultListener inner_listener; + // Create InnerMatcherArg as a temporarily object to avoid it outlives + // *left and *right. Dereference or the conversion to `const T&` may + // return temp objects, e.g for vector<bool>. if (!mono_tuple_matcher_.MatchAndExplain( - value_pair, &inner_listener)) { + InnerMatcherArg(ImplicitCast_<const LhsValue&>(*left), + ImplicitCast_<const RhsValue&>(*right)), + &inner_listener)) { *listener << "where the value pair ("; UniversalPrint(*left, listener->stream()); *listener << ", "; @@ -2773,7 +3024,9 @@ class PointwiseMatcher { return false; } } else { - if (!mono_tuple_matcher_.Matches(value_pair)) + if (!mono_tuple_matcher_.Matches( + InnerMatcherArg(ImplicitCast_<const LhsValue&>(*left), + ImplicitCast_<const RhsValue&>(*right)))) return false; } } @@ -2931,6 +3184,50 @@ class EachMatcher { GTEST_DISALLOW_ASSIGN_(EachMatcher); }; +struct Rank1 {}; +struct Rank0 : Rank1 {}; + +namespace pair_getters { +#if GTEST_LANG_CXX11 +using std::get; +template <typename T> +auto First(T& x, Rank1) -> decltype(get<0>(x)) { // NOLINT + return get<0>(x); +} +template <typename T> +auto First(T& x, Rank0) -> decltype((x.first)) { // NOLINT + return x.first; +} + +template <typename T> +auto Second(T& x, Rank1) -> decltype(get<1>(x)) { // NOLINT + return get<1>(x); +} +template <typename T> +auto Second(T& x, Rank0) -> decltype((x.second)) { // NOLINT + return x.second; +} +#else +template <typename T> +typename T::first_type& First(T& x, Rank0) { // NOLINT + return x.first; +} +template <typename T> +const typename T::first_type& First(const T& x, Rank0) { + return x.first; +} + +template <typename T> +typename T::second_type& Second(T& x, Rank0) { // NOLINT + return x.second; +} +template <typename T> +const typename T::second_type& Second(const T& x, Rank0) { + return x.second; +} +#endif // GTEST_LANG_CXX11 +} // namespace pair_getters + // Implements Key(inner_matcher) for the given argument pair type. // Key(inner_matcher) matches an std::pair whose 'first' field matches // inner_matcher. For example, Contains(Key(Ge(5))) can be used to match an @@ -2951,9 +3248,9 @@ class KeyMatcherImpl : public MatcherInterface<PairType> { virtual bool MatchAndExplain(PairType key_value, MatchResultListener* listener) const { StringMatchResultListener inner_listener; - const bool match = inner_matcher_.MatchAndExplain(key_value.first, - &inner_listener); - const internal::string explanation = inner_listener.str(); + const bool match = inner_matcher_.MatchAndExplain( + pair_getters::First(key_value, Rank0()), &inner_listener); + const std::string explanation = inner_listener.str(); if (explanation != "") { *listener << "whose first field is a value " << explanation; } @@ -3035,18 +3332,18 @@ class PairMatcherImpl : public MatcherInterface<PairType> { if (!listener->IsInterested()) { // If the listener is not interested, we don't need to construct the // explanation. - return first_matcher_.Matches(a_pair.first) && - second_matcher_.Matches(a_pair.second); + return first_matcher_.Matches(pair_getters::First(a_pair, Rank0())) && + second_matcher_.Matches(pair_getters::Second(a_pair, Rank0())); } StringMatchResultListener first_inner_listener; - if (!first_matcher_.MatchAndExplain(a_pair.first, + if (!first_matcher_.MatchAndExplain(pair_getters::First(a_pair, Rank0()), &first_inner_listener)) { *listener << "whose first field does not match"; PrintIfNotEmpty(first_inner_listener.str(), listener->stream()); return false; } StringMatchResultListener second_inner_listener; - if (!second_matcher_.MatchAndExplain(a_pair.second, + if (!second_matcher_.MatchAndExplain(pair_getters::Second(a_pair, Rank0()), &second_inner_listener)) { *listener << "whose second field does not match"; PrintIfNotEmpty(second_inner_listener.str(), listener->stream()); @@ -3058,8 +3355,8 @@ class PairMatcherImpl : public MatcherInterface<PairType> { } private: - void ExplainSuccess(const internal::string& first_explanation, - const internal::string& second_explanation, + void ExplainSuccess(const std::string& first_explanation, + const std::string& second_explanation, MatchResultListener* listener) const { *listener << "whose both fields match"; if (first_explanation != "") { @@ -3166,7 +3463,7 @@ class ElementsAreMatcherImpl : public MatcherInterface<Container> { const bool listener_interested = listener->IsInterested(); // explanations[i] is the explanation of the element at index i. - ::std::vector<internal::string> explanations(count()); + ::std::vector<std::string> explanations(count()); StlContainerReference stl_container = View::ConstReference(container); typename StlContainer::const_iterator it = stl_container.begin(); size_t exam_pos = 0; @@ -3225,7 +3522,7 @@ class ElementsAreMatcherImpl : public MatcherInterface<Container> { if (listener_interested) { bool reason_printed = false; for (size_t i = 0; i != count(); ++i) { - const internal::string& s = explanations[i]; + const std::string& s = explanations[i]; if (!s.empty()) { if (reason_printed) { *listener << ",\nand "; @@ -3278,7 +3575,7 @@ class GTEST_API_ MatchMatrix { void Randomize(); - string DebugString() const; + std::string DebugString() const; private: size_t SpaceIndex(size_t ilhs, size_t irhs) const { @@ -3302,14 +3599,23 @@ typedef ::std::vector<ElementMatcherPair> ElementMatcherPairs; GTEST_API_ ElementMatcherPairs FindMaxBipartiteMatching(const MatchMatrix& g); -GTEST_API_ bool FindPairing(const MatchMatrix& matrix, - MatchResultListener* listener); +struct UnorderedMatcherRequire { + enum Flags { + Superset = 1 << 0, + Subset = 1 << 1, + ExactMatch = Superset | Subset, + }; +}; // Untyped base class for implementing UnorderedElementsAre. By // putting logic that's not specific to the element type here, we // reduce binary bloat and increase compilation speed. class GTEST_API_ UnorderedElementsAreMatcherImplBase { protected: + explicit UnorderedElementsAreMatcherImplBase( + UnorderedMatcherRequire::Flags matcher_flags) + : match_flags_(matcher_flags) {} + // A vector of matcher describers, one for each element matcher. // Does not own the describers (and thus can be used only when the // element matchers are alive). @@ -3321,10 +3627,12 @@ class GTEST_API_ UnorderedElementsAreMatcherImplBase { // Describes the negation of this UnorderedElementsAre matcher. void DescribeNegationToImpl(::std::ostream* os) const; - bool VerifyAllElementsAndMatchersAreMatched( - const ::std::vector<string>& element_printouts, - const MatchMatrix& matrix, - MatchResultListener* listener) const; + bool VerifyMatchMatrix(const ::std::vector<std::string>& element_printouts, + const MatchMatrix& matrix, + MatchResultListener* listener) const; + + bool FindPairing(const MatchMatrix& matrix, + MatchResultListener* listener) const; MatcherDescriberVec& matcher_describers() { return matcher_describers_; @@ -3334,13 +3642,17 @@ class GTEST_API_ UnorderedElementsAreMatcherImplBase { return Message() << n << " element" << (n == 1 ? "" : "s"); } + UnorderedMatcherRequire::Flags match_flags() const { return match_flags_; } + private: + UnorderedMatcherRequire::Flags match_flags_; MatcherDescriberVec matcher_describers_; GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreMatcherImplBase); }; -// Implements unordered ElementsAre and unordered ElementsAreArray. +// Implements UnorderedElementsAre, UnorderedElementsAreArray, IsSubsetOf, and +// IsSupersetOf. template <typename Container> class UnorderedElementsAreMatcherImpl : public MatcherInterface<Container>, @@ -3353,10 +3665,10 @@ class UnorderedElementsAreMatcherImpl typedef typename StlContainer::const_iterator StlContainerConstIterator; typedef typename StlContainer::value_type Element; - // Constructs the matcher from a sequence of element values or - // element matchers. template <typename InputIter> - UnorderedElementsAreMatcherImpl(InputIter first, InputIter last) { + UnorderedElementsAreMatcherImpl(UnorderedMatcherRequire::Flags matcher_flags, + InputIter first, InputIter last) + : UnorderedElementsAreMatcherImplBase(matcher_flags) { for (; first != last; ++first) { matchers_.push_back(MatcherCast<const Element&>(*first)); matcher_describers().push_back(matchers_.back().GetDescriber()); @@ -3376,38 +3688,36 @@ class UnorderedElementsAreMatcherImpl virtual bool MatchAndExplain(Container container, MatchResultListener* listener) const { StlContainerReference stl_container = View::ConstReference(container); - ::std::vector<string> element_printouts; - MatchMatrix matrix = AnalyzeElements(stl_container.begin(), - stl_container.end(), - &element_printouts, - listener); - - const size_t actual_count = matrix.LhsSize(); - if (actual_count == 0 && matchers_.empty()) { + ::std::vector<std::string> element_printouts; + MatchMatrix matrix = + AnalyzeElements(stl_container.begin(), stl_container.end(), + &element_printouts, listener); + + if (matrix.LhsSize() == 0 && matrix.RhsSize() == 0) { return true; } - if (actual_count != matchers_.size()) { - // The element count doesn't match. If the container is empty, - // there's no need to explain anything as Google Mock already - // prints the empty container. Otherwise we just need to show - // how many elements there actually are. - if (actual_count != 0 && listener->IsInterested()) { - *listener << "which has " << Elements(actual_count); + + if (match_flags() == UnorderedMatcherRequire::ExactMatch) { + if (matrix.LhsSize() != matrix.RhsSize()) { + // The element count doesn't match. If the container is empty, + // there's no need to explain anything as Google Mock already + // prints the empty container. Otherwise we just need to show + // how many elements there actually are. + if (matrix.LhsSize() != 0 && listener->IsInterested()) { + *listener << "which has " << Elements(matrix.LhsSize()); + } + return false; } - return false; } - return VerifyAllElementsAndMatchersAreMatched(element_printouts, - matrix, listener) && + return VerifyMatchMatrix(element_printouts, matrix, listener) && FindPairing(matrix, listener); } private: - typedef ::std::vector<Matcher<const Element&> > MatcherVec; - template <typename ElementIter> MatchMatrix AnalyzeElements(ElementIter elem_first, ElementIter elem_last, - ::std::vector<string>* element_printouts, + ::std::vector<std::string>* element_printouts, MatchResultListener* listener) const { element_printouts->clear(); ::std::vector<char> did_match; @@ -3431,7 +3741,7 @@ class UnorderedElementsAreMatcherImpl return matrix; } - MatcherVec matchers_; + ::std::vector<Matcher<const Element&> > matchers_; GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreMatcherImpl); }; @@ -3460,11 +3770,11 @@ class UnorderedElementsAreMatcher { typedef typename View::value_type Element; typedef ::std::vector<Matcher<const Element&> > MatcherVec; MatcherVec matchers; - matchers.reserve(::testing::tuple_size<MatcherTuple>::value); + matchers.reserve(::std::tuple_size<MatcherTuple>::value); TransformTupleValues(CastAndAppendTransform<const Element&>(), matchers_, ::std::back_inserter(matchers)); return MakeMatcher(new UnorderedElementsAreMatcherImpl<Container>( - matchers.begin(), matchers.end())); + UnorderedMatcherRequire::ExactMatch, matchers.begin(), matchers.end())); } private: @@ -3480,12 +3790,17 @@ class ElementsAreMatcher { template <typename Container> operator Matcher<Container>() const { + GTEST_COMPILE_ASSERT_( + !IsHashTable<GTEST_REMOVE_REFERENCE_AND_CONST_(Container)>::value || + ::std::tuple_size<MatcherTuple>::value < 2, + use_UnorderedElementsAre_with_hash_tables); + typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer; typedef typename internal::StlContainerView<RawContainer>::type View; typedef typename View::value_type Element; typedef ::std::vector<Matcher<const Element&> > MatcherVec; MatcherVec matchers; - matchers.reserve(::testing::tuple_size<MatcherTuple>::value); + matchers.reserve(::std::tuple_size<MatcherTuple>::value); TransformTupleValues(CastAndAppendTransform<const Element&>(), matchers_, ::std::back_inserter(matchers)); return MakeMatcher(new ElementsAreMatcherImpl<Container>( @@ -3497,24 +3812,23 @@ class ElementsAreMatcher { GTEST_DISALLOW_ASSIGN_(ElementsAreMatcher); }; -// Implements UnorderedElementsAreArray(). +// Implements UnorderedElementsAreArray(), IsSubsetOf(), and IsSupersetOf(). template <typename T> class UnorderedElementsAreArrayMatcher { public: - UnorderedElementsAreArrayMatcher() {} - template <typename Iter> - UnorderedElementsAreArrayMatcher(Iter first, Iter last) - : matchers_(first, last) {} + UnorderedElementsAreArrayMatcher(UnorderedMatcherRequire::Flags match_flags, + Iter first, Iter last) + : match_flags_(match_flags), matchers_(first, last) {} template <typename Container> operator Matcher<Container>() const { - return MakeMatcher( - new UnorderedElementsAreMatcherImpl<Container>(matchers_.begin(), - matchers_.end())); + return MakeMatcher(new UnorderedElementsAreMatcherImpl<Container>( + match_flags_, matchers_.begin(), matchers_.end())); } private: + UnorderedMatcherRequire::Flags match_flags_; ::std::vector<T> matchers_; GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreArrayMatcher); @@ -3529,6 +3843,10 @@ class ElementsAreArrayMatcher { template <typename Container> operator Matcher<Container>() const { + GTEST_COMPILE_ASSERT_( + !IsHashTable<GTEST_REMOVE_REFERENCE_AND_CONST_(Container)>::value, + use_UnorderedElementsAreArray_with_hash_tables); + return MakeMatcher(new ElementsAreMatcherImpl<Container>( matchers_.begin(), matchers_.end())); } @@ -3575,7 +3893,7 @@ class BoundSecondMatcher { template <typename T> class Impl : public MatcherInterface<T> { public: - typedef ::testing::tuple<T, Second> ArgTuple; + typedef ::std::tuple<T, Second> ArgTuple; Impl(const Tuple2Matcher& tm, const Second& second) : mono_tuple2_matcher_(SafeMatcherCast<const ArgTuple&>(tm)), @@ -3619,13 +3937,190 @@ BoundSecondMatcher<Tuple2Matcher, Second> MatcherBindSecond( // 'negation' is false; otherwise returns the description of the // negation of the matcher. 'param_values' contains a list of strings // that are the print-out of the matcher's parameters. -GTEST_API_ string FormatMatcherDescription(bool negation, - const char* matcher_name, - const Strings& param_values); +GTEST_API_ std::string FormatMatcherDescription(bool negation, + const char* matcher_name, + const Strings& param_values); + +// Implements a matcher that checks the value of a optional<> type variable. +template <typename ValueMatcher> +class OptionalMatcher { + public: + explicit OptionalMatcher(const ValueMatcher& value_matcher) + : value_matcher_(value_matcher) {} + template <typename Optional> + operator Matcher<Optional>() const { + return MakeMatcher(new Impl<Optional>(value_matcher_)); + } + + template <typename Optional> + class Impl : public MatcherInterface<Optional> { + public: + typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Optional) OptionalView; + typedef typename OptionalView::value_type ValueType; + explicit Impl(const ValueMatcher& value_matcher) + : value_matcher_(MatcherCast<ValueType>(value_matcher)) {} + + virtual void DescribeTo(::std::ostream* os) const { + *os << "value "; + value_matcher_.DescribeTo(os); + } + + virtual void DescribeNegationTo(::std::ostream* os) const { + *os << "value "; + value_matcher_.DescribeNegationTo(os); + } + + virtual bool MatchAndExplain(Optional optional, + MatchResultListener* listener) const { + if (!optional) { + *listener << "which is not engaged"; + return false; + } + const ValueType& value = *optional; + StringMatchResultListener value_listener; + const bool match = value_matcher_.MatchAndExplain(value, &value_listener); + *listener << "whose value " << PrintToString(value) + << (match ? " matches" : " doesn't match"); + PrintIfNotEmpty(value_listener.str(), listener->stream()); + return match; + } + + private: + const Matcher<ValueType> value_matcher_; + GTEST_DISALLOW_ASSIGN_(Impl); + }; + + private: + const ValueMatcher value_matcher_; + GTEST_DISALLOW_ASSIGN_(OptionalMatcher); +}; + +namespace variant_matcher { +// Overloads to allow VariantMatcher to do proper ADL lookup. +template <typename T> +void holds_alternative() {} +template <typename T> +void get() {} + +// Implements a matcher that checks the value of a variant<> type variable. +template <typename T> +class VariantMatcher { + public: + explicit VariantMatcher(::testing::Matcher<const T&> matcher) + : matcher_(internal::move(matcher)) {} + + template <typename Variant> + bool MatchAndExplain(const Variant& value, + ::testing::MatchResultListener* listener) const { + using std::get; + if (!listener->IsInterested()) { + return holds_alternative<T>(value) && matcher_.Matches(get<T>(value)); + } + + if (!holds_alternative<T>(value)) { + *listener << "whose value is not of type '" << GetTypeName() << "'"; + return false; + } + + const T& elem = get<T>(value); + StringMatchResultListener elem_listener; + const bool match = matcher_.MatchAndExplain(elem, &elem_listener); + *listener << "whose value " << PrintToString(elem) + << (match ? " matches" : " doesn't match"); + PrintIfNotEmpty(elem_listener.str(), listener->stream()); + return match; + } + + void DescribeTo(std::ostream* os) const { + *os << "is a variant<> with value of type '" << GetTypeName() + << "' and the value "; + matcher_.DescribeTo(os); + } + + void DescribeNegationTo(std::ostream* os) const { + *os << "is a variant<> with value of type other than '" << GetTypeName() + << "' or the value "; + matcher_.DescribeNegationTo(os); + } + + private: + static std::string GetTypeName() { +#if GTEST_HAS_RTTI + GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_( + return internal::GetTypeName<T>()); +#endif + return "the element type"; + } + + const ::testing::Matcher<const T&> matcher_; +}; + +} // namespace variant_matcher + +namespace any_cast_matcher { + +// Overloads to allow AnyCastMatcher to do proper ADL lookup. +template <typename T> +void any_cast() {} + +// Implements a matcher that any_casts the value. +template <typename T> +class AnyCastMatcher { + public: + explicit AnyCastMatcher(const ::testing::Matcher<const T&>& matcher) + : matcher_(matcher) {} + + template <typename AnyType> + bool MatchAndExplain(const AnyType& value, + ::testing::MatchResultListener* listener) const { + if (!listener->IsInterested()) { + const T* ptr = any_cast<T>(&value); + return ptr != nullptr && matcher_.Matches(*ptr); + } + + const T* elem = any_cast<T>(&value); + if (elem == nullptr) { + *listener << "whose value is not of type '" << GetTypeName() << "'"; + return false; + } + + StringMatchResultListener elem_listener; + const bool match = matcher_.MatchAndExplain(*elem, &elem_listener); + *listener << "whose value " << PrintToString(*elem) + << (match ? " matches" : " doesn't match"); + PrintIfNotEmpty(elem_listener.str(), listener->stream()); + return match; + } + + void DescribeTo(std::ostream* os) const { + *os << "is an 'any' type with value of type '" << GetTypeName() + << "' and the value "; + matcher_.DescribeTo(os); + } + + void DescribeNegationTo(std::ostream* os) const { + *os << "is an 'any' type with value of type other than '" << GetTypeName() + << "' or the value "; + matcher_.DescribeNegationTo(os); + } + + private: + static std::string GetTypeName() { +#if GTEST_HAS_RTTI + GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_( + return internal::GetTypeName<T>()); +#endif + return "the element type"; + } + + const ::testing::Matcher<const T&> matcher_; +}; + +} // namespace any_cast_matcher } // namespace internal -// ElementsAreArray(first, last) +// ElementsAreArray(iterator_first, iterator_last) // ElementsAreArray(pointer, count) // ElementsAreArray(array) // ElementsAreArray(container) @@ -3674,20 +4169,26 @@ ElementsAreArray(::std::initializer_list<T> xs) { } #endif -// UnorderedElementsAreArray(first, last) +// UnorderedElementsAreArray(iterator_first, iterator_last) // UnorderedElementsAreArray(pointer, count) // UnorderedElementsAreArray(array) // UnorderedElementsAreArray(container) // UnorderedElementsAreArray({ e1, e2, ..., en }) // -// The UnorderedElementsAreArray() functions are like -// ElementsAreArray(...), but allow matching the elements in any order. +// UnorderedElementsAreArray() verifies that a bijective mapping onto a +// collection of matchers exists. +// +// The matchers can be specified as an array, a pointer and count, a container, +// an initializer list, or an STL iterator range. In each of these cases, the +// underlying matchers can be either values or matchers. + template <typename Iter> inline internal::UnorderedElementsAreArrayMatcher< typename ::std::iterator_traits<Iter>::value_type> UnorderedElementsAreArray(Iter first, Iter last) { typedef typename ::std::iterator_traits<Iter>::value_type T; - return internal::UnorderedElementsAreArrayMatcher<T>(first, last); + return internal::UnorderedElementsAreArrayMatcher<T>( + internal::UnorderedMatcherRequire::ExactMatch, first, last); } template <typename T> @@ -3729,7 +4230,9 @@ UnorderedElementsAreArray(::std::initializer_list<T> xs) { const internal::AnythingMatcher _ = {}; // Creates a matcher that matches any value of the given type T. template <typename T> -inline Matcher<T> A() { return MakeMatcher(new internal::AnyMatcherImpl<T>()); } +inline Matcher<T> A() { + return Matcher<T>(new internal::AnyMatcherImpl<T>()); +} // Creates a matcher that matches any value of the given type T. template <typename T> @@ -3746,6 +4249,14 @@ inline internal::EqMatcher<T> Eq(T x) { return internal::EqMatcher<T>(x); } template <typename T> Matcher<T>::Matcher(T value) { *this = Eq(value); } +template <typename T, typename M> +Matcher<T> internal::MatcherCastImpl<T, M>::CastImpl( + const M& value, + internal::BooleanConstant<false> /* convertible_to_matcher */, + internal::BooleanConstant<false> /* convertible_to_T */) { + return Eq(value); +} + // Creates a monomorphic matcher that matches anything with type Lhs // and equal to rhs. A user may need to use this instead of Eq(...) // in order to resolve an overloading ambiguity. @@ -3874,6 +4385,7 @@ inline internal::PointeeMatcher<InnerMatcher> Pointee( return internal::PointeeMatcher<InnerMatcher>(inner_matcher); } +#if GTEST_HAS_RTTI // Creates a matcher that matches a pointer or reference that matches // inner_matcher when dynamic_cast<To> is applied. // The result of dynamic_cast<To> is forwarded to the inner matcher. @@ -3886,6 +4398,7 @@ WhenDynamicCastTo(const Matcher<To>& inner_matcher) { return MakePolymorphicMatcher( internal::WhenDynamicCastToMatcher<To>(inner_matcher)); } +#endif // GTEST_HAS_RTTI // Creates a matcher that matches an object whose given field matches // 'matcher'. For example, @@ -3904,16 +4417,28 @@ inline PolymorphicMatcher< // to compile where bar is an int32 and m is a matcher for int64. } +// Same as Field() but also takes the name of the field to provide better error +// messages. +template <typename Class, typename FieldType, typename FieldMatcher> +inline PolymorphicMatcher<internal::FieldMatcher<Class, FieldType> > Field( + const std::string& field_name, FieldType Class::*field, + const FieldMatcher& matcher) { + return MakePolymorphicMatcher(internal::FieldMatcher<Class, FieldType>( + field_name, field, MatcherCast<const FieldType&>(matcher))); +} + // Creates a matcher that matches an object whose given property // matches 'matcher'. For example, // Property(&Foo::str, StartsWith("hi")) // matches a Foo object x iff x.str() starts with "hi". template <typename Class, typename PropertyType, typename PropertyMatcher> -inline PolymorphicMatcher< - internal::PropertyMatcher<Class, PropertyType> > Property( - PropertyType (Class::*property)() const, const PropertyMatcher& matcher) { +inline PolymorphicMatcher<internal::PropertyMatcher< + Class, PropertyType, PropertyType (Class::*)() const> > +Property(PropertyType (Class::*property)() const, + const PropertyMatcher& matcher) { return MakePolymorphicMatcher( - internal::PropertyMatcher<Class, PropertyType>( + internal::PropertyMatcher<Class, PropertyType, + PropertyType (Class::*)() const>( property, MatcherCast<GTEST_REFERENCE_TO_CONST_(PropertyType)>(matcher))); // The call to MatcherCast() is required for supporting inner @@ -3922,82 +4447,115 @@ inline PolymorphicMatcher< // to compile where bar() returns an int32 and m is a matcher for int64. } +// Same as Property() above, but also takes the name of the property to provide +// better error messages. +template <typename Class, typename PropertyType, typename PropertyMatcher> +inline PolymorphicMatcher<internal::PropertyMatcher< + Class, PropertyType, PropertyType (Class::*)() const> > +Property(const std::string& property_name, + PropertyType (Class::*property)() const, + const PropertyMatcher& matcher) { + return MakePolymorphicMatcher( + internal::PropertyMatcher<Class, PropertyType, + PropertyType (Class::*)() const>( + property_name, property, + MatcherCast<GTEST_REFERENCE_TO_CONST_(PropertyType)>(matcher))); +} + +#if GTEST_LANG_CXX11 +// The same as above but for reference-qualified member functions. +template <typename Class, typename PropertyType, typename PropertyMatcher> +inline PolymorphicMatcher<internal::PropertyMatcher< + Class, PropertyType, PropertyType (Class::*)() const &> > +Property(PropertyType (Class::*property)() const &, + const PropertyMatcher& matcher) { + return MakePolymorphicMatcher( + internal::PropertyMatcher<Class, PropertyType, + PropertyType (Class::*)() const &>( + property, + MatcherCast<GTEST_REFERENCE_TO_CONST_(PropertyType)>(matcher))); +} + +// Three-argument form for reference-qualified member functions. +template <typename Class, typename PropertyType, typename PropertyMatcher> +inline PolymorphicMatcher<internal::PropertyMatcher< + Class, PropertyType, PropertyType (Class::*)() const &> > +Property(const std::string& property_name, + PropertyType (Class::*property)() const &, + const PropertyMatcher& matcher) { + return MakePolymorphicMatcher( + internal::PropertyMatcher<Class, PropertyType, + PropertyType (Class::*)() const &>( + property_name, property, + MatcherCast<GTEST_REFERENCE_TO_CONST_(PropertyType)>(matcher))); +} +#endif + // Creates a matcher that matches an object iff the result of applying // a callable to x matches 'matcher'. // For example, // ResultOf(f, StartsWith("hi")) // matches a Foo object x iff f(x) starts with "hi". -// callable parameter can be a function, function pointer, or a functor. -// Callable has to satisfy the following conditions: -// * It is required to keep no state affecting the results of -// the calls on it and make no assumptions about how many calls -// will be made. Any state it keeps must be protected from the -// concurrent access. -// * If it is a function object, it has to define type result_type. -// We recommend deriving your functor classes from std::unary_function. -template <typename Callable, typename ResultOfMatcher> -internal::ResultOfMatcher<Callable> ResultOf( - Callable callable, const ResultOfMatcher& matcher) { - return internal::ResultOfMatcher<Callable>( - callable, - MatcherCast<typename internal::CallableTraits<Callable>::ResultType>( - matcher)); - // The call to MatcherCast() is required for supporting inner - // matchers of compatible types. For example, it allows - // ResultOf(Function, m) - // to compile where Function() returns an int32 and m is a matcher for int64. +// `callable` parameter can be a function, function pointer, or a functor. It is +// required to keep no state affecting the results of the calls on it and make +// no assumptions about how many calls will be made. Any state it keeps must be +// protected from the concurrent access. +template <typename Callable, typename InnerMatcher> +internal::ResultOfMatcher<Callable, InnerMatcher> ResultOf( + Callable callable, InnerMatcher matcher) { + return internal::ResultOfMatcher<Callable, InnerMatcher>( + internal::move(callable), internal::move(matcher)); } // String matchers. // Matches a string equal to str. -inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> > - StrEq(const internal::string& str) { - return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>( - str, true, true)); +inline PolymorphicMatcher<internal::StrEqualityMatcher<std::string> > StrEq( + const std::string& str) { + return MakePolymorphicMatcher( + internal::StrEqualityMatcher<std::string>(str, true, true)); } // Matches a string not equal to str. -inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> > - StrNe(const internal::string& str) { - return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>( - str, false, true)); +inline PolymorphicMatcher<internal::StrEqualityMatcher<std::string> > StrNe( + const std::string& str) { + return MakePolymorphicMatcher( + internal::StrEqualityMatcher<std::string>(str, false, true)); } // Matches a string equal to str, ignoring case. -inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> > - StrCaseEq(const internal::string& str) { - return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>( - str, true, false)); +inline PolymorphicMatcher<internal::StrEqualityMatcher<std::string> > StrCaseEq( + const std::string& str) { + return MakePolymorphicMatcher( + internal::StrEqualityMatcher<std::string>(str, true, false)); } // Matches a string not equal to str, ignoring case. -inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> > - StrCaseNe(const internal::string& str) { - return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>( - str, false, false)); +inline PolymorphicMatcher<internal::StrEqualityMatcher<std::string> > StrCaseNe( + const std::string& str) { + return MakePolymorphicMatcher( + internal::StrEqualityMatcher<std::string>(str, false, false)); } // Creates a matcher that matches any string, std::string, or C string // that contains the given substring. -inline PolymorphicMatcher<internal::HasSubstrMatcher<internal::string> > - HasSubstr(const internal::string& substring) { - return MakePolymorphicMatcher(internal::HasSubstrMatcher<internal::string>( - substring)); +inline PolymorphicMatcher<internal::HasSubstrMatcher<std::string> > HasSubstr( + const std::string& substring) { + return MakePolymorphicMatcher( + internal::HasSubstrMatcher<std::string>(substring)); } // Matches a string that starts with 'prefix' (case-sensitive). -inline PolymorphicMatcher<internal::StartsWithMatcher<internal::string> > - StartsWith(const internal::string& prefix) { - return MakePolymorphicMatcher(internal::StartsWithMatcher<internal::string>( - prefix)); +inline PolymorphicMatcher<internal::StartsWithMatcher<std::string> > StartsWith( + const std::string& prefix) { + return MakePolymorphicMatcher( + internal::StartsWithMatcher<std::string>(prefix)); } // Matches a string that ends with 'suffix' (case-sensitive). -inline PolymorphicMatcher<internal::EndsWithMatcher<internal::string> > - EndsWith(const internal::string& suffix) { - return MakePolymorphicMatcher(internal::EndsWithMatcher<internal::string>( - suffix)); +inline PolymorphicMatcher<internal::EndsWithMatcher<std::string> > EndsWith( + const std::string& suffix) { + return MakePolymorphicMatcher(internal::EndsWithMatcher<std::string>(suffix)); } // Matches a string that fully matches regular expression 'regex'. @@ -4007,7 +4565,7 @@ inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex( return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, true)); } inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex( - const internal::string& regex) { + const std::string& regex) { return MatchesRegex(new internal::RE(regex)); } @@ -4018,7 +4576,7 @@ inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex( return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, false)); } inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex( - const internal::string& regex) { + const std::string& regex) { return ContainsRegex(new internal::RE(regex)); } @@ -4026,53 +4584,53 @@ inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex( // Wide string matchers. // Matches a string equal to str. -inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> > - StrEq(const internal::wstring& str) { - return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>( - str, true, true)); +inline PolymorphicMatcher<internal::StrEqualityMatcher<std::wstring> > StrEq( + const std::wstring& str) { + return MakePolymorphicMatcher( + internal::StrEqualityMatcher<std::wstring>(str, true, true)); } // Matches a string not equal to str. -inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> > - StrNe(const internal::wstring& str) { - return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>( - str, false, true)); +inline PolymorphicMatcher<internal::StrEqualityMatcher<std::wstring> > StrNe( + const std::wstring& str) { + return MakePolymorphicMatcher( + internal::StrEqualityMatcher<std::wstring>(str, false, true)); } // Matches a string equal to str, ignoring case. -inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> > - StrCaseEq(const internal::wstring& str) { - return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>( - str, true, false)); +inline PolymorphicMatcher<internal::StrEqualityMatcher<std::wstring> > +StrCaseEq(const std::wstring& str) { + return MakePolymorphicMatcher( + internal::StrEqualityMatcher<std::wstring>(str, true, false)); } // Matches a string not equal to str, ignoring case. -inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> > - StrCaseNe(const internal::wstring& str) { - return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>( - str, false, false)); +inline PolymorphicMatcher<internal::StrEqualityMatcher<std::wstring> > +StrCaseNe(const std::wstring& str) { + return MakePolymorphicMatcher( + internal::StrEqualityMatcher<std::wstring>(str, false, false)); } -// Creates a matcher that matches any wstring, std::wstring, or C wide string +// Creates a matcher that matches any ::wstring, std::wstring, or C wide string // that contains the given substring. -inline PolymorphicMatcher<internal::HasSubstrMatcher<internal::wstring> > - HasSubstr(const internal::wstring& substring) { - return MakePolymorphicMatcher(internal::HasSubstrMatcher<internal::wstring>( - substring)); +inline PolymorphicMatcher<internal::HasSubstrMatcher<std::wstring> > HasSubstr( + const std::wstring& substring) { + return MakePolymorphicMatcher( + internal::HasSubstrMatcher<std::wstring>(substring)); } // Matches a string that starts with 'prefix' (case-sensitive). -inline PolymorphicMatcher<internal::StartsWithMatcher<internal::wstring> > - StartsWith(const internal::wstring& prefix) { - return MakePolymorphicMatcher(internal::StartsWithMatcher<internal::wstring>( - prefix)); +inline PolymorphicMatcher<internal::StartsWithMatcher<std::wstring> > +StartsWith(const std::wstring& prefix) { + return MakePolymorphicMatcher( + internal::StartsWithMatcher<std::wstring>(prefix)); } // Matches a string that ends with 'suffix' (case-sensitive). -inline PolymorphicMatcher<internal::EndsWithMatcher<internal::wstring> > - EndsWith(const internal::wstring& suffix) { - return MakePolymorphicMatcher(internal::EndsWithMatcher<internal::wstring>( - suffix)); +inline PolymorphicMatcher<internal::EndsWithMatcher<std::wstring> > EndsWith( + const std::wstring& suffix) { + return MakePolymorphicMatcher( + internal::EndsWithMatcher<std::wstring>(suffix)); } #endif // GTEST_HAS_GLOBAL_WSTRING || GTEST_HAS_STD_WSTRING @@ -4101,6 +4659,58 @@ inline internal::Lt2Matcher Lt() { return internal::Lt2Matcher(); } // first field != the second field. inline internal::Ne2Matcher Ne() { return internal::Ne2Matcher(); } +// Creates a polymorphic matcher that matches a 2-tuple where +// FloatEq(first field) matches the second field. +inline internal::FloatingEq2Matcher<float> FloatEq() { + return internal::FloatingEq2Matcher<float>(); +} + +// Creates a polymorphic matcher that matches a 2-tuple where +// DoubleEq(first field) matches the second field. +inline internal::FloatingEq2Matcher<double> DoubleEq() { + return internal::FloatingEq2Matcher<double>(); +} + +// Creates a polymorphic matcher that matches a 2-tuple where +// FloatEq(first field) matches the second field with NaN equality. +inline internal::FloatingEq2Matcher<float> NanSensitiveFloatEq() { + return internal::FloatingEq2Matcher<float>(true); +} + +// Creates a polymorphic matcher that matches a 2-tuple where +// DoubleEq(first field) matches the second field with NaN equality. +inline internal::FloatingEq2Matcher<double> NanSensitiveDoubleEq() { + return internal::FloatingEq2Matcher<double>(true); +} + +// Creates a polymorphic matcher that matches a 2-tuple where +// FloatNear(first field, max_abs_error) matches the second field. +inline internal::FloatingEq2Matcher<float> FloatNear(float max_abs_error) { + return internal::FloatingEq2Matcher<float>(max_abs_error); +} + +// Creates a polymorphic matcher that matches a 2-tuple where +// DoubleNear(first field, max_abs_error) matches the second field. +inline internal::FloatingEq2Matcher<double> DoubleNear(double max_abs_error) { + return internal::FloatingEq2Matcher<double>(max_abs_error); +} + +// Creates a polymorphic matcher that matches a 2-tuple where +// FloatNear(first field, max_abs_error) matches the second field with NaN +// equality. +inline internal::FloatingEq2Matcher<float> NanSensitiveFloatNear( + float max_abs_error) { + return internal::FloatingEq2Matcher<float>(max_abs_error, true); +} + +// Creates a polymorphic matcher that matches a 2-tuple where +// DoubleNear(first field, max_abs_error) matches the second field with NaN +// equality. +inline internal::FloatingEq2Matcher<double> NanSensitiveDoubleNear( + double max_abs_error) { + return internal::FloatingEq2Matcher<double>(max_abs_error, true); +} + // Creates a matcher that matches any value of type T that m doesn't // match. template <typename InnerMatcher> @@ -4178,7 +4788,7 @@ WhenSorted(const ContainerMatcher& container_matcher) { // Matches an STL-style container or a native array that contains the // same number of elements as in rhs, where its i-th element and rhs's // i-th element (as a pair) satisfy the given pair matcher, for all i. -// TupleMatcher must be able to be safely cast to Matcher<tuple<const +// TupleMatcher must be able to be safely cast to Matcher<std::tuple<const // T1&, const T2&> >, where T1 and T2 are the types of elements in the // LHS container and the RHS container respectively. template <typename TupleMatcher, typename Container> @@ -4209,7 +4819,7 @@ inline internal::PointwiseMatcher<TupleMatcher, std::vector<T> > Pointwise( // elements as in rhs, where in some permutation of the container, its // i-th element and rhs's i-th element (as a pair) satisfy the given // pair matcher, for all i. Tuple2Matcher must be able to be safely -// cast to Matcher<tuple<const T1&, const T2&> >, where T1 and T2 are +// cast to Matcher<std::tuple<const T1&, const T2&> >, where T1 and T2 are // the types of elements in the LHS container and the RHS container // respectively. // @@ -4283,6 +4893,128 @@ inline internal::ContainsMatcher<M> Contains(M matcher) { return internal::ContainsMatcher<M>(matcher); } +// IsSupersetOf(iterator_first, iterator_last) +// IsSupersetOf(pointer, count) +// IsSupersetOf(array) +// IsSupersetOf(container) +// IsSupersetOf({e1, e2, ..., en}) +// +// IsSupersetOf() verifies that a surjective partial mapping onto a collection +// of matchers exists. In other words, a container matches +// IsSupersetOf({e1, ..., en}) if and only if there is a permutation +// {y1, ..., yn} of some of the container's elements where y1 matches e1, +// ..., and yn matches en. Obviously, the size of the container must be >= n +// in order to have a match. Examples: +// +// - {1, 2, 3} matches IsSupersetOf({Ge(3), Ne(0)}), as 3 matches Ge(3) and +// 1 matches Ne(0). +// - {1, 2} doesn't match IsSupersetOf({Eq(1), Lt(2)}), even though 1 matches +// both Eq(1) and Lt(2). The reason is that different matchers must be used +// for elements in different slots of the container. +// - {1, 1, 2} matches IsSupersetOf({Eq(1), Lt(2)}), as (the first) 1 matches +// Eq(1) and (the second) 1 matches Lt(2). +// - {1, 2, 3} matches IsSupersetOf(Gt(1), Gt(1)), as 2 matches (the first) +// Gt(1) and 3 matches (the second) Gt(1). +// +// The matchers can be specified as an array, a pointer and count, a container, +// an initializer list, or an STL iterator range. In each of these cases, the +// underlying matchers can be either values or matchers. + +template <typename Iter> +inline internal::UnorderedElementsAreArrayMatcher< + typename ::std::iterator_traits<Iter>::value_type> +IsSupersetOf(Iter first, Iter last) { + typedef typename ::std::iterator_traits<Iter>::value_type T; + return internal::UnorderedElementsAreArrayMatcher<T>( + internal::UnorderedMatcherRequire::Superset, first, last); +} + +template <typename T> +inline internal::UnorderedElementsAreArrayMatcher<T> IsSupersetOf( + const T* pointer, size_t count) { + return IsSupersetOf(pointer, pointer + count); +} + +template <typename T, size_t N> +inline internal::UnorderedElementsAreArrayMatcher<T> IsSupersetOf( + const T (&array)[N]) { + return IsSupersetOf(array, N); +} + +template <typename Container> +inline internal::UnorderedElementsAreArrayMatcher< + typename Container::value_type> +IsSupersetOf(const Container& container) { + return IsSupersetOf(container.begin(), container.end()); +} + +#if GTEST_HAS_STD_INITIALIZER_LIST_ +template <typename T> +inline internal::UnorderedElementsAreArrayMatcher<T> IsSupersetOf( + ::std::initializer_list<T> xs) { + return IsSupersetOf(xs.begin(), xs.end()); +} +#endif + +// IsSubsetOf(iterator_first, iterator_last) +// IsSubsetOf(pointer, count) +// IsSubsetOf(array) +// IsSubsetOf(container) +// IsSubsetOf({e1, e2, ..., en}) +// +// IsSubsetOf() verifies that an injective mapping onto a collection of matchers +// exists. In other words, a container matches IsSubsetOf({e1, ..., en}) if and +// only if there is a subset of matchers {m1, ..., mk} which would match the +// container using UnorderedElementsAre. Obviously, the size of the container +// must be <= n in order to have a match. Examples: +// +// - {1} matches IsSubsetOf({Gt(0), Lt(0)}), as 1 matches Gt(0). +// - {1, -1} matches IsSubsetOf({Lt(0), Gt(0)}), as 1 matches Gt(0) and -1 +// matches Lt(0). +// - {1, 2} doesn't matches IsSubsetOf({Gt(0), Lt(0)}), even though 1 and 2 both +// match Gt(0). The reason is that different matchers must be used for +// elements in different slots of the container. +// +// The matchers can be specified as an array, a pointer and count, a container, +// an initializer list, or an STL iterator range. In each of these cases, the +// underlying matchers can be either values or matchers. + +template <typename Iter> +inline internal::UnorderedElementsAreArrayMatcher< + typename ::std::iterator_traits<Iter>::value_type> +IsSubsetOf(Iter first, Iter last) { + typedef typename ::std::iterator_traits<Iter>::value_type T; + return internal::UnorderedElementsAreArrayMatcher<T>( + internal::UnorderedMatcherRequire::Subset, first, last); +} + +template <typename T> +inline internal::UnorderedElementsAreArrayMatcher<T> IsSubsetOf( + const T* pointer, size_t count) { + return IsSubsetOf(pointer, pointer + count); +} + +template <typename T, size_t N> +inline internal::UnorderedElementsAreArrayMatcher<T> IsSubsetOf( + const T (&array)[N]) { + return IsSubsetOf(array, N); +} + +template <typename Container> +inline internal::UnorderedElementsAreArrayMatcher< + typename Container::value_type> +IsSubsetOf(const Container& container) { + return IsSubsetOf(container.begin(), container.end()); +} + +#if GTEST_HAS_STD_INITIALIZER_LIST_ +template <typename T> +inline internal::UnorderedElementsAreArrayMatcher<T> IsSubsetOf( + ::std::initializer_list<T> xs) { + return IsSubsetOf(xs.begin(), xs.end()); +} +#endif + // Matches an STL-style container or a native array that contains only // elements matching the given value or matcher. // @@ -4356,20 +5088,60 @@ inline bool ExplainMatchResult( return SafeMatcherCast<const T&>(matcher).MatchAndExplain(value, listener); } -#if GTEST_LANG_CXX11 -// Define variadic matcher versions. They are overloaded in -// gmock-generated-matchers.h for the cases supported by pre C++11 compilers. +// Returns a string representation of the given matcher. Useful for description +// strings of matchers defined using MATCHER_P* macros that accept matchers as +// their arguments. For example: +// +// MATCHER_P(XAndYThat, matcher, +// "X that " + DescribeMatcher<int>(matcher, negation) + +// " and Y that " + DescribeMatcher<double>(matcher, negation)) { +// return ExplainMatchResult(matcher, arg.x(), result_listener) && +// ExplainMatchResult(matcher, arg.y(), result_listener); +// } +template <typename T, typename M> +std::string DescribeMatcher(const M& matcher, bool negation = false) { + ::std::stringstream ss; + Matcher<T> monomorphic_matcher = SafeMatcherCast<T>(matcher); + if (negation) { + monomorphic_matcher.DescribeNegationTo(&ss); + } else { + monomorphic_matcher.DescribeTo(&ss); + } + return ss.str(); +} + template <typename... Args> -inline internal::AllOfMatcher<Args...> AllOf(const Args&... matchers) { - return internal::AllOfMatcher<Args...>(matchers...); +internal::ElementsAreMatcher< + std::tuple<typename std::decay<const Args&>::type...>> +ElementsAre(const Args&... matchers) { + return internal::ElementsAreMatcher< + std::tuple<typename std::decay<const Args&>::type...>>( + std::make_tuple(matchers...)); } template <typename... Args> -inline internal::AnyOfMatcher<Args...> AnyOf(const Args&... matchers) { - return internal::AnyOfMatcher<Args...>(matchers...); +internal::UnorderedElementsAreMatcher< + std::tuple<typename std::decay<const Args&>::type...>> +UnorderedElementsAre(const Args&... matchers) { + return internal::UnorderedElementsAreMatcher< + std::tuple<typename std::decay<const Args&>::type...>>( + std::make_tuple(matchers...)); } -#endif // GTEST_LANG_CXX11 +// Define variadic matcher versions. +template <typename... Args> +internal::AllOfMatcher<typename std::decay<const Args&>::type...> AllOf( + const Args&... matchers) { + return internal::AllOfMatcher<typename std::decay<const Args&>::type...>( + matchers...); +} + +template <typename... Args> +internal::AnyOfMatcher<typename std::decay<const Args&>::type...> AnyOf( + const Args&... matchers) { + return internal::AnyOfMatcher<typename std::decay<const Args&>::type...>( + matchers...); +} // AllArgs(m) is a synonym of m. This is useful in // @@ -4381,6 +5153,39 @@ inline internal::AnyOfMatcher<Args...> AnyOf(const Args&... matchers) { template <typename InnerMatcher> inline InnerMatcher AllArgs(const InnerMatcher& matcher) { return matcher; } +// Returns a matcher that matches the value of an optional<> type variable. +// The matcher implementation only uses '!arg' and requires that the optional<> +// type has a 'value_type' member type and that '*arg' is of type 'value_type' +// and is printable using 'PrintToString'. It is compatible with +// std::optional/std::experimental::optional. +// Note that to compare an optional type variable against nullopt you should +// use Eq(nullopt) and not Optional(Eq(nullopt)). The latter implies that the +// optional value contains an optional itself. +template <typename ValueMatcher> +inline internal::OptionalMatcher<ValueMatcher> Optional( + const ValueMatcher& value_matcher) { + return internal::OptionalMatcher<ValueMatcher>(value_matcher); +} + +// Returns a matcher that matches the value of a absl::any type variable. +template <typename T> +PolymorphicMatcher<internal::any_cast_matcher::AnyCastMatcher<T> > AnyWith( + const Matcher<const T&>& matcher) { + return MakePolymorphicMatcher( + internal::any_cast_matcher::AnyCastMatcher<T>(matcher)); +} + +// Returns a matcher that matches the value of a variant<> type variable. +// The matcher implementation uses ADL to find the holds_alternative and get +// functions. +// It is compatible with std::variant. +template <typename T> +PolymorphicMatcher<internal::variant_matcher::VariantMatcher<T> > VariantWith( + const Matcher<const T&>& matcher) { + return MakePolymorphicMatcher( + internal::variant_matcher::VariantMatcher<T>(matcher)); +} + // These macros allow using matchers to check values in Google Test // tests. ASSERT_THAT(value, matcher) and EXPECT_THAT(value, matcher) // succeed iff the value matches the matcher. If the assertion fails, @@ -4392,8 +5197,11 @@ inline InnerMatcher AllArgs(const InnerMatcher& matcher) { return matcher; } } // namespace testing +GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251 5046 + // Include any custom callback matchers added by the local installation. // We must include this header at the end to make sure it can use the // declarations from this file. #include "gmock/internal/custom/gmock-matchers.h" + #endif // GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_ diff --git a/googlemock/include/gmock/gmock-more-actions.h b/googlemock/include/gmock/gmock-more-actions.h index 3d387b6..5c6dc8b 100644 --- a/googlemock/include/gmock/gmock-more-actions.h +++ b/googlemock/include/gmock/gmock-more-actions.h @@ -26,13 +26,14 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // Google Mock - a framework for writing C++ mock classes. // // This file implements some actions that depend on gmock-generated-actions.h. +// GOOGLETEST_CM0002 DO NOT DELETE + #ifndef GMOCK_INCLUDE_GMOCK_GMOCK_MORE_ACTIONS_H_ #define GMOCK_INCLUDE_GMOCK_GMOCK_MORE_ACTIONS_H_ @@ -161,7 +162,7 @@ WithArg(const InnerAction& action) { ACTION_TEMPLATE(ReturnArg, HAS_1_TEMPLATE_PARAMS(int, k), AND_0_VALUE_PARAMS()) { - return ::testing::get<k>(args); + return ::std::get<k>(args); } // Action SaveArg<k>(pointer) saves the k-th (0-based) argument of the @@ -169,7 +170,7 @@ ACTION_TEMPLATE(ReturnArg, ACTION_TEMPLATE(SaveArg, HAS_1_TEMPLATE_PARAMS(int, k), AND_1_VALUE_PARAMS(pointer)) { - *pointer = ::testing::get<k>(args); + *pointer = ::std::get<k>(args); } // Action SaveArgPointee<k>(pointer) saves the value pointed to @@ -177,7 +178,7 @@ ACTION_TEMPLATE(SaveArg, ACTION_TEMPLATE(SaveArgPointee, HAS_1_TEMPLATE_PARAMS(int, k), AND_1_VALUE_PARAMS(pointer)) { - *pointer = *::testing::get<k>(args); + *pointer = *::std::get<k>(args); } // Action SetArgReferee<k>(value) assigns 'value' to the variable @@ -185,13 +186,13 @@ ACTION_TEMPLATE(SaveArgPointee, ACTION_TEMPLATE(SetArgReferee, HAS_1_TEMPLATE_PARAMS(int, k), AND_1_VALUE_PARAMS(value)) { - typedef typename ::testing::tuple_element<k, args_type>::type argk_type; + typedef typename ::std::tuple_element<k, args_type>::type argk_type; // Ensures that argument #k is a reference. If you get a compiler // error on the next line, you are using SetArgReferee<k>(value) in // a mock function whose k-th (0-based) argument is not a reference. GTEST_COMPILE_ASSERT_(internal::is_reference<argk_type>::value, SetArgReferee_must_be_used_with_a_reference_argument); - ::testing::get<k>(args) = value; + ::std::get<k>(args) = value; } // Action SetArrayArgument<k>(first, last) copies the elements in @@ -204,9 +205,9 @@ ACTION_TEMPLATE(SetArrayArgument, AND_2_VALUE_PARAMS(first, last)) { // Visual Studio deprecates ::std::copy, so we use our own copy in that case. #ifdef _MSC_VER - internal::CopyElements(first, last, ::testing::get<k>(args)); + internal::CopyElements(first, last, ::std::get<k>(args)); #else - ::std::copy(first, last, ::testing::get<k>(args)); + ::std::copy(first, last, ::std::get<k>(args)); #endif } @@ -215,7 +216,7 @@ ACTION_TEMPLATE(SetArrayArgument, ACTION_TEMPLATE(DeleteArg, HAS_1_TEMPLATE_PARAMS(int, k), AND_0_VALUE_PARAMS()) { - delete ::testing::get<k>(args); + delete ::std::get<k>(args); } // This action returns the value pointed to by 'pointer'. diff --git a/googlemock/include/gmock/gmock-more-matchers.h b/googlemock/include/gmock/gmock-more-matchers.h index 3db899f..1c9a399 100644 --- a/googlemock/include/gmock/gmock-more-matchers.h +++ b/googlemock/include/gmock/gmock-more-matchers.h @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: marcus.boerger@google.com (Marcus Boerger) + // Google Mock - a framework for writing C++ mock classes. // @@ -36,13 +35,27 @@ // Note that tests are implemented in gmock-matchers_test.cc rather than // gmock-more-matchers-test.cc. -#ifndef GMOCK_GMOCK_MORE_MATCHERS_H_ -#define GMOCK_GMOCK_MORE_MATCHERS_H_ +// GOOGLETEST_CM0002 DO NOT DELETE + +#ifndef GMOCK_INCLUDE_GMOCK_MORE_MATCHERS_H_ +#define GMOCK_INCLUDE_GMOCK_MORE_MATCHERS_H_ #include "gmock/gmock-generated-matchers.h" namespace testing { +// Silence C4100 (unreferenced formal +// parameter) for MSVC +#ifdef _MSC_VER +# pragma warning(push) +# pragma warning(disable:4100) +#if (_MSC_VER == 1900) +// and silence C4800 (C4800: 'int *const ': forcing value +// to bool 'true' or 'false') for MSVC 14 +# pragma warning(disable:4800) + #endif +#endif + // Defines a matcher that matches an empty container. The container must // support both size() and empty(), which all STL-like containers provide. MATCHER(IsEmpty, negation ? "isn't empty" : "is empty") { @@ -53,6 +66,27 @@ MATCHER(IsEmpty, negation ? "isn't empty" : "is empty") { return false; } +// Define a matcher that matches a value that evaluates in boolean +// context to true. Useful for types that define "explicit operator +// bool" operators and so can't be compared for equality with true +// and false. +MATCHER(IsTrue, negation ? "is false" : "is true") { + return static_cast<bool>(arg); +} + +// Define a matcher that matches a value that evaluates in boolean +// context to false. Useful for types that define "explicit operator +// bool" operators and so can't be compared for equality with true +// and false. +MATCHER(IsFalse, negation ? "is true" : "is false") { + return !static_cast<bool>(arg); +} + +#ifdef _MSC_VER +# pragma warning(pop) +#endif + + } // namespace testing -#endif // GMOCK_GMOCK_MORE_MATCHERS_H_ +#endif // GMOCK_INCLUDE_GMOCK_MORE_MATCHERS_H_ diff --git a/googlemock/include/gmock/gmock-spec-builders.h b/googlemock/include/gmock/gmock-spec-builders.h index 1e8f732..d085df3 100644 --- a/googlemock/include/gmock/gmock-spec-builders.h +++ b/googlemock/include/gmock/gmock-spec-builders.h @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // Google Mock - a framework for writing C++ mock classes. // @@ -57,6 +56,8 @@ // where all clauses are optional, and .InSequence()/.After()/ // .WillOnce() can appear any number of times. +// GOOGLETEST_CM0002 DO NOT DELETE + #ifndef GMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_ #define GMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_ @@ -65,11 +66,6 @@ #include <sstream> #include <string> #include <vector> - -#if GTEST_HAS_EXCEPTIONS -# include <stdexcept> // NOLINT -#endif - #include "gmock/gmock-actions.h" #include "gmock/gmock-cardinalities.h" #include "gmock/gmock-matchers.h" @@ -77,6 +73,13 @@ #include "gmock/internal/gmock-port.h" #include "gtest/gtest.h" +#if GTEST_HAS_EXCEPTIONS +# include <stdexcept> // NOLINT +#endif + +GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \ +/* class A needs to have dll-interface to be used by clients of class B */) + namespace testing { // An abstract handle of an expectation. @@ -148,15 +151,13 @@ class GTEST_API_ UntypedFunctionMockerBase { // action fails. // L = * virtual UntypedActionResultHolderBase* UntypedPerformDefaultAction( - const void* untyped_args, - const string& call_description) const = 0; + void* untyped_args, const std::string& call_description) const = 0; // Performs the given action with the given arguments and returns // the action's result. // L = * virtual UntypedActionResultHolderBase* UntypedPerformAction( - const void* untyped_action, - const void* untyped_args) const = 0; + const void* untyped_action, void* untyped_args) const = 0; // Writes a message that the call is uninteresting (i.e. neither // explicitly expected nor explicitly unexpected) to the given @@ -186,7 +187,7 @@ class GTEST_API_ UntypedFunctionMockerBase { // this information in the global mock registry. Will be called // whenever an EXPECT_CALL() or ON_CALL() is executed on this mock // method. - // TODO(wan@google.com): rename to SetAndRegisterOwner(). + // FIXME: rename to SetAndRegisterOwner(). void RegisterOwner(const void* mock_obj) GTEST_LOCK_EXCLUDED_(g_gmock_mutex); @@ -211,9 +212,8 @@ class GTEST_API_ UntypedFunctionMockerBase { // arguments. This function can be safely called from multiple // threads concurrently. The caller is responsible for deleting the // result. - UntypedActionResultHolderBase* UntypedInvokeWith( - const void* untyped_args) - GTEST_LOCK_EXCLUDED_(g_gmock_mutex); + UntypedActionResultHolderBase* UntypedInvokeWith(void* untyped_args) + GTEST_LOCK_EXCLUDED_(g_gmock_mutex); protected: typedef std::vector<const void*> UntypedOnCallSpecs; @@ -238,6 +238,14 @@ class GTEST_API_ UntypedFunctionMockerBase { UntypedOnCallSpecs untyped_on_call_specs_; // All expectations for this function mocker. + // + // It's undefined behavior to interleave expectations (EXPECT_CALLs + // or ON_CALLs) and mock function calls. Also, the order of + // expectations is important. Therefore it's a logic race condition + // to read/write untyped_expectations_ concurrently. In order for + // tools like tsan to catch concurrent read/write accesses to + // untyped_expectations, we deliberately leave accesses to it + // unprotected. UntypedExpectations untyped_expectations_; }; // class UntypedFunctionMockerBase @@ -263,12 +271,14 @@ class UntypedOnCallSpecBase { }; // Asserts that the ON_CALL() statement has a certain property. - void AssertSpecProperty(bool property, const string& failure_message) const { + void AssertSpecProperty(bool property, + const std::string& failure_message) const { Assert(property, file_, line_, failure_message); } // Expects that the ON_CALL() statement has a certain property. - void ExpectSpecProperty(bool property, const string& failure_message) const { + void ExpectSpecProperty(bool property, + const std::string& failure_message) const { Expect(property, file_, line_, failure_message); } @@ -362,7 +372,6 @@ enum CallReaction { kAllow, kWarn, kFail, - kDefault = kWarn // By default, warn about uninteresting calls. }; } // namespace internal @@ -700,7 +709,7 @@ GTEST_API_ extern ThreadLocal<Sequence*> g_gmock_implicit_sequence; class GTEST_API_ ExpectationBase { public: // source_text is the EXPECT_CALL(...) source that created this Expectation. - ExpectationBase(const char* file, int line, const string& source_text); + ExpectationBase(const char* file, int line, const std::string& source_text); virtual ~ExpectationBase(); @@ -748,12 +757,14 @@ class GTEST_API_ ExpectationBase { virtual Expectation GetHandle() = 0; // Asserts that the EXPECT_CALL() statement has the given property. - void AssertSpecProperty(bool property, const string& failure_message) const { + void AssertSpecProperty(bool property, + const std::string& failure_message) const { Assert(property, file_, line_, failure_message); } // Expects that the EXPECT_CALL() statement has the given property. - void ExpectSpecProperty(bool property, const string& failure_message) const { + void ExpectSpecProperty(bool property, + const std::string& failure_message) const { Expect(property, file_, line_, failure_message); } @@ -855,7 +866,7 @@ class GTEST_API_ ExpectationBase { // an EXPECT_CALL() statement finishes. const char* file_; // The file that contains the expectation. int line_; // The line number of the expectation. - const string source_text_; // The EXPECT_CALL(...) source text. + const std::string source_text_; // The EXPECT_CALL(...) source text. // True iff the cardinality is specified explicitly. bool cardinality_specified_; Cardinality cardinality_; // The cardinality of the expectation. @@ -890,8 +901,8 @@ class TypedExpectation : public ExpectationBase { typedef typename Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple; typedef typename Function<F>::Result Result; - TypedExpectation(FunctionMockerBase<F>* owner, - const char* a_file, int a_line, const string& a_source_text, + TypedExpectation(FunctionMockerBase<F>* owner, const char* a_file, int a_line, + const std::string& a_source_text, const ArgumentMatcherTuple& m) : ExpectationBase(a_file, a_line, a_source_text), owner_(owner), @@ -1183,9 +1194,10 @@ class TypedExpectation : public ExpectationBase { Log(kWarning, ss.str(), 1); } - return count <= action_count ? - *static_cast<const Action<F>*>(untyped_actions_[count - 1]) : - repeated_action(); + return count <= action_count + ? *static_cast<const Action<F>*>( + untyped_actions_[static_cast<size_t>(count - 1)]) + : repeated_action(); } // Given the arguments of a mock function call, if the call will @@ -1209,10 +1221,10 @@ class TypedExpectation : public ExpectationBase { mocker->DescribeDefaultActionTo(args, what); DescribeCallCountTo(why); - // TODO(wan@google.com): allow the user to control whether + // FIXME: allow the user to control whether // unexpected calls should fail immediately or continue using a // flag --gmock_unexpected_calls_are_fatal. - return NULL; + return nullptr; } IncrementCallCount(); @@ -1250,7 +1262,7 @@ class TypedExpectation : public ExpectationBase { // Logs a message including file and line number information. GTEST_API_ void LogWithLocation(testing::internal::LogSeverity severity, const char* file, int line, - const string& message); + const std::string& message); template <typename F> class MockSpec { @@ -1261,15 +1273,16 @@ class MockSpec { // Constructs a MockSpec object, given the function mocker object // that the spec is associated with. - explicit MockSpec(internal::FunctionMockerBase<F>* function_mocker) - : function_mocker_(function_mocker) {} + MockSpec(internal::FunctionMockerBase<F>* function_mocker, + const ArgumentMatcherTuple& matchers) + : function_mocker_(function_mocker), matchers_(matchers) {} // Adds a new default action spec to the function mocker and returns // the newly created spec. internal::OnCallSpec<F>& InternalDefaultActionSetAt( const char* file, int line, const char* obj, const char* call) { LogWithLocation(internal::kInfo, file, line, - string("ON_CALL(") + obj + ", " + call + ") invoked"); + std::string("ON_CALL(") + obj + ", " + call + ") invoked"); return function_mocker_->AddNewOnCallSpec(file, line, matchers_); } @@ -1277,20 +1290,24 @@ class MockSpec { // the newly created spec. internal::TypedExpectation<F>& InternalExpectedAt( const char* file, int line, const char* obj, const char* call) { - const string source_text(string("EXPECT_CALL(") + obj + ", " + call + ")"); + const std::string source_text(std::string("EXPECT_CALL(") + obj + ", " + + call + ")"); LogWithLocation(internal::kInfo, file, line, source_text + " invoked"); return function_mocker_->AddNewExpectation( file, line, source_text, matchers_); } + // This operator overload is used to swallow the superfluous parameter list + // introduced by the ON/EXPECT_CALL macros. See the macro comments for more + // explanation. + MockSpec<F>& operator()(const internal::WithoutMatchers&, void* const) { + return *this; + } + private: template <typename Function> friend class internal::FunctionMocker; - void SetMatchers(const ArgumentMatcherTuple& matchers) { - matchers_ = matchers; - } - // The function mocker that owns this spec. internal::FunctionMockerBase<F>* const function_mocker_; // The argument matchers specified in the spec. @@ -1354,11 +1371,7 @@ class ReferenceOrValueWrapper<T&> { // we need to temporarily disable the warning. We have to do it for // the entire class to suppress the warning, even though it's about // the constructor only. - -#ifdef _MSC_VER -# pragma warning(push) // Saves the current warning state. -# pragma warning(disable:4355) // Temporarily disables warning 4355. -#endif // _MSV_VER +GTEST_DISABLE_MSC_WARNINGS_PUSH_(4355) // C++ treats the void type specially. For example, you cannot define // a void-typed variable or pass a void value to a function. @@ -1398,19 +1411,20 @@ class ActionResultHolder : public UntypedActionResultHolderBase { template <typename F> static ActionResultHolder* PerformDefaultAction( const FunctionMockerBase<F>* func_mocker, - const typename Function<F>::ArgumentTuple& args, - const string& call_description) { - return new ActionResultHolder(Wrapper( - func_mocker->PerformDefaultAction(args, call_description))); + typename RvalueRef<typename Function<F>::ArgumentTuple>::type args, + const std::string& call_description) { + return new ActionResultHolder(Wrapper(func_mocker->PerformDefaultAction( + internal::move(args), call_description))); } // Performs the given action and returns the result in a new-ed // ActionResultHolder. template <typename F> - static ActionResultHolder* - PerformAction(const Action<F>& action, - const typename Function<F>::ArgumentTuple& args) { - return new ActionResultHolder(Wrapper(action.Perform(args))); + static ActionResultHolder* PerformAction( + const Action<F>& action, + typename RvalueRef<typename Function<F>::ArgumentTuple>::type args) { + return new ActionResultHolder( + Wrapper(action.Perform(internal::move(args)))); } private: @@ -1438,9 +1452,9 @@ class ActionResultHolder<void> : public UntypedActionResultHolderBase { template <typename F> static ActionResultHolder* PerformDefaultAction( const FunctionMockerBase<F>* func_mocker, - const typename Function<F>::ArgumentTuple& args, - const string& call_description) { - func_mocker->PerformDefaultAction(args, call_description); + typename RvalueRef<typename Function<F>::ArgumentTuple>::type args, + const std::string& call_description) { + func_mocker->PerformDefaultAction(internal::move(args), call_description); return new ActionResultHolder; } @@ -1449,8 +1463,8 @@ class ActionResultHolder<void> : public UntypedActionResultHolderBase { template <typename F> static ActionResultHolder* PerformAction( const Action<F>& action, - const typename Function<F>::ArgumentTuple& args) { - action.Perform(args); + typename RvalueRef<typename Function<F>::ArgumentTuple>::type args) { + action.Perform(internal::move(args)); return new ActionResultHolder; } @@ -1469,7 +1483,7 @@ class FunctionMockerBase : public UntypedFunctionMockerBase { typedef typename Function<F>::ArgumentTuple ArgumentTuple; typedef typename Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple; - FunctionMockerBase() : current_spec_(this) {} + FunctionMockerBase() {} // The destructor verifies that all expectations on this mock // function have been satisfied. If not, it will report Google Test @@ -1495,7 +1509,7 @@ class FunctionMockerBase : public UntypedFunctionMockerBase { return spec; } - return NULL; + return nullptr; } // Performs the default action of this mock function on the given @@ -1505,14 +1519,16 @@ class FunctionMockerBase : public UntypedFunctionMockerBase { // mutable state of this object, and thus can be called concurrently // without locking. // L = * - Result PerformDefaultAction(const ArgumentTuple& args, - const string& call_description) const { + Result PerformDefaultAction( + typename RvalueRef<typename Function<F>::ArgumentTuple>::type args, + const std::string& call_description) const { const OnCallSpec<F>* const spec = this->FindOnCallSpec(args); - if (spec != NULL) { - return spec->GetAction().Perform(args); + if (spec != nullptr) { + return spec->GetAction().Perform(internal::move(args)); } - const string message = call_description + + const std::string message = + call_description + "\n The mock function has no default action " "set, and its return type has no default value set."; #if GTEST_HAS_EXCEPTIONS @@ -1531,11 +1547,11 @@ class FunctionMockerBase : public UntypedFunctionMockerBase { // action fails. The caller is responsible for deleting the result. // L = * virtual UntypedActionResultHolderBase* UntypedPerformDefaultAction( - const void* untyped_args, // must point to an ArgumentTuple - const string& call_description) const { - const ArgumentTuple& args = - *static_cast<const ArgumentTuple*>(untyped_args); - return ResultHolder::PerformDefaultAction(this, args, call_description); + void* untyped_args, // must point to an ArgumentTuple + const std::string& call_description) const { + ArgumentTuple* args = static_cast<ArgumentTuple*>(untyped_args); + return ResultHolder::PerformDefaultAction(this, internal::move(*args), + call_description); } // Performs the given action with the given arguments and returns @@ -1543,13 +1559,12 @@ class FunctionMockerBase : public UntypedFunctionMockerBase { // result. // L = * virtual UntypedActionResultHolderBase* UntypedPerformAction( - const void* untyped_action, const void* untyped_args) const { + const void* untyped_action, void* untyped_args) const { // Make a copy of the action before performing it, in case the // action deletes the mock object (and thus deletes itself). const Action<F> action = *static_cast<const Action<F>*>(untyped_action); - const ArgumentTuple& args = - *static_cast<const ArgumentTuple*>(untyped_args); - return ResultHolder::PerformAction(action, args); + ArgumentTuple* args = static_cast<ArgumentTuple*>(untyped_args); + return ResultHolder::PerformAction(action, internal::move(*args)); } // Implements UntypedFunctionMockerBase::ClearDefaultActionsLocked(): @@ -1589,10 +1604,14 @@ class FunctionMockerBase : public UntypedFunctionMockerBase { // Returns the result of invoking this mock function with the given // arguments. This function can be safely called from multiple // threads concurrently. - Result InvokeWith(const ArgumentTuple& args) - GTEST_LOCK_EXCLUDED_(g_gmock_mutex) { + Result InvokeWith( + typename RvalueRef<typename Function<F>::ArgumentTuple>::type args) + GTEST_LOCK_EXCLUDED_(g_gmock_mutex) { + // const_cast is required since in C++98 we still pass ArgumentTuple around + // by const& instead of rvalue reference. + void* untyped_args = const_cast<void*>(static_cast<const void*>(&args)); scoped_ptr<ResultHolder> holder( - DownCast_<ResultHolder*>(this->UntypedInvokeWith(&args))); + DownCast_<ResultHolder*>(this->UntypedInvokeWith(untyped_args))); return holder->Unwrap(); } @@ -1608,31 +1627,27 @@ class FunctionMockerBase : public UntypedFunctionMockerBase { } // Adds and returns an expectation spec for this mock function. - TypedExpectation<F>& AddNewExpectation( - const char* file, - int line, - const string& source_text, - const ArgumentMatcherTuple& m) - GTEST_LOCK_EXCLUDED_(g_gmock_mutex) { + TypedExpectation<F>& AddNewExpectation(const char* file, int line, + const std::string& source_text, + const ArgumentMatcherTuple& m) + GTEST_LOCK_EXCLUDED_(g_gmock_mutex) { Mock::RegisterUseByOnCallOrExpectCall(MockObject(), file, line); TypedExpectation<F>* const expectation = new TypedExpectation<F>(this, file, line, source_text, m); const linked_ptr<ExpectationBase> untyped_expectation(expectation); + // See the definition of untyped_expectations_ for why access to + // it is unprotected here. untyped_expectations_.push_back(untyped_expectation); // Adds this expectation into the implicit sequence if there is one. Sequence* const implicit_sequence = g_gmock_implicit_sequence.get(); - if (implicit_sequence != NULL) { + if (implicit_sequence != nullptr) { implicit_sequence->AddExpectation(Expectation(untyped_expectation)); } return *expectation; } - // The current spec (either default action spec or expectation spec) - // being described on this function mocker. - MockSpec<F>& current_spec() { return current_spec_; } - private: template <typename Func> friend class TypedExpectation; @@ -1645,7 +1660,7 @@ class FunctionMockerBase : public UntypedFunctionMockerBase { ::std::ostream* os) const { const OnCallSpec<F>* const spec = FindOnCallSpec(args); - if (spec == NULL) { + if (spec == nullptr) { *os << (internal::type_equals<Result, void>::value ? "returning directly.\n" : "returning default value.\n"); @@ -1695,9 +1710,9 @@ class FunctionMockerBase : public UntypedFunctionMockerBase { *static_cast<const ArgumentTuple*>(untyped_args); MutexLock l(&g_gmock_mutex); TypedExpectation<F>* exp = this->FindMatchingExpectationLocked(args); - if (exp == NULL) { // A match wasn't found. + if (exp == nullptr) { // A match wasn't found. this->FormatUnexpectedCallMessageLocked(args, what, why); - return NULL; + return nullptr; } // This line must be done before calling GetActionForArguments(), @@ -1705,8 +1720,8 @@ class FunctionMockerBase : public UntypedFunctionMockerBase { // its saturation status. *is_excessive = exp->IsSaturated(); const Action<F>* action = exp->GetActionForArguments(this, args, what, why); - if (action != NULL && action->IsDoDefault()) - action = NULL; // Normalize "do default" to NULL. + if (action != nullptr && action->IsDoDefault()) + action = nullptr; // Normalize "do default" to NULL. *untyped_action = action; return exp; } @@ -1725,6 +1740,8 @@ class FunctionMockerBase : public UntypedFunctionMockerBase { const ArgumentTuple& args) const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { g_gmock_mutex.AssertHeld(); + // See the definition of untyped_expectations_ for why access to + // it is unprotected here. for (typename UntypedExpectations::const_reverse_iterator it = untyped_expectations_.rbegin(); it != untyped_expectations_.rend(); ++it) { @@ -1734,7 +1751,7 @@ class FunctionMockerBase : public UntypedFunctionMockerBase { return exp; } } - return NULL; + return nullptr; } // Returns a message that the arguments don't match any expectation. @@ -1756,12 +1773,12 @@ class FunctionMockerBase : public UntypedFunctionMockerBase { ::std::ostream* why) const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { g_gmock_mutex.AssertHeld(); - const int count = static_cast<int>(untyped_expectations_.size()); + const size_t count = untyped_expectations_.size(); *why << "Google Mock tried the following " << count << " " << (count == 1 ? "expectation, but it didn't match" : "expectations, but none matched") << ":\n"; - for (int i = 0; i < count; i++) { + for (size_t i = 0; i < count; i++) { TypedExpectation<F>* const expectation = static_cast<TypedExpectation<F>*>(untyped_expectations_[i].get()); *why << "\n"; @@ -1775,14 +1792,10 @@ class FunctionMockerBase : public UntypedFunctionMockerBase { } } - // The current spec (either default action spec or expectation spec) - // being described on this function mocker. - MockSpec<F> current_spec_; - // There is no generally useful and implementable semantics of // copying a mock object, so copying a mock is usually a user error. // Thus we disallow copying function mockers. If the user really - // wants to copy a mock object, he should implement his own copy + // wants to copy a mock object, they should implement their own copy // operation, for example: // // class MockFoo : public Foo { @@ -1794,9 +1807,7 @@ class FunctionMockerBase : public UntypedFunctionMockerBase { GTEST_DISALLOW_COPY_AND_ASSIGN_(FunctionMockerBase); }; // class FunctionMockerBase -#ifdef _MSC_VER -# pragma warning(pop) // Restores the warning state. -#endif // _MSV_VER +GTEST_DISABLE_MSC_WARNINGS_POP_() // 4355 // Implements methods of FunctionMockerBase. @@ -1806,7 +1817,7 @@ class FunctionMockerBase : public UntypedFunctionMockerBase { // Reports an uninteresting call (whose description is in msg) in the // manner specified by 'reaction'. -void ReportUninterestingCall(CallReaction reaction, const string& msg); +void ReportUninterestingCall(CallReaction reaction, const std::string& msg); } // namespace internal @@ -1841,17 +1852,78 @@ inline Expectation::Expectation(internal::ExpectationBase& exp) // NOLINT } // namespace testing -// A separate macro is required to avoid compile errors when the name -// of the method used in call is a result of macro expansion. -// See CompilesWithMethodNameExpandedFromMacro tests in -// internal/gmock-spec-builders_test.cc for more details. -#define GMOCK_ON_CALL_IMPL_(obj, call) \ - ((obj).gmock_##call).InternalDefaultActionSetAt(__FILE__, __LINE__, \ - #obj, #call) -#define ON_CALL(obj, call) GMOCK_ON_CALL_IMPL_(obj, call) - -#define GMOCK_EXPECT_CALL_IMPL_(obj, call) \ - ((obj).gmock_##call).InternalExpectedAt(__FILE__, __LINE__, #obj, #call) -#define EXPECT_CALL(obj, call) GMOCK_EXPECT_CALL_IMPL_(obj, call) +GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251 + +// Implementation for ON_CALL and EXPECT_CALL macros. A separate macro is +// required to avoid compile errors when the name of the method used in call is +// a result of macro expansion. See CompilesWithMethodNameExpandedFromMacro +// tests in internal/gmock-spec-builders_test.cc for more details. +// +// This macro supports statements both with and without parameter matchers. If +// the parameter list is omitted, gMock will accept any parameters, which allows +// tests to be written that don't need to encode the number of method +// parameter. This technique may only be used for non-overloaded methods. +// +// // These are the same: +// ON_CALL(mock, NoArgsMethod()).WillByDefault(...); +// ON_CALL(mock, NoArgsMethod).WillByDefault(...); +// +// // As are these: +// ON_CALL(mock, TwoArgsMethod(_, _)).WillByDefault(...); +// ON_CALL(mock, TwoArgsMethod).WillByDefault(...); +// +// // Can also specify args if you want, of course: +// ON_CALL(mock, TwoArgsMethod(_, 45)).WillByDefault(...); +// +// // Overloads work as long as you specify parameters: +// ON_CALL(mock, OverloadedMethod(_)).WillByDefault(...); +// ON_CALL(mock, OverloadedMethod(_, _)).WillByDefault(...); +// +// // Oops! Which overload did you want? +// ON_CALL(mock, OverloadedMethod).WillByDefault(...); +// => ERROR: call to member function 'gmock_OverloadedMethod' is ambiguous +// +// How this works: The mock class uses two overloads of the gmock_Method +// expectation setter method plus an operator() overload on the MockSpec object. +// In the matcher list form, the macro expands to: +// +// // This statement: +// ON_CALL(mock, TwoArgsMethod(_, 45))... +// +// // ...expands to: +// mock.gmock_TwoArgsMethod(_, 45)(WithoutMatchers(), nullptr)... +// |-------------v---------------||------------v-------------| +// invokes first overload swallowed by operator() +// +// // ...which is essentially: +// mock.gmock_TwoArgsMethod(_, 45)... +// +// Whereas the form without a matcher list: +// +// // This statement: +// ON_CALL(mock, TwoArgsMethod)... +// +// // ...expands to: +// mock.gmock_TwoArgsMethod(WithoutMatchers(), nullptr)... +// |-----------------------v--------------------------| +// invokes second overload +// +// // ...which is essentially: +// mock.gmock_TwoArgsMethod(_, _)... +// +// The WithoutMatchers() argument is used to disambiguate overloads and to +// block the caller from accidentally invoking the second overload directly. The +// second argument is an internal type derived from the method signature. The +// failure to disambiguate two overloads of this method in the ON_CALL statement +// is how we block callers from setting expectations on overloaded methods. +#define GMOCK_ON_CALL_IMPL_(mock_expr, Setter, call) \ + ((mock_expr).gmock_##call)(::testing::internal::GetWithoutMatchers(), NULL) \ + .Setter(__FILE__, __LINE__, #mock_expr, #call) + +#define ON_CALL(obj, call) \ + GMOCK_ON_CALL_IMPL_(obj, InternalDefaultActionSetAt, call) + +#define EXPECT_CALL(obj, call) \ + GMOCK_ON_CALL_IMPL_(obj, InternalExpectedAt, call) #endif // GMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_ diff --git a/googlemock/include/gmock/gmock.h b/googlemock/include/gmock/gmock.h index 6735c71..dd96226 100644 --- a/googlemock/include/gmock/gmock.h +++ b/googlemock/include/gmock/gmock.h @@ -26,13 +26,14 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // Google Mock - a framework for writing C++ mock classes. // // This is the main header file a user should include. +// GOOGLETEST_CM0002 DO NOT DELETE + #ifndef GMOCK_INCLUDE_GMOCK_GMOCK_H_ #define GMOCK_INCLUDE_GMOCK_GMOCK_H_ @@ -59,8 +60,8 @@ #include "gmock/gmock-cardinalities.h" #include "gmock/gmock-generated-actions.h" #include "gmock/gmock-generated-function-mockers.h" -#include "gmock/gmock-generated-nice-strict.h" #include "gmock/gmock-generated-matchers.h" +#include "gmock/gmock-generated-nice-strict.h" #include "gmock/gmock-matchers.h" #include "gmock/gmock-more-actions.h" #include "gmock/gmock-more-matchers.h" @@ -71,6 +72,7 @@ namespace testing { // Declares Google Mock flags that we want a user to use programmatically. GMOCK_DECLARE_bool_(catch_leaked_mocks); GMOCK_DECLARE_string_(verbose); +GMOCK_DECLARE_int32_(default_mock_behavior); // Initializes Google Mock. This must be called before running the // tests. In particular, it parses the command line for the flags diff --git a/googlemock/include/gmock/internal/custom/README.md b/googlemock/include/gmock/internal/custom/README.md new file mode 100644 index 0000000..f6c93f6 --- /dev/null +++ b/googlemock/include/gmock/internal/custom/README.md @@ -0,0 +1,16 @@ +# Customization Points + +The custom directory is an injection point for custom user configurations. + +## Header `gmock-port.h` + +The following macros can be defined: + +### Flag related macros: + +* `GMOCK_DECLARE_bool_(name)` +* `GMOCK_DECLARE_int32_(name)` +* `GMOCK_DECLARE_string_(name)` +* `GMOCK_DEFINE_bool_(name, default_val, doc)` +* `GMOCK_DEFINE_int32_(name, default_val, doc)` +* `GMOCK_DEFINE_string_(name, default_val, doc)` diff --git a/googlemock/include/gmock/internal/custom/gmock-generated-actions.h b/googlemock/include/gmock/internal/custom/gmock-generated-actions.h index 7dc3b1a..92d910c 100644 --- a/googlemock/include/gmock/internal/custom/gmock-generated-actions.h +++ b/googlemock/include/gmock/internal/custom/gmock-generated-actions.h @@ -2,6 +2,8 @@ // pump.py gmock-generated-actions.h.pump // DO NOT EDIT BY HAND!!! +// GOOGLETEST_CM0002 DO NOT DELETE + #ifndef GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_GENERATED_ACTIONS_H_ #define GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_GENERATED_ACTIONS_H_ diff --git a/googlemock/include/gmock/internal/custom/gmock-generated-actions.h.pump b/googlemock/include/gmock/internal/custom/gmock-generated-actions.h.pump index d26c8a0..67c221f 100644 --- a/googlemock/include/gmock/internal/custom/gmock-generated-actions.h.pump +++ b/googlemock/include/gmock/internal/custom/gmock-generated-actions.h.pump @@ -1,9 +1,11 @@ $$ -*- mode: c++; -*- -$$ This is a Pump source file (http://go/pump). Please use Pump to convert +$$ This is a Pump source file. Please use Pump to convert $$ it to callback-actions.h. $$ $var max_callback_arity = 5 $$}} This meta comment fixes auto-indentation in editors. + +// GOOGLETEST_CM0002 DO NOT DELETE #ifndef GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_GENERATED_ACTIONS_H_ #define GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_GENERATED_ACTIONS_H_ diff --git a/googlemock/include/gmock/internal/custom/gmock-matchers.h b/googlemock/include/gmock/internal/custom/gmock-matchers.h index f2efef9..14aafaa 100644 --- a/googlemock/include/gmock/internal/custom/gmock-matchers.h +++ b/googlemock/include/gmock/internal/custom/gmock-matchers.h @@ -27,13 +27,10 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // -// ============================================================ -// An installation-specific extension point for gmock-matchers.h. -// ============================================================ +// Injection point for custom user configurations. See README for details // -// Adds google3 callback support to CallableTraits. -// -#ifndef GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_CALLBACK_MATCHERS_H_ -#define GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_CALLBACK_MATCHERS_H_ +// GOOGLETEST_CM0002 DO NOT DELETE -#endif // GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_CALLBACK_MATCHERS_H_ +#ifndef GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_MATCHERS_H_ +#define GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_MATCHERS_H_ +#endif // GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_MATCHERS_H_ diff --git a/googlemock/include/gmock/internal/custom/gmock-port.h b/googlemock/include/gmock/internal/custom/gmock-port.h index 9ce8bfe..0030fe9 100644 --- a/googlemock/include/gmock/internal/custom/gmock-port.h +++ b/googlemock/include/gmock/internal/custom/gmock-port.h @@ -27,19 +27,12 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // -// Injection point for custom user configurations. -// The following macros can be defined: -// -// Flag related macros: -// GMOCK_DECLARE_bool_(name) -// GMOCK_DECLARE_int32_(name) -// GMOCK_DECLARE_string_(name) -// GMOCK_DEFINE_bool_(name, default_val, doc) -// GMOCK_DEFINE_int32_(name, default_val, doc) -// GMOCK_DEFINE_string_(name, default_val, doc) +// Injection point for custom user configurations. See README for details // // ** Custom implementation starts here ** +// GOOGLETEST_CM0002 DO NOT DELETE + #ifndef GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_PORT_H_ #define GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_PORT_H_ diff --git a/googlemock/include/gmock/internal/gmock-generated-internal-utils.h b/googlemock/include/gmock/internal/gmock-generated-internal-utils.h index 7811e43..efa0462 100644 --- a/googlemock/include/gmock/internal/gmock-generated-internal-utils.h +++ b/googlemock/include/gmock/internal/gmock-generated-internal-utils.h @@ -30,14 +30,15 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // Google Mock - a framework for writing C++ mock classes. // // This file contains template meta-programming utility classes needed // for implementing Google Mock. +// GOOGLETEST_CM0002 DO NOT DELETE + #ifndef GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_GENERATED_INTERNAL_UTILS_H_ #define GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_GENERATED_INTERNAL_UTILS_H_ @@ -69,70 +70,69 @@ template <typename Tuple> struct MatcherTuple; template <> -struct MatcherTuple< ::testing::tuple<> > { - typedef ::testing::tuple< > type; +struct MatcherTuple< ::std::tuple<> > { + typedef ::std::tuple< > type; }; template <typename A1> -struct MatcherTuple< ::testing::tuple<A1> > { - typedef ::testing::tuple<Matcher<A1> > type; +struct MatcherTuple< ::std::tuple<A1> > { + typedef ::std::tuple<Matcher<A1> > type; }; template <typename A1, typename A2> -struct MatcherTuple< ::testing::tuple<A1, A2> > { - typedef ::testing::tuple<Matcher<A1>, Matcher<A2> > type; +struct MatcherTuple< ::std::tuple<A1, A2> > { + typedef ::std::tuple<Matcher<A1>, Matcher<A2> > type; }; template <typename A1, typename A2, typename A3> -struct MatcherTuple< ::testing::tuple<A1, A2, A3> > { - typedef ::testing::tuple<Matcher<A1>, Matcher<A2>, Matcher<A3> > type; +struct MatcherTuple< ::std::tuple<A1, A2, A3> > { + typedef ::std::tuple<Matcher<A1>, Matcher<A2>, Matcher<A3> > type; }; template <typename A1, typename A2, typename A3, typename A4> -struct MatcherTuple< ::testing::tuple<A1, A2, A3, A4> > { - typedef ::testing::tuple<Matcher<A1>, Matcher<A2>, Matcher<A3>, +struct MatcherTuple< ::std::tuple<A1, A2, A3, A4> > { + typedef ::std::tuple<Matcher<A1>, Matcher<A2>, Matcher<A3>, Matcher<A4> > type; }; template <typename A1, typename A2, typename A3, typename A4, typename A5> -struct MatcherTuple< ::testing::tuple<A1, A2, A3, A4, A5> > { - typedef ::testing::tuple<Matcher<A1>, Matcher<A2>, Matcher<A3>, Matcher<A4>, +struct MatcherTuple< ::std::tuple<A1, A2, A3, A4, A5> > { + typedef ::std::tuple<Matcher<A1>, Matcher<A2>, Matcher<A3>, Matcher<A4>, Matcher<A5> > type; }; template <typename A1, typename A2, typename A3, typename A4, typename A5, typename A6> -struct MatcherTuple< ::testing::tuple<A1, A2, A3, A4, A5, A6> > { - typedef ::testing::tuple<Matcher<A1>, Matcher<A2>, Matcher<A3>, Matcher<A4>, +struct MatcherTuple< ::std::tuple<A1, A2, A3, A4, A5, A6> > { + typedef ::std::tuple<Matcher<A1>, Matcher<A2>, Matcher<A3>, Matcher<A4>, Matcher<A5>, Matcher<A6> > type; }; template <typename A1, typename A2, typename A3, typename A4, typename A5, typename A6, typename A7> -struct MatcherTuple< ::testing::tuple<A1, A2, A3, A4, A5, A6, A7> > { - typedef ::testing::tuple<Matcher<A1>, Matcher<A2>, Matcher<A3>, Matcher<A4>, +struct MatcherTuple< ::std::tuple<A1, A2, A3, A4, A5, A6, A7> > { + typedef ::std::tuple<Matcher<A1>, Matcher<A2>, Matcher<A3>, Matcher<A4>, Matcher<A5>, Matcher<A6>, Matcher<A7> > type; }; template <typename A1, typename A2, typename A3, typename A4, typename A5, typename A6, typename A7, typename A8> -struct MatcherTuple< ::testing::tuple<A1, A2, A3, A4, A5, A6, A7, A8> > { - typedef ::testing::tuple<Matcher<A1>, Matcher<A2>, Matcher<A3>, Matcher<A4>, +struct MatcherTuple< ::std::tuple<A1, A2, A3, A4, A5, A6, A7, A8> > { + typedef ::std::tuple<Matcher<A1>, Matcher<A2>, Matcher<A3>, Matcher<A4>, Matcher<A5>, Matcher<A6>, Matcher<A7>, Matcher<A8> > type; }; template <typename A1, typename A2, typename A3, typename A4, typename A5, typename A6, typename A7, typename A8, typename A9> -struct MatcherTuple< ::testing::tuple<A1, A2, A3, A4, A5, A6, A7, A8, A9> > { - typedef ::testing::tuple<Matcher<A1>, Matcher<A2>, Matcher<A3>, Matcher<A4>, +struct MatcherTuple< ::std::tuple<A1, A2, A3, A4, A5, A6, A7, A8, A9> > { + typedef ::std::tuple<Matcher<A1>, Matcher<A2>, Matcher<A3>, Matcher<A4>, Matcher<A5>, Matcher<A6>, Matcher<A7>, Matcher<A8>, Matcher<A9> > type; }; template <typename A1, typename A2, typename A3, typename A4, typename A5, typename A6, typename A7, typename A8, typename A9, typename A10> -struct MatcherTuple< ::testing::tuple<A1, A2, A3, A4, A5, A6, A7, A8, A9, - A10> > { - typedef ::testing::tuple<Matcher<A1>, Matcher<A2>, Matcher<A3>, Matcher<A4>, +struct MatcherTuple< ::std::tuple<A1, A2, A3, A4, A5, A6, A7, A8, A9, A10> > { + typedef ::std::tuple<Matcher<A1>, Matcher<A2>, Matcher<A3>, Matcher<A4>, Matcher<A5>, Matcher<A6>, Matcher<A7>, Matcher<A8>, Matcher<A9>, Matcher<A10> > type; }; @@ -156,7 +156,7 @@ struct Function; template <typename R> struct Function<R()> { typedef R Result; - typedef ::testing::tuple<> ArgumentTuple; + typedef ::std::tuple<> ArgumentTuple; typedef typename MatcherTuple<ArgumentTuple>::type ArgumentMatcherTuple; typedef void MakeResultVoid(); typedef IgnoredValue MakeResultIgnoredValue(); @@ -166,7 +166,7 @@ template <typename R, typename A1> struct Function<R(A1)> : Function<R()> { typedef A1 Argument1; - typedef ::testing::tuple<A1> ArgumentTuple; + typedef ::std::tuple<A1> ArgumentTuple; typedef typename MatcherTuple<ArgumentTuple>::type ArgumentMatcherTuple; typedef void MakeResultVoid(A1); typedef IgnoredValue MakeResultIgnoredValue(A1); @@ -176,7 +176,7 @@ template <typename R, typename A1, typename A2> struct Function<R(A1, A2)> : Function<R(A1)> { typedef A2 Argument2; - typedef ::testing::tuple<A1, A2> ArgumentTuple; + typedef ::std::tuple<A1, A2> ArgumentTuple; typedef typename MatcherTuple<ArgumentTuple>::type ArgumentMatcherTuple; typedef void MakeResultVoid(A1, A2); typedef IgnoredValue MakeResultIgnoredValue(A1, A2); @@ -186,7 +186,7 @@ template <typename R, typename A1, typename A2, typename A3> struct Function<R(A1, A2, A3)> : Function<R(A1, A2)> { typedef A3 Argument3; - typedef ::testing::tuple<A1, A2, A3> ArgumentTuple; + typedef ::std::tuple<A1, A2, A3> ArgumentTuple; typedef typename MatcherTuple<ArgumentTuple>::type ArgumentMatcherTuple; typedef void MakeResultVoid(A1, A2, A3); typedef IgnoredValue MakeResultIgnoredValue(A1, A2, A3); @@ -196,7 +196,7 @@ template <typename R, typename A1, typename A2, typename A3, typename A4> struct Function<R(A1, A2, A3, A4)> : Function<R(A1, A2, A3)> { typedef A4 Argument4; - typedef ::testing::tuple<A1, A2, A3, A4> ArgumentTuple; + typedef ::std::tuple<A1, A2, A3, A4> ArgumentTuple; typedef typename MatcherTuple<ArgumentTuple>::type ArgumentMatcherTuple; typedef void MakeResultVoid(A1, A2, A3, A4); typedef IgnoredValue MakeResultIgnoredValue(A1, A2, A3, A4); @@ -207,7 +207,7 @@ template <typename R, typename A1, typename A2, typename A3, typename A4, struct Function<R(A1, A2, A3, A4, A5)> : Function<R(A1, A2, A3, A4)> { typedef A5 Argument5; - typedef ::testing::tuple<A1, A2, A3, A4, A5> ArgumentTuple; + typedef ::std::tuple<A1, A2, A3, A4, A5> ArgumentTuple; typedef typename MatcherTuple<ArgumentTuple>::type ArgumentMatcherTuple; typedef void MakeResultVoid(A1, A2, A3, A4, A5); typedef IgnoredValue MakeResultIgnoredValue(A1, A2, A3, A4, A5); @@ -218,7 +218,7 @@ template <typename R, typename A1, typename A2, typename A3, typename A4, struct Function<R(A1, A2, A3, A4, A5, A6)> : Function<R(A1, A2, A3, A4, A5)> { typedef A6 Argument6; - typedef ::testing::tuple<A1, A2, A3, A4, A5, A6> ArgumentTuple; + typedef ::std::tuple<A1, A2, A3, A4, A5, A6> ArgumentTuple; typedef typename MatcherTuple<ArgumentTuple>::type ArgumentMatcherTuple; typedef void MakeResultVoid(A1, A2, A3, A4, A5, A6); typedef IgnoredValue MakeResultIgnoredValue(A1, A2, A3, A4, A5, A6); @@ -229,7 +229,7 @@ template <typename R, typename A1, typename A2, typename A3, typename A4, struct Function<R(A1, A2, A3, A4, A5, A6, A7)> : Function<R(A1, A2, A3, A4, A5, A6)> { typedef A7 Argument7; - typedef ::testing::tuple<A1, A2, A3, A4, A5, A6, A7> ArgumentTuple; + typedef ::std::tuple<A1, A2, A3, A4, A5, A6, A7> ArgumentTuple; typedef typename MatcherTuple<ArgumentTuple>::type ArgumentMatcherTuple; typedef void MakeResultVoid(A1, A2, A3, A4, A5, A6, A7); typedef IgnoredValue MakeResultIgnoredValue(A1, A2, A3, A4, A5, A6, A7); @@ -240,7 +240,7 @@ template <typename R, typename A1, typename A2, typename A3, typename A4, struct Function<R(A1, A2, A3, A4, A5, A6, A7, A8)> : Function<R(A1, A2, A3, A4, A5, A6, A7)> { typedef A8 Argument8; - typedef ::testing::tuple<A1, A2, A3, A4, A5, A6, A7, A8> ArgumentTuple; + typedef ::std::tuple<A1, A2, A3, A4, A5, A6, A7, A8> ArgumentTuple; typedef typename MatcherTuple<ArgumentTuple>::type ArgumentMatcherTuple; typedef void MakeResultVoid(A1, A2, A3, A4, A5, A6, A7, A8); typedef IgnoredValue MakeResultIgnoredValue(A1, A2, A3, A4, A5, A6, A7, A8); @@ -251,7 +251,7 @@ template <typename R, typename A1, typename A2, typename A3, typename A4, struct Function<R(A1, A2, A3, A4, A5, A6, A7, A8, A9)> : Function<R(A1, A2, A3, A4, A5, A6, A7, A8)> { typedef A9 Argument9; - typedef ::testing::tuple<A1, A2, A3, A4, A5, A6, A7, A8, A9> ArgumentTuple; + typedef ::std::tuple<A1, A2, A3, A4, A5, A6, A7, A8, A9> ArgumentTuple; typedef typename MatcherTuple<ArgumentTuple>::type ArgumentMatcherTuple; typedef void MakeResultVoid(A1, A2, A3, A4, A5, A6, A7, A8, A9); typedef IgnoredValue MakeResultIgnoredValue(A1, A2, A3, A4, A5, A6, A7, A8, @@ -264,8 +264,7 @@ template <typename R, typename A1, typename A2, typename A3, typename A4, struct Function<R(A1, A2, A3, A4, A5, A6, A7, A8, A9, A10)> : Function<R(A1, A2, A3, A4, A5, A6, A7, A8, A9)> { typedef A10 Argument10; - typedef ::testing::tuple<A1, A2, A3, A4, A5, A6, A7, A8, A9, - A10> ArgumentTuple; + typedef ::std::tuple<A1, A2, A3, A4, A5, A6, A7, A8, A9, A10> ArgumentTuple; typedef typename MatcherTuple<ArgumentTuple>::type ArgumentMatcherTuple; typedef void MakeResultVoid(A1, A2, A3, A4, A5, A6, A7, A8, A9, A10); typedef IgnoredValue MakeResultIgnoredValue(A1, A2, A3, A4, A5, A6, A7, A8, diff --git a/googlemock/include/gmock/internal/gmock-generated-internal-utils.h.pump b/googlemock/include/gmock/internal/gmock-generated-internal-utils.h.pump index 800af17..9962f6b 100644 --- a/googlemock/include/gmock/internal/gmock-generated-internal-utils.h.pump +++ b/googlemock/include/gmock/internal/gmock-generated-internal-utils.h.pump @@ -31,14 +31,15 @@ $var n = 10 $$ The maximum arity we support. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // Google Mock - a framework for writing C++ mock classes. // // This file contains template meta-programming utility classes needed // for implementing Google Mock. +// GOOGLETEST_CM0002 DO NOT DELETE + #ifndef GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_GENERATED_INTERNAL_UTILS_H_ #define GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_GENERATED_INTERNAL_UTILS_H_ @@ -77,8 +78,8 @@ $var typename_As = [[$for j, [[typename A$j]]]] $var As = [[$for j, [[A$j]]]] $var matcher_As = [[$for j, [[Matcher<A$j>]]]] template <$typename_As> -struct MatcherTuple< ::testing::tuple<$As> > { - typedef ::testing::tuple<$matcher_As > type; +struct MatcherTuple< ::std::tuple<$As> > { + typedef ::std::tuple<$matcher_As > type; }; @@ -102,7 +103,7 @@ struct Function; template <typename R> struct Function<R()> { typedef R Result; - typedef ::testing::tuple<> ArgumentTuple; + typedef ::std::tuple<> ArgumentTuple; typedef typename MatcherTuple<ArgumentTuple>::type ArgumentMatcherTuple; typedef void MakeResultVoid(); typedef IgnoredValue MakeResultIgnoredValue(); @@ -121,7 +122,7 @@ template <typename R$typename_As> struct Function<R($As)> : Function<R($prev_As)> { typedef A$i Argument$i; - typedef ::testing::tuple<$As> ArgumentTuple; + typedef ::std::tuple<$As> ArgumentTuple; typedef typename MatcherTuple<ArgumentTuple>::type ArgumentMatcherTuple; typedef void MakeResultVoid($As); typedef IgnoredValue MakeResultIgnoredValue($As); diff --git a/googlemock/include/gmock/internal/gmock-internal-utils.h b/googlemock/include/gmock/internal/gmock-internal-utils.h index e2ddb05..fd33c00 100644 --- a/googlemock/include/gmock/internal/gmock-internal-utils.h +++ b/googlemock/include/gmock/internal/gmock-internal-utils.h @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // Google Mock - a framework for writing C++ mock classes. // @@ -35,13 +34,14 @@ // Mock. They are subject to change without notice, so please DO NOT // USE THEM IN USER CODE. +// GOOGLETEST_CM0002 DO NOT DELETE + #ifndef GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_INTERNAL_UTILS_H_ #define GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_INTERNAL_UTILS_H_ #include <stdio.h> #include <ostream> // NOLINT #include <string> - #include "gmock/internal/gmock-generated-internal-utils.h" #include "gmock/internal/gmock-port.h" #include "gtest/gtest.h" @@ -49,11 +49,23 @@ namespace testing { namespace internal { +// Silence MSVC C4100 (unreferenced formal parameter) and +// C4805('==': unsafe mix of type 'const int' and type 'const bool') +#ifdef _MSC_VER +# pragma warning(push) +# pragma warning(disable:4100) +# pragma warning(disable:4805) +#endif + +// Joins a vector of strings as if they are fields of a tuple; returns +// the joined string. +GTEST_API_ std::string JoinAsTuple(const Strings& fields); + // Converts an identifier name to a space-separated list of lower-case // words. Each maximum substring of the form [A-Za-z][a-z]*|\d+ is // treated as one word. For example, both "FooBar123" and // "foo_bar_123" are converted to "foo bar 123". -GTEST_API_ string ConvertIdentifierNameToWords(const char* id_name); +GTEST_API_ std::string ConvertIdentifierNameToWords(const char* id_name); // PointeeOf<Pointer>::type is the type of a value pointed to by a // Pointer, which can be either a smart pointer or a raw pointer. The @@ -114,9 +126,11 @@ struct LinkedPtrLessThan { // To gcc, // wchar_t == signed wchar_t != unsigned wchar_t == unsigned int #ifdef __GNUC__ +#if !defined(__WCHAR_UNSIGNED__) // signed/unsigned wchar_t are valid types. # define GMOCK_HAS_SIGNED_WCHAR_T_ 1 #endif +#endif // In what follows, we use the term "kind" to indicate whether a type // is bool, an integer type (excluding bool), a floating-point type, @@ -267,7 +281,7 @@ class FailureReporterInterface { // Reports a failure that occurred at the given source file location. virtual void ReportFailure(FailureType type, const char* file, int line, - const string& message) = 0; + const std::string& message) = 0; }; // Returns the failure reporter used by Google Mock. @@ -279,7 +293,7 @@ GTEST_API_ FailureReporterInterface* GetFailureReporter(); // inline this function to prevent it from showing up in the stack // trace. inline void Assert(bool condition, const char* file, int line, - const string& msg) { + const std::string& msg) { if (!condition) { GetFailureReporter()->ReportFailure(FailureReporterInterface::kFatal, file, line, msg); @@ -292,7 +306,7 @@ inline void Assert(bool condition, const char* file, int line) { // Verifies that condition is true; generates a non-fatal failure if // condition is false. inline void Expect(bool condition, const char* file, int line, - const string& msg) { + const std::string& msg) { if (!condition) { GetFailureReporter()->ReportFailure(FailureReporterInterface::kNonfatal, file, line, msg); @@ -328,11 +342,25 @@ GTEST_API_ bool LogIsVisible(LogSeverity severity); // stack_frames_to_skip is treated as 0, since we don't know which // function calls will be inlined by the compiler and need to be // conservative. -GTEST_API_ void Log(LogSeverity severity, - const string& message, +GTEST_API_ void Log(LogSeverity severity, const std::string& message, int stack_frames_to_skip); -// TODO(wan@google.com): group all type utilities together. +// A marker class that is used to resolve parameterless expectations to the +// correct overload. This must not be instantiable, to prevent client code from +// accidentally resolving to the overload; for example: +// +// ON_CALL(mock, Method({}, nullptr))... +// +class WithoutMatchers { + private: + WithoutMatchers() {} + friend GTEST_API_ WithoutMatchers GetWithoutMatchers(); +}; + +// Internal use only: access the singleton instance of WithoutMatchers. +GTEST_API_ WithoutMatchers GetWithoutMatchers(); + +// FIXME: group all type utilities together. // Type traits. @@ -465,7 +493,7 @@ class StlContainerView<Element[N]> { // This specialization is used when RawContainer is a native array // represented as a (pointer, size) tuple. template <typename ElementPointer, typename Size> -class StlContainerView< ::testing::tuple<ElementPointer, Size> > { +class StlContainerView< ::std::tuple<ElementPointer, Size> > { public: typedef GTEST_REMOVE_CONST_( typename internal::PointeeOf<ElementPointer>::type) RawElement; @@ -473,11 +501,12 @@ class StlContainerView< ::testing::tuple<ElementPointer, Size> > { typedef const type const_reference; static const_reference ConstReference( - const ::testing::tuple<ElementPointer, Size>& array) { - return type(get<0>(array), get<1>(array), RelationToSourceReference()); + const ::std::tuple<ElementPointer, Size>& array) { + return type(std::get<0>(array), std::get<1>(array), + RelationToSourceReference()); } - static type Copy(const ::testing::tuple<ElementPointer, Size>& array) { - return type(get<0>(array), get<1>(array), RelationToSourceCopy()); + static type Copy(const ::std::tuple<ElementPointer, Size>& array) { + return type(std::get<0>(array), std::get<1>(array), RelationToSourceCopy()); } }; @@ -504,8 +533,44 @@ struct RemoveConstFromKey<std::pair<const K, V> > { template <bool kValue> struct BooleanConstant {}; +// Emit an assertion failure due to incorrect DoDefault() usage. Out-of-lined to +// reduce code size. +GTEST_API_ void IllegalDoDefault(const char* file, int line); + +#if GTEST_LANG_CXX11 +// Helper types for Apply() below. +template <size_t... Is> struct int_pack { typedef int_pack type; }; + +template <class Pack, size_t I> struct append; +template <size_t... Is, size_t I> +struct append<int_pack<Is...>, I> : int_pack<Is..., I> {}; + +template <size_t C> +struct make_int_pack : append<typename make_int_pack<C - 1>::type, C - 1> {}; +template <> struct make_int_pack<0> : int_pack<> {}; + +template <typename F, typename Tuple, size_t... Idx> +auto ApplyImpl(F&& f, Tuple&& args, int_pack<Idx...>) -> decltype( + std::forward<F>(f)(std::get<Idx>(std::forward<Tuple>(args))...)) { + return std::forward<F>(f)(std::get<Idx>(std::forward<Tuple>(args))...); +} + +// Apply the function to a tuple of arguments. +template <typename F, typename Tuple> +auto Apply(F&& f, Tuple&& args) + -> decltype(ApplyImpl(std::forward<F>(f), std::forward<Tuple>(args), + make_int_pack<std::tuple_size<Tuple>::value>())) { + return ApplyImpl(std::forward<F>(f), std::forward<Tuple>(args), + make_int_pack<std::tuple_size<Tuple>::value>()); +} +#endif + + +#ifdef _MSC_VER +# pragma warning(pop) +#endif + } // namespace internal } // namespace testing #endif // GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_INTERNAL_UTILS_H_ - diff --git a/googlemock/include/gmock/internal/gmock-port.h b/googlemock/include/gmock/internal/gmock-port.h index 63f4a68..fda27db 100644 --- a/googlemock/include/gmock/internal/gmock-port.h +++ b/googlemock/include/gmock/internal/gmock-port.h @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: vadimb@google.com (Vadim Berman) + // // Low-level types and utilities for porting Google Mock to various // platforms. All macros ending with _ and symbols defined in an @@ -36,6 +35,8 @@ // end with _ are part of Google Mock's public API and can be used by // code outside Google Mock. +// GOOGLETEST_CM0002 DO NOT DELETE + #ifndef GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_PORT_H_ #define GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_PORT_H_ @@ -50,15 +51,11 @@ // portability utilities to Google Test's gtest-port.h instead of // here, as Google Mock depends on Google Test. Only add a utility // here if it's truly specific to Google Mock. + #include "gtest/internal/gtest-linked_ptr.h" #include "gtest/internal/gtest-port.h" #include "gmock/internal/custom/gmock-port.h" -// To avoid conditional compilation everywhere, we make it -// gmock-port.h's responsibility to #include the header implementing -// tr1/tuple. gmock-port.h does this via gtest-port.h, which is -// guaranteed to pull in the tuple header. - // For MS Visual C++, check the compiler version. At least VS 2003 is // required to compile Google Mock. #if defined(_MSC_VER) && _MSC_VER < 1310 @@ -72,18 +69,18 @@ #if !defined(GMOCK_DECLARE_bool_) // Macros for declaring flags. -#define GMOCK_DECLARE_bool_(name) extern GTEST_API_ bool GMOCK_FLAG(name) -#define GMOCK_DECLARE_int32_(name) \ +# define GMOCK_DECLARE_bool_(name) extern GTEST_API_ bool GMOCK_FLAG(name) +# define GMOCK_DECLARE_int32_(name) \ extern GTEST_API_ ::testing::internal::Int32 GMOCK_FLAG(name) -#define GMOCK_DECLARE_string_(name) \ +# define GMOCK_DECLARE_string_(name) \ extern GTEST_API_ ::std::string GMOCK_FLAG(name) // Macros for defining flags. -#define GMOCK_DEFINE_bool_(name, default_val, doc) \ +# define GMOCK_DEFINE_bool_(name, default_val, doc) \ GTEST_API_ bool GMOCK_FLAG(name) = (default_val) -#define GMOCK_DEFINE_int32_(name, default_val, doc) \ +# define GMOCK_DEFINE_int32_(name, default_val, doc) \ GTEST_API_ ::testing::internal::Int32 GMOCK_FLAG(name) = (default_val) -#define GMOCK_DEFINE_string_(name, default_val, doc) \ +# define GMOCK_DEFINE_string_(name, default_val, doc) \ GTEST_API_ ::std::string GMOCK_FLAG(name) = (default_val) #endif // !defined(GMOCK_DECLARE_bool_) diff --git a/googlemock/msvc/2010/gmock.sln b/googlemock/msvc/2010/gmock.sln index d949656..bb48f5b 100644 --- a/googlemock/msvc/2010/gmock.sln +++ b/googlemock/msvc/2010/gmock.sln @@ -10,21 +10,35 @@ EndProject Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Win32 = Debug|Win32
+ Debug|x64 = Debug|x64
Release|Win32 = Release|Win32
+ Release|x64 = Release|x64
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{34681F0D-CE45-415D-B5F2-5C662DFE3BD5}.Debug|Win32.ActiveCfg = Debug|Win32
{34681F0D-CE45-415D-B5F2-5C662DFE3BD5}.Debug|Win32.Build.0 = Debug|Win32
+ {34681F0D-CE45-415D-B5F2-5C662DFE3BD5}.Debug|x64.ActiveCfg = Debug|x64
+ {34681F0D-CE45-415D-B5F2-5C662DFE3BD5}.Debug|x64.Build.0 = Debug|x64
{34681F0D-CE45-415D-B5F2-5C662DFE3BD5}.Release|Win32.ActiveCfg = Release|Win32
{34681F0D-CE45-415D-B5F2-5C662DFE3BD5}.Release|Win32.Build.0 = Release|Win32
+ {34681F0D-CE45-415D-B5F2-5C662DFE3BD5}.Release|x64.ActiveCfg = Release|x64
+ {34681F0D-CE45-415D-B5F2-5C662DFE3BD5}.Release|x64.Build.0 = Release|x64
{F10D22F8-AC7B-4213-8720-608E7D878CD2}.Debug|Win32.ActiveCfg = Debug|Win32
{F10D22F8-AC7B-4213-8720-608E7D878CD2}.Debug|Win32.Build.0 = Debug|Win32
+ {F10D22F8-AC7B-4213-8720-608E7D878CD2}.Debug|x64.ActiveCfg = Debug|x64
+ {F10D22F8-AC7B-4213-8720-608E7D878CD2}.Debug|x64.Build.0 = Debug|x64
{F10D22F8-AC7B-4213-8720-608E7D878CD2}.Release|Win32.ActiveCfg = Release|Win32
{F10D22F8-AC7B-4213-8720-608E7D878CD2}.Release|Win32.Build.0 = Release|Win32
+ {F10D22F8-AC7B-4213-8720-608E7D878CD2}.Release|x64.ActiveCfg = Release|x64
+ {F10D22F8-AC7B-4213-8720-608E7D878CD2}.Release|x64.Build.0 = Release|x64
{E4EF614B-30DF-4954-8C53-580A0BF6B589}.Debug|Win32.ActiveCfg = Debug|Win32
{E4EF614B-30DF-4954-8C53-580A0BF6B589}.Debug|Win32.Build.0 = Debug|Win32
+ {E4EF614B-30DF-4954-8C53-580A0BF6B589}.Debug|x64.ActiveCfg = Debug|x64
+ {E4EF614B-30DF-4954-8C53-580A0BF6B589}.Debug|x64.Build.0 = Debug|x64
{E4EF614B-30DF-4954-8C53-580A0BF6B589}.Release|Win32.ActiveCfg = Release|Win32
{E4EF614B-30DF-4954-8C53-580A0BF6B589}.Release|Win32.Build.0 = Release|Win32
+ {E4EF614B-30DF-4954-8C53-580A0BF6B589}.Release|x64.ActiveCfg = Release|x64
+ {E4EF614B-30DF-4954-8C53-580A0BF6B589}.Release|x64.Build.0 = Release|x64
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
diff --git a/googlemock/msvc/2010/gmock.vcxproj b/googlemock/msvc/2010/gmock.vcxproj index 21a85ef..7bc71d3 100644 --- a/googlemock/msvc/2010/gmock.vcxproj +++ b/googlemock/msvc/2010/gmock.vcxproj @@ -1,14 +1,22 @@ -<?xml version="1.0" encoding="utf-8"?>
+<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
+ <ProjectConfiguration Include="Debug|x64">
+ <Configuration>Debug</Configuration>
+ <Platform>x64</Platform>
+ </ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
+ <ProjectConfiguration Include="Release|x64">
+ <Configuration>Release</Configuration>
+ <Platform>x64</Platform>
+ </ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectGuid>{34681F0D-CE45-415D-B5F2-5C662DFE3BD5}</ProjectGuid>
@@ -20,10 +28,23 @@ <ConfigurationType>StaticLibrary</ConfigurationType>
<CharacterSet>Unicode</CharacterSet>
<WholeProgramOptimization>true</WholeProgramOptimization>
+ <PlatformToolset>v100</PlatformToolset>
+ </PropertyGroup>
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
+ <ConfigurationType>StaticLibrary</ConfigurationType>
+ <CharacterSet>Unicode</CharacterSet>
+ <WholeProgramOptimization>true</WholeProgramOptimization>
+ <PlatformToolset>v100</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>StaticLibrary</ConfigurationType>
<CharacterSet>Unicode</CharacterSet>
+ <PlatformToolset>v100</PlatformToolset>
+ </PropertyGroup>
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
+ <ConfigurationType>StaticLibrary</ConfigurationType>
+ <CharacterSet>Unicode</CharacterSet>
+ <PlatformToolset>v100</PlatformToolset>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
@@ -32,23 +53,39 @@ <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
<Import Project="gmock_config.props" />
</ImportGroup>
+ <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="PropertySheets">
+ <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+ <Import Project="gmock_config.props" />
+ </ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
<Import Project="gmock_config.props" />
</ImportGroup>
+ <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="PropertySheets">
+ <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+ <Import Project="gmock_config.props" />
+ </ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup>
<_ProjectFileVersion>10.0.30319.1</_ProjectFileVersion>
- <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)$(Configuration)\</OutDir>
+ <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)$(Platform)-$(Configuration)\</OutDir>
<IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(OutDir)$(ProjectName)\</IntDir>
- <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)$(Configuration)\</OutDir>
+ <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)$(Platform)-$(Configuration)\</OutDir>
<IntDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(OutDir)$(ProjectName)\</IntDir>
</PropertyGroup>
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
+ <OutDir>$(SolutionDir)$(Platform)-$(Configuration)\</OutDir>
+ <IntDir>$(OutDir)$(ProjectName)\</IntDir>
+ </PropertyGroup>
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
+ <OutDir>$(SolutionDir)$(Platform)-$(Configuration)\</OutDir>
+ <IntDir>$(OutDir)$(ProjectName)\</IntDir>
+ </PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<Optimization>Disabled</Optimization>
<AdditionalIncludeDirectories>..\..\include;..\..;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
- <PreprocessorDefinitions>WIN32;_DEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions>WIN32;_VARIADIC_MAX=10;_DEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<MinimalRebuild>true</MinimalRebuild>
<BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
@@ -58,10 +95,34 @@ <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
</ClCompile>
</ItemDefinitionGroup>
+ <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
+ <ClCompile>
+ <Optimization>Disabled</Optimization>
+ <AdditionalIncludeDirectories>..\..\include;..\..;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <PreprocessorDefinitions>WIN32;_VARIADIC_MAX=10;_DEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
+ <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
+ <PrecompiledHeader>
+ </PrecompiledHeader>
+ <WarningLevel>Level3</WarningLevel>
+ <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
+ </ClCompile>
+ </ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<AdditionalIncludeDirectories>..\..\include;..\..;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
- <PreprocessorDefinitions>WIN32;NDEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions>WIN32;_VARIADIC_MAX=10;NDEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
+ <PrecompiledHeader>
+ </PrecompiledHeader>
+ <WarningLevel>Level3</WarningLevel>
+ <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
+ </ClCompile>
+ </ItemDefinitionGroup>
+ <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
+ <ClCompile>
+ <AdditionalIncludeDirectories>..\..\include;..\..;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <PreprocessorDefinitions>WIN32;_VARIADIC_MAX=10;NDEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
<PrecompiledHeader>
</PrecompiledHeader>
@@ -73,10 +134,12 @@ <ClCompile Include="..\..\src\gmock-all.cc" />
<ClCompile Include="$(GTestDir)\src\gtest-all.cc">
<AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(GTestDir);%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(GTestDir);%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(GTestDir);%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(GTestDir);%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
</ClCompile>
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
-</Project>
+</Project>
\ No newline at end of file diff --git a/googlemock/msvc/2010/gmock_config.props b/googlemock/msvc/2010/gmock_config.props index 441f31c..017d710 100644 --- a/googlemock/msvc/2010/gmock_config.props +++ b/googlemock/msvc/2010/gmock_config.props @@ -1,4 +1,4 @@ -<?xml version="1.0" encoding="utf-8"?>
+<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup Label="UserMacros">
<GTestDir>../../../googletest</GTestDir>
@@ -16,4 +16,4 @@ <Value>$(GTestDir)</Value>
</BuildMacro>
</ItemGroup>
-</Project>
+</Project>
\ No newline at end of file diff --git a/googlemock/msvc/2010/gmock_main.vcxproj b/googlemock/msvc/2010/gmock_main.vcxproj index 27fecd5..43da043 100644 --- a/googlemock/msvc/2010/gmock_main.vcxproj +++ b/googlemock/msvc/2010/gmock_main.vcxproj @@ -1,14 +1,22 @@ -<?xml version="1.0" encoding="utf-8"?>
+<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
+ <ProjectConfiguration Include="Debug|x64">
+ <Configuration>Debug</Configuration>
+ <Platform>x64</Platform>
+ </ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
+ <ProjectConfiguration Include="Release|x64">
+ <Configuration>Release</Configuration>
+ <Platform>x64</Platform>
+ </ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectGuid>{E4EF614B-30DF-4954-8C53-580A0BF6B589}</ProjectGuid>
@@ -20,10 +28,23 @@ <ConfigurationType>StaticLibrary</ConfigurationType>
<CharacterSet>Unicode</CharacterSet>
<WholeProgramOptimization>true</WholeProgramOptimization>
+ <PlatformToolset>v100</PlatformToolset>
+ </PropertyGroup>
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
+ <ConfigurationType>StaticLibrary</ConfigurationType>
+ <CharacterSet>Unicode</CharacterSet>
+ <WholeProgramOptimization>true</WholeProgramOptimization>
+ <PlatformToolset>v100</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>StaticLibrary</ConfigurationType>
<CharacterSet>Unicode</CharacterSet>
+ <PlatformToolset>v100</PlatformToolset>
+ </PropertyGroup>
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
+ <ConfigurationType>StaticLibrary</ConfigurationType>
+ <CharacterSet>Unicode</CharacterSet>
+ <PlatformToolset>v100</PlatformToolset>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
@@ -32,23 +53,39 @@ <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
<Import Project="gmock_config.props" />
</ImportGroup>
+ <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="PropertySheets">
+ <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+ <Import Project="gmock_config.props" />
+ </ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
<Import Project="gmock_config.props" />
</ImportGroup>
+ <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="PropertySheets">
+ <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+ <Import Project="gmock_config.props" />
+ </ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup>
<_ProjectFileVersion>10.0.30319.1</_ProjectFileVersion>
- <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)$(Configuration)\</OutDir>
+ <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)$(Platform)-$(Configuration)\</OutDir>
<IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(OutDir)$(ProjectName)\</IntDir>
- <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)$(Configuration)\</OutDir>
+ <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)$(Platform)-$(Configuration)\</OutDir>
<IntDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(OutDir)$(ProjectName)\</IntDir>
</PropertyGroup>
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
+ <OutDir>$(SolutionDir)$(Platform)-$(Configuration)\</OutDir>
+ <IntDir>$(OutDir)$(ProjectName)\</IntDir>
+ </PropertyGroup>
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
+ <OutDir>$(SolutionDir)$(Platform)-$(Configuration)\</OutDir>
+ <IntDir>$(OutDir)$(ProjectName)\</IntDir>
+ </PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<Optimization>Disabled</Optimization>
<AdditionalIncludeDirectories>../../include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
- <PreprocessorDefinitions>WIN32;_DEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions>WIN32;_VARIADIC_MAX=10;_DEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<MinimalRebuild>true</MinimalRebuild>
<BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
@@ -58,10 +95,34 @@ <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
</ClCompile>
</ItemDefinitionGroup>
+ <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
+ <ClCompile>
+ <Optimization>Disabled</Optimization>
+ <AdditionalIncludeDirectories>../../include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <PreprocessorDefinitions>WIN32;_VARIADIC_MAX=10;_DEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
+ <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
+ <PrecompiledHeader>
+ </PrecompiledHeader>
+ <WarningLevel>Level3</WarningLevel>
+ <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
+ </ClCompile>
+ </ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<AdditionalIncludeDirectories>../../include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
- <PreprocessorDefinitions>WIN32;NDEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions>WIN32;_VARIADIC_MAX=10;NDEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
+ <PrecompiledHeader>
+ </PrecompiledHeader>
+ <WarningLevel>Level3</WarningLevel>
+ <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
+ </ClCompile>
+ </ItemDefinitionGroup>
+ <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
+ <ClCompile>
+ <AdditionalIncludeDirectories>../../include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <PreprocessorDefinitions>WIN32;_VARIADIC_MAX=10;NDEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
<PrecompiledHeader>
</PrecompiledHeader>
@@ -79,10 +140,12 @@ <ItemGroup>
<ClCompile Include="..\..\src\gmock_main.cc">
<AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">../../include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">../../include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">../../include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release|x64'">../../include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
</ClCompile>
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
-</Project>
+</Project>
\ No newline at end of file diff --git a/googlemock/msvc/2010/gmock_test.vcxproj b/googlemock/msvc/2010/gmock_test.vcxproj index 265439e..dcbeb58 100644 --- a/googlemock/msvc/2010/gmock_test.vcxproj +++ b/googlemock/msvc/2010/gmock_test.vcxproj @@ -1,14 +1,22 @@ -<?xml version="1.0" encoding="utf-8"?>
+<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
+ <ProjectConfiguration Include="Debug|x64">
+ <Configuration>Debug</Configuration>
+ <Platform>x64</Platform>
+ </ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
+ <ProjectConfiguration Include="Release|x64">
+ <Configuration>Release</Configuration>
+ <Platform>x64</Platform>
+ </ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectGuid>{F10D22F8-AC7B-4213-8720-608E7D878CD2}</ProjectGuid>
@@ -20,10 +28,23 @@ <ConfigurationType>Application</ConfigurationType>
<CharacterSet>Unicode</CharacterSet>
<WholeProgramOptimization>true</WholeProgramOptimization>
+ <PlatformToolset>v100</PlatformToolset>
+ </PropertyGroup>
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
+ <ConfigurationType>Application</ConfigurationType>
+ <CharacterSet>Unicode</CharacterSet>
+ <WholeProgramOptimization>true</WholeProgramOptimization>
+ <PlatformToolset>v100</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<CharacterSet>Unicode</CharacterSet>
+ <PlatformToolset>v100</PlatformToolset>
+ </PropertyGroup>
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
+ <ConfigurationType>Application</ConfigurationType>
+ <CharacterSet>Unicode</CharacterSet>
+ <PlatformToolset>v100</PlatformToolset>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
@@ -32,26 +53,44 @@ <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
<Import Project="gmock_config.props" />
</ImportGroup>
+ <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="PropertySheets">
+ <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+ <Import Project="gmock_config.props" />
+ </ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
<Import Project="gmock_config.props" />
</ImportGroup>
+ <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="PropertySheets">
+ <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+ <Import Project="gmock_config.props" />
+ </ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup>
<_ProjectFileVersion>10.0.30319.1</_ProjectFileVersion>
- <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)$(Configuration)\</OutDir>
+ <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)$(Platform)-$(Configuration)\</OutDir>
<IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(OutDir)$(ProjectName)\</IntDir>
<LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</LinkIncremental>
- <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)$(Configuration)\</OutDir>
+ <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</LinkIncremental>
+ <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)$(Platform)-$(Configuration)\</OutDir>
<IntDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(OutDir)$(ProjectName)\</IntDir>
<LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">false</LinkIncremental>
+ <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Release|x64'">false</LinkIncremental>
+ </PropertyGroup>
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
+ <OutDir>$(SolutionDir)$(Platform)-$(Configuration)\</OutDir>
+ <IntDir>$(OutDir)$(ProjectName)\</IntDir>
+ </PropertyGroup>
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
+ <OutDir>$(SolutionDir)$(Platform)-$(Configuration)\</OutDir>
+ <IntDir>$(OutDir)$(ProjectName)\</IntDir>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<AdditionalOptions>/bigobj %(AdditionalOptions)</AdditionalOptions>
<Optimization>Disabled</Optimization>
- <AdditionalIncludeDirectories>..\..\include;..\..;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
- <PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <AdditionalIncludeDirectories>..\..\include;..\..;$(GTestDir);%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <PreprocessorDefinitions>WIN32;_VARIADIC_MAX=10;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<MinimalRebuild>true</MinimalRebuild>
<BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
@@ -66,11 +105,29 @@ <TargetMachine>MachineX86</TargetMachine>
</Link>
</ItemDefinitionGroup>
+ <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
+ <ClCompile>
+ <AdditionalOptions>/bigobj %(AdditionalOptions)</AdditionalOptions>
+ <Optimization>Disabled</Optimization>
+ <AdditionalIncludeDirectories>..\..\include;..\..;$(GTestDir);%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <PreprocessorDefinitions>WIN32;_VARIADIC_MAX=10;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
+ <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
+ <PrecompiledHeader>
+ </PrecompiledHeader>
+ <WarningLevel>Level3</WarningLevel>
+ <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
+ </ClCompile>
+ <Link>
+ <GenerateDebugInformation>true</GenerateDebugInformation>
+ <SubSystem>Console</SubSystem>
+ </Link>
+ </ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<AdditionalOptions>/bigobj %(AdditionalOptions)</AdditionalOptions>
- <AdditionalIncludeDirectories>..\..\include;..\..;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
- <PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <AdditionalIncludeDirectories>..\..\include;..\..;$(GTestDir);%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <PreprocessorDefinitions>WIN32;_VARIADIC_MAX=10;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
<PrecompiledHeader>
</PrecompiledHeader>
@@ -85,6 +142,24 @@ <TargetMachine>MachineX86</TargetMachine>
</Link>
</ItemDefinitionGroup>
+ <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
+ <ClCompile>
+ <AdditionalOptions>/bigobj %(AdditionalOptions)</AdditionalOptions>
+ <AdditionalIncludeDirectories>..\..\include;..\..;$(GTestDir);%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <PreprocessorDefinitions>WIN32;_VARIADIC_MAX=10;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
+ <PrecompiledHeader>
+ </PrecompiledHeader>
+ <WarningLevel>Level3</WarningLevel>
+ <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
+ </ClCompile>
+ <Link>
+ <GenerateDebugInformation>true</GenerateDebugInformation>
+ <SubSystem>Console</SubSystem>
+ <OptimizeReferences>true</OptimizeReferences>
+ <EnableCOMDATFolding>true</EnableCOMDATFolding>
+ </Link>
+ </ItemDefinitionGroup>
<ItemGroup>
<ProjectReference Include="gmock_main.vcxproj">
<Project>{e4ef614b-30df-4954-8c53-580a0bf6b589}</Project>
@@ -98,4 +173,4 @@ <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
-</Project>
+</Project>
\ No newline at end of file diff --git a/googlemock/msvc/2015/gmock.sln b/googlemock/msvc/2015/gmock.sln index c59e07f..d4203a8 100644 --- a/googlemock/msvc/2015/gmock.sln +++ b/googlemock/msvc/2015/gmock.sln @@ -10,21 +10,35 @@ EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Win32 = Debug|Win32 + Debug|x64 = Debug|x64 Release|Win32 = Release|Win32 + Release|x64 = Release|x64 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {34681F0D-CE45-415D-B5F2-5C662DFE3BD5}.Debug|Win32.ActiveCfg = Debug|Win32 {34681F0D-CE45-415D-B5F2-5C662DFE3BD5}.Debug|Win32.Build.0 = Debug|Win32 + {34681F0D-CE45-415D-B5F2-5C662DFE3BD5}.Debug|x64.ActiveCfg = Debug|x64 + {34681F0D-CE45-415D-B5F2-5C662DFE3BD5}.Debug|x64.Build.0 = Debug|x64 {34681F0D-CE45-415D-B5F2-5C662DFE3BD5}.Release|Win32.ActiveCfg = Release|Win32 {34681F0D-CE45-415D-B5F2-5C662DFE3BD5}.Release|Win32.Build.0 = Release|Win32 + {34681F0D-CE45-415D-B5F2-5C662DFE3BD5}.Release|x64.ActiveCfg = Release|x64 + {34681F0D-CE45-415D-B5F2-5C662DFE3BD5}.Release|x64.Build.0 = Release|x64 {F10D22F8-AC7B-4213-8720-608E7D878CD2}.Debug|Win32.ActiveCfg = Debug|Win32 {F10D22F8-AC7B-4213-8720-608E7D878CD2}.Debug|Win32.Build.0 = Debug|Win32 + {F10D22F8-AC7B-4213-8720-608E7D878CD2}.Debug|x64.ActiveCfg = Debug|x64 + {F10D22F8-AC7B-4213-8720-608E7D878CD2}.Debug|x64.Build.0 = Debug|x64 {F10D22F8-AC7B-4213-8720-608E7D878CD2}.Release|Win32.ActiveCfg = Release|Win32 {F10D22F8-AC7B-4213-8720-608E7D878CD2}.Release|Win32.Build.0 = Release|Win32 + {F10D22F8-AC7B-4213-8720-608E7D878CD2}.Release|x64.ActiveCfg = Release|x64 + {F10D22F8-AC7B-4213-8720-608E7D878CD2}.Release|x64.Build.0 = Release|x64 {E4EF614B-30DF-4954-8C53-580A0BF6B589}.Debug|Win32.ActiveCfg = Debug|Win32 {E4EF614B-30DF-4954-8C53-580A0BF6B589}.Debug|Win32.Build.0 = Debug|Win32 + {E4EF614B-30DF-4954-8C53-580A0BF6B589}.Debug|x64.ActiveCfg = Debug|x64 + {E4EF614B-30DF-4954-8C53-580A0BF6B589}.Debug|x64.Build.0 = Debug|x64 {E4EF614B-30DF-4954-8C53-580A0BF6B589}.Release|Win32.ActiveCfg = Release|Win32 {E4EF614B-30DF-4954-8C53-580A0BF6B589}.Release|Win32.Build.0 = Release|Win32 + {E4EF614B-30DF-4954-8C53-580A0BF6B589}.Release|x64.ActiveCfg = Release|x64 + {E4EF614B-30DF-4954-8C53-580A0BF6B589}.Release|x64.Build.0 = Release|x64 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/googlemock/msvc/2015/gmock.vcxproj b/googlemock/msvc/2015/gmock.vcxproj index d5ddd09..c6b56e6 100644 --- a/googlemock/msvc/2015/gmock.vcxproj +++ b/googlemock/msvc/2015/gmock.vcxproj @@ -5,10 +5,18 @@ <Configuration>Debug</Configuration> <Platform>Win32</Platform> </ProjectConfiguration> + <ProjectConfiguration Include="Debug|x64"> + <Configuration>Debug</Configuration> + <Platform>x64</Platform> + </ProjectConfiguration> <ProjectConfiguration Include="Release|Win32"> <Configuration>Release</Configuration> <Platform>Win32</Platform> </ProjectConfiguration> + <ProjectConfiguration Include="Release|x64"> + <Configuration>Release</Configuration> + <Platform>x64</Platform> + </ProjectConfiguration> </ItemGroup> <PropertyGroup Label="Globals"> <ProjectGuid>{34681F0D-CE45-415D-B5F2-5C662DFE3BD5}</ProjectGuid> @@ -22,11 +30,22 @@ <WholeProgramOptimization>true</WholeProgramOptimization> <PlatformToolset>v140</PlatformToolset> </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration"> + <ConfigurationType>StaticLibrary</ConfigurationType> + <CharacterSet>Unicode</CharacterSet> + <WholeProgramOptimization>true</WholeProgramOptimization> + <PlatformToolset>v140</PlatformToolset> + </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration"> <ConfigurationType>StaticLibrary</ConfigurationType> <CharacterSet>Unicode</CharacterSet> <PlatformToolset>v140</PlatformToolset> </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration"> + <ConfigurationType>StaticLibrary</ConfigurationType> + <CharacterSet>Unicode</CharacterSet> + <PlatformToolset>v140</PlatformToolset> + </PropertyGroup> <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" /> <ImportGroup Label="ExtensionSettings"> </ImportGroup> @@ -34,18 +53,34 @@ <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> <Import Project="gmock_config.props" /> </ImportGroup> + <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="PropertySheets"> + <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> + <Import Project="gmock_config.props" /> + </ImportGroup> <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="PropertySheets"> <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> <Import Project="gmock_config.props" /> </ImportGroup> + <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="PropertySheets"> + <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> + <Import Project="gmock_config.props" /> + </ImportGroup> <PropertyGroup Label="UserMacros" /> <PropertyGroup> <_ProjectFileVersion>10.0.30319.1</_ProjectFileVersion> - <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)$(Configuration)\</OutDir> + <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)$(Platform)-$(Configuration)\</OutDir> <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(OutDir)$(ProjectName)\</IntDir> - <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)$(Configuration)\</OutDir> + <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)$(Platform)-$(Configuration)\</OutDir> <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(OutDir)$(ProjectName)\</IntDir> </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'"> + <OutDir>$(SolutionDir)$(Platform)-$(Configuration)\</OutDir> + <IntDir>$(OutDir)$(ProjectName)\</IntDir> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'"> + <OutDir>$(SolutionDir)$(Platform)-$(Configuration)\</OutDir> + <IntDir>$(OutDir)$(ProjectName)\</IntDir> + </PropertyGroup> <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> <ClCompile> <Optimization>Disabled</Optimization> @@ -60,6 +95,19 @@ <DebugInformationFormat>ProgramDatabase</DebugInformationFormat> </ClCompile> </ItemDefinitionGroup> + <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'"> + <ClCompile> + <Optimization>Disabled</Optimization> + <AdditionalIncludeDirectories>..\..\include;..\..;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories> + <PreprocessorDefinitions>WIN32;_DEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions> + <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks> + <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary> + <PrecompiledHeader> + </PrecompiledHeader> + <WarningLevel>Level3</WarningLevel> + <DebugInformationFormat>ProgramDatabase</DebugInformationFormat> + </ClCompile> + </ItemDefinitionGroup> <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'"> <ClCompile> <AdditionalIncludeDirectories>..\..\include;..\..;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories> @@ -71,11 +119,24 @@ <DebugInformationFormat>ProgramDatabase</DebugInformationFormat> </ClCompile> </ItemDefinitionGroup> + <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'"> + <ClCompile> + <AdditionalIncludeDirectories>..\..\include;..\..;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories> + <PreprocessorDefinitions>WIN32;NDEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions> + <RuntimeLibrary>MultiThreaded</RuntimeLibrary> + <PrecompiledHeader> + </PrecompiledHeader> + <WarningLevel>Level3</WarningLevel> + <DebugInformationFormat>ProgramDatabase</DebugInformationFormat> + </ClCompile> + </ItemDefinitionGroup> <ItemGroup> <ClCompile Include="..\..\src\gmock-all.cc" /> <ClCompile Include="$(GTestDir)\src\gtest-all.cc"> <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(GTestDir);%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories> + <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(GTestDir);%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories> <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(GTestDir);%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories> + <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(GTestDir);%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories> </ClCompile> </ItemGroup> <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" /> diff --git a/googlemock/msvc/2015/gmock_main.vcxproj b/googlemock/msvc/2015/gmock_main.vcxproj index 76cc68b..42381df 100644 --- a/googlemock/msvc/2015/gmock_main.vcxproj +++ b/googlemock/msvc/2015/gmock_main.vcxproj @@ -5,10 +5,18 @@ <Configuration>Debug</Configuration> <Platform>Win32</Platform> </ProjectConfiguration> + <ProjectConfiguration Include="Debug|x64"> + <Configuration>Debug</Configuration> + <Platform>x64</Platform> + </ProjectConfiguration> <ProjectConfiguration Include="Release|Win32"> <Configuration>Release</Configuration> <Platform>Win32</Platform> </ProjectConfiguration> + <ProjectConfiguration Include="Release|x64"> + <Configuration>Release</Configuration> + <Platform>x64</Platform> + </ProjectConfiguration> </ItemGroup> <PropertyGroup Label="Globals"> <ProjectGuid>{E4EF614B-30DF-4954-8C53-580A0BF6B589}</ProjectGuid> @@ -22,11 +30,22 @@ <WholeProgramOptimization>true</WholeProgramOptimization> <PlatformToolset>v140</PlatformToolset> </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration"> + <ConfigurationType>StaticLibrary</ConfigurationType> + <CharacterSet>Unicode</CharacterSet> + <WholeProgramOptimization>true</WholeProgramOptimization> + <PlatformToolset>v140</PlatformToolset> + </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration"> <ConfigurationType>StaticLibrary</ConfigurationType> <CharacterSet>Unicode</CharacterSet> <PlatformToolset>v140</PlatformToolset> </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration"> + <ConfigurationType>StaticLibrary</ConfigurationType> + <CharacterSet>Unicode</CharacterSet> + <PlatformToolset>v140</PlatformToolset> + </PropertyGroup> <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" /> <ImportGroup Label="ExtensionSettings"> </ImportGroup> @@ -34,18 +53,34 @@ <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> <Import Project="gmock_config.props" /> </ImportGroup> + <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="PropertySheets"> + <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> + <Import Project="gmock_config.props" /> + </ImportGroup> <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="PropertySheets"> <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> <Import Project="gmock_config.props" /> </ImportGroup> + <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="PropertySheets"> + <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> + <Import Project="gmock_config.props" /> + </ImportGroup> <PropertyGroup Label="UserMacros" /> <PropertyGroup> <_ProjectFileVersion>10.0.30319.1</_ProjectFileVersion> - <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)$(Configuration)\</OutDir> + <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)$(Platform)-$(Configuration)\</OutDir> <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(OutDir)$(ProjectName)\</IntDir> - <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)$(Configuration)\</OutDir> + <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)$(Platform)-$(Configuration)\</OutDir> <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(OutDir)$(ProjectName)\</IntDir> </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'"> + <OutDir>$(SolutionDir)$(Platform)-$(Configuration)\</OutDir> + <IntDir>$(OutDir)$(ProjectName)\</IntDir> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'"> + <OutDir>$(SolutionDir)$(Platform)-$(Configuration)\</OutDir> + <IntDir>$(OutDir)$(ProjectName)\</IntDir> + </PropertyGroup> <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> <ClCompile> <Optimization>Disabled</Optimization> @@ -60,6 +95,19 @@ <DebugInformationFormat>ProgramDatabase</DebugInformationFormat> </ClCompile> </ItemDefinitionGroup> + <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'"> + <ClCompile> + <Optimization>Disabled</Optimization> + <AdditionalIncludeDirectories>../../include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories> + <PreprocessorDefinitions>WIN32;_DEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions> + <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks> + <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary> + <PrecompiledHeader> + </PrecompiledHeader> + <WarningLevel>Level3</WarningLevel> + <DebugInformationFormat>ProgramDatabase</DebugInformationFormat> + </ClCompile> + </ItemDefinitionGroup> <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'"> <ClCompile> <AdditionalIncludeDirectories>../../include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories> @@ -71,6 +119,17 @@ <DebugInformationFormat>ProgramDatabase</DebugInformationFormat> </ClCompile> </ItemDefinitionGroup> + <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'"> + <ClCompile> + <AdditionalIncludeDirectories>../../include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories> + <PreprocessorDefinitions>WIN32;NDEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions> + <RuntimeLibrary>MultiThreaded</RuntimeLibrary> + <PrecompiledHeader> + </PrecompiledHeader> + <WarningLevel>Level3</WarningLevel> + <DebugInformationFormat>ProgramDatabase</DebugInformationFormat> + </ClCompile> + </ItemDefinitionGroup> <ItemGroup> <ProjectReference Include="gmock.vcxproj"> <Project>{34681f0d-ce45-415d-b5f2-5c662dfe3bd5}</Project> @@ -81,7 +140,9 @@ <ItemGroup> <ClCompile Include="..\..\src\gmock_main.cc"> <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">../../include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories> + <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">../../include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories> <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">../../include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories> + <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release|x64'">../../include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories> </ClCompile> </ItemGroup> <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" /> diff --git a/googlemock/msvc/2015/gmock_test.vcxproj b/googlemock/msvc/2015/gmock_test.vcxproj index 76ea553..01d1f20 100644 --- a/googlemock/msvc/2015/gmock_test.vcxproj +++ b/googlemock/msvc/2015/gmock_test.vcxproj @@ -5,10 +5,18 @@ <Configuration>Debug</Configuration> <Platform>Win32</Platform> </ProjectConfiguration> + <ProjectConfiguration Include="Debug|x64"> + <Configuration>Debug</Configuration> + <Platform>x64</Platform> + </ProjectConfiguration> <ProjectConfiguration Include="Release|Win32"> <Configuration>Release</Configuration> <Platform>Win32</Platform> </ProjectConfiguration> + <ProjectConfiguration Include="Release|x64"> + <Configuration>Release</Configuration> + <Platform>x64</Platform> + </ProjectConfiguration> </ItemGroup> <PropertyGroup Label="Globals"> <ProjectGuid>{F10D22F8-AC7B-4213-8720-608E7D878CD2}</ProjectGuid> @@ -22,11 +30,22 @@ <WholeProgramOptimization>true</WholeProgramOptimization> <PlatformToolset>v140</PlatformToolset> </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration"> + <ConfigurationType>Application</ConfigurationType> + <CharacterSet>Unicode</CharacterSet> + <WholeProgramOptimization>true</WholeProgramOptimization> + <PlatformToolset>v140</PlatformToolset> + </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration"> <ConfigurationType>Application</ConfigurationType> <CharacterSet>Unicode</CharacterSet> <PlatformToolset>v140</PlatformToolset> </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration"> + <ConfigurationType>Application</ConfigurationType> + <CharacterSet>Unicode</CharacterSet> + <PlatformToolset>v140</PlatformToolset> + </PropertyGroup> <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" /> <ImportGroup Label="ExtensionSettings"> </ImportGroup> @@ -34,19 +53,37 @@ <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> <Import Project="gmock_config.props" /> </ImportGroup> + <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="PropertySheets"> + <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> + <Import Project="gmock_config.props" /> + </ImportGroup> <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="PropertySheets"> <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> <Import Project="gmock_config.props" /> </ImportGroup> + <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="PropertySheets"> + <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> + <Import Project="gmock_config.props" /> + </ImportGroup> <PropertyGroup Label="UserMacros" /> <PropertyGroup> <_ProjectFileVersion>10.0.30319.1</_ProjectFileVersion> - <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)$(Configuration)\</OutDir> + <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)$(Platform)-$(Configuration)\</OutDir> <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(OutDir)$(ProjectName)\</IntDir> <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</LinkIncremental> - <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)$(Configuration)\</OutDir> + <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</LinkIncremental> + <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)$(Platform)-$(Configuration)\</OutDir> <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(OutDir)$(ProjectName)\</IntDir> <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">false</LinkIncremental> + <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Release|x64'">false</LinkIncremental> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'"> + <OutDir>$(SolutionDir)$(Platform)-$(Configuration)\</OutDir> + <IntDir>$(OutDir)$(ProjectName)\</IntDir> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'"> + <OutDir>$(SolutionDir)$(Platform)-$(Configuration)\</OutDir> + <IntDir>$(OutDir)$(ProjectName)\</IntDir> </PropertyGroup> <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> <ClCompile> @@ -68,10 +105,28 @@ <TargetMachine>MachineX86</TargetMachine> </Link> </ItemDefinitionGroup> + <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'"> + <ClCompile> + <AdditionalOptions>/bigobj %(AdditionalOptions)</AdditionalOptions> + <Optimization>Disabled</Optimization> + <AdditionalIncludeDirectories>..\..\include;..\..;$(GTestDir);%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories> + <PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions> + <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks> + <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary> + <PrecompiledHeader> + </PrecompiledHeader> + <WarningLevel>Level3</WarningLevel> + <DebugInformationFormat>ProgramDatabase</DebugInformationFormat> + </ClCompile> + <Link> + <GenerateDebugInformation>true</GenerateDebugInformation> + <SubSystem>Console</SubSystem> + </Link> + </ItemDefinitionGroup> <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'"> <ClCompile> <AdditionalOptions>/bigobj %(AdditionalOptions)</AdditionalOptions> - <AdditionalIncludeDirectories>..\..\include;..\..;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories> + <AdditionalIncludeDirectories>..\..\include;..\..;$(GTestDir);%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories> <PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions> <RuntimeLibrary>MultiThreaded</RuntimeLibrary> <PrecompiledHeader> @@ -87,6 +142,24 @@ <TargetMachine>MachineX86</TargetMachine> </Link> </ItemDefinitionGroup> + <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'"> + <ClCompile> + <AdditionalOptions>/bigobj %(AdditionalOptions)</AdditionalOptions> + <AdditionalIncludeDirectories>..\..\include;..\..;$(GTestDir);%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories> + <PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions> + <RuntimeLibrary>MultiThreaded</RuntimeLibrary> + <PrecompiledHeader> + </PrecompiledHeader> + <WarningLevel>Level3</WarningLevel> + <DebugInformationFormat>ProgramDatabase</DebugInformationFormat> + </ClCompile> + <Link> + <GenerateDebugInformation>true</GenerateDebugInformation> + <SubSystem>Console</SubSystem> + <OptimizeReferences>true</OptimizeReferences> + <EnableCOMDATFolding>true</EnableCOMDATFolding> + </Link> + </ItemDefinitionGroup> <ItemGroup> <ProjectReference Include="gmock_main.vcxproj"> <Project>{e4ef614b-30df-4954-8c53-580a0bf6b589}</Project> diff --git a/googlemock/scripts/fuse_gmock_files.py b/googlemock/scripts/fuse_gmock_files.py index cb7fdf2..9b6956f 100755 --- a/googlemock/scripts/fuse_gmock_files.py +++ b/googlemock/scripts/fuse_gmock_files.py @@ -55,7 +55,7 @@ EXAMPLES This tool is experimental. In particular, it assumes that there is no conditional inclusion of Google Mock or Google Test headers. Please report any problems to googlemock@googlegroups.com. You can read -http://code.google.com/p/googlemock/wiki/CookBook for more +https://github.com/google/googletest/blob/master/googlemock/docs/CookBook.md for more information. """ diff --git a/googlemock/scripts/generator/README b/googlemock/scripts/generator/README index d6f9597..01fd463 100644 --- a/googlemock/scripts/generator/README +++ b/googlemock/scripts/generator/README @@ -1,11 +1,10 @@ The Google Mock class generator is an application that is part of cppclean. -For more information about cppclean, see the README.cppclean file or -visit http://code.google.com/p/cppclean/ +For more information about cppclean, visit http://code.google.com/p/cppclean/ -cppclean requires Python 2.3.5 or later. If you don't have Python installed -on your system, you will also need to install it. You can download Python -from: http://www.python.org/download/releases/ +The mock generator requires Python 2.3.5 or later. If you don't have Python +installed on your system, you will also need to install it. You can download +Python from: http://www.python.org/download/releases/ To use the Google Mock class generator, you need to call it on the command line passing the header file and class for which you want diff --git a/googlemock/scripts/generator/cpp/ast.py b/googlemock/scripts/generator/cpp/ast.py index 11cbe91..f14728b 100755 --- a/googlemock/scripts/generator/cpp/ast.py +++ b/googlemock/scripts/generator/cpp/ast.py @@ -338,7 +338,7 @@ class Class(_GenericDeclaration): # TODO(nnorwitz): handle namespaces, etc. if self.bases: for token_list in self.bases: - # TODO(nnorwitz): bases are tokens, do name comparision. + # TODO(nnorwitz): bases are tokens, do name comparison. for token in token_list: if token.name == node.name: return True @@ -381,7 +381,7 @@ class Function(_GenericDeclaration): def Requires(self, node): if self.parameters: - # TODO(nnorwitz): parameters are tokens, do name comparision. + # TODO(nnorwitz): parameters are tokens, do name comparison. for p in self.parameters: if p.name == node.name: return True @@ -858,7 +858,7 @@ class AstBuilder(object): last_token = self._GetNextToken() return tokens, last_token - # TODO(nnorwitz): remove _IgnoreUpTo() it shouldn't be necesary. + # TODO(nnorwitz): remove _IgnoreUpTo() it shouldn't be necessary. def _IgnoreUpTo(self, token_type, token): unused_tokens = self._GetTokensUpTo(token_type, token) @@ -1264,6 +1264,9 @@ class AstBuilder(object): return self._GetNestedType(Union) def handle_enum(self): + token = self._GetNextToken() + if not (token.token_type == tokenize.NAME and token.name == 'class'): + self._AddBackToken(token) return self._GetNestedType(Enum) def handle_auto(self): diff --git a/googlemock/scripts/generator/cpp/gmock_class_test.py b/googlemock/scripts/generator/cpp/gmock_class_test.py index 018f90a..c53e600 100755 --- a/googlemock/scripts/generator/cpp/gmock_class_test.py +++ b/googlemock/scripts/generator/cpp/gmock_class_test.py @@ -444,5 +444,23 @@ void(const FooType& test_arg)); self.assertEqualIgnoreLeadingWhitespace( expected, self.GenerateMocks(source)) + def testEnumClass(self): + source = """ +class Test { + public: + enum class Baz { BAZINGA }; + virtual void Bar(const FooType& test_arg); +}; +""" + expected = """\ +class MockTest : public Test { +public: +MOCK_METHOD1(Bar, +void(const FooType& test_arg)); +}; +""" + self.assertEqualIgnoreLeadingWhitespace( + expected, self.GenerateMocks(source)) + if __name__ == '__main__': unittest.main() diff --git a/googlemock/scripts/upload.py b/googlemock/scripts/upload.py index 6e6f9a1..95239dc 100755 --- a/googlemock/scripts/upload.py +++ b/googlemock/scripts/upload.py @@ -242,7 +242,7 @@ class AbstractRpcServer(object): The authentication process works as follows: 1) We get a username and password from the user 2) We use ClientLogin to obtain an AUTH token for the user - (see http://code.google.com/apis/accounts/AuthForInstalledApps.html). + (see https://developers.google.com/identity/protocols/AuthForInstalledApps). 3) We pass the auth token to /_ah/login on the server to obtain an authentication cookie. If login was successful, it tries to redirect us to the URL we provided. @@ -506,7 +506,7 @@ def EncodeMultipartFormData(fields, files): (content_type, body) ready for httplib.HTTP instance. Source: - http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/146306 + https://web.archive.org/web/20160116052001/code.activestate.com/recipes/146306 """ BOUNDARY = '-M-A-G-I-C---B-O-U-N-D-A-R-Y-' CRLF = '\r\n' @@ -807,7 +807,7 @@ class SubversionVCS(VersionControlSystem): # svn cat translates keywords but svn diff doesn't. As a result of this # behavior patching.PatchChunks() fails with a chunk mismatch error. # This part was originally written by the Review Board development team - # who had the same problem (http://reviews.review-board.org/r/276/). + # who had the same problem (https://reviews.reviewboard.org/r/276/). # Mapping of keywords to known aliases svn_keywords = { # Standard keywords @@ -860,7 +860,7 @@ class SubversionVCS(VersionControlSystem): status_lines = status.splitlines() # If file is in a cl, the output will begin with # "\n--- Changelist 'cl_name':\n". See - # http://svn.collab.net/repos/svn/trunk/notes/changelist-design.txt + # https://web.archive.org/web/20090918234815/svn.collab.net/repos/svn/trunk/notes/changelist-design.txt if (len(status_lines) == 3 and not status_lines[0] and status_lines[1].startswith("--- Changelist")): diff --git a/googlemock/src/gmock-all.cc b/googlemock/src/gmock-all.cc index 7aebce7..e43c9b7 100644 --- a/googlemock/src/gmock-all.cc +++ b/googlemock/src/gmock-all.cc @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // // Google C++ Mocking Framework (Google Mock) // diff --git a/googlemock/src/gmock-cardinalities.cc b/googlemock/src/gmock-cardinalities.cc index 50ec728..0549f72 100644 --- a/googlemock/src/gmock-cardinalities.cc +++ b/googlemock/src/gmock-cardinalities.cc @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // Google Mock - a framework for writing C++ mock classes. // @@ -92,7 +91,7 @@ class BetweenCardinalityImpl : public CardinalityInterface { }; // Formats "n times" in a human-friendly way. -inline internal::string FormatTimes(int n) { +inline std::string FormatTimes(int n) { if (n == 1) { return "once"; } else if (n == 2) { diff --git a/googlemock/src/gmock-internal-utils.cc b/googlemock/src/gmock-internal-utils.cc index fb53080..e3a6748 100644 --- a/googlemock/src/gmock-internal-utils.cc +++ b/googlemock/src/gmock-internal-utils.cc @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // Google Mock - a framework for writing C++ mock classes. // @@ -47,12 +46,31 @@ namespace testing { namespace internal { +// Joins a vector of strings as if they are fields of a tuple; returns +// the joined string. +GTEST_API_ std::string JoinAsTuple(const Strings& fields) { + switch (fields.size()) { + case 0: + return ""; + case 1: + return fields[0]; + default: + std::string result = "(" + fields[0]; + for (size_t i = 1; i < fields.size(); i++) { + result += ", "; + result += fields[i]; + } + result += ")"; + return result; + } +} + // Converts an identifier name to a space-separated list of lower-case // words. Each maximum substring of the form [A-Za-z][a-z]*|\d+ is // treated as one word. For example, both "FooBar123" and // "foo_bar_123" are converted to "foo bar 123". -GTEST_API_ string ConvertIdentifierNameToWords(const char* id_name) { - string result; +GTEST_API_ std::string ConvertIdentifierNameToWords(const char* id_name) { + std::string result; char prev_char = '\0'; for (const char* p = id_name; *p != '\0'; prev_char = *(p++)) { // We don't care about the current locale as the input is @@ -71,12 +89,12 @@ GTEST_API_ string ConvertIdentifierNameToWords(const char* id_name) { } // This class reports Google Mock failures as Google Test failures. A -// user can define another class in a similar fashion if he intends to +// user can define another class in a similar fashion if they intend to // use Google Mock with a testing framework other than Google Test. class GoogleTestFailureReporter : public FailureReporterInterface { public: virtual void ReportFailure(FailureType type, const char* file, int line, - const string& message) { + const std::string& message) { AssertHelper(type == kFatal ? TestPartResult::kFatalFailure : TestPartResult::kNonFatalFailure, @@ -128,8 +146,7 @@ GTEST_API_ bool LogIsVisible(LogSeverity severity) { // stack_frames_to_skip is treated as 0, since we don't know which // function calls will be inlined by the compiler and need to be // conservative. -GTEST_API_ void Log(LogSeverity severity, - const string& message, +GTEST_API_ void Log(LogSeverity severity, const std::string& message, int stack_frames_to_skip) { if (!LogIsVisible(severity)) return; @@ -170,5 +187,17 @@ GTEST_API_ void Log(LogSeverity severity, std::cout << ::std::flush; } +GTEST_API_ WithoutMatchers GetWithoutMatchers() { return WithoutMatchers(); } + +GTEST_API_ void IllegalDoDefault(const char* file, int line) { + internal::Assert( + false, file, line, + "You are using DoDefault() inside a composite action like " + "DoAll() or WithArgs(). This is not supported for technical " + "reasons. Please instead spell out the default action, or " + "assign the default action to an Action variable and use " + "the variable in various places."); +} + } // namespace internal } // namespace testing diff --git a/googlemock/src/gmock-matchers.cc b/googlemock/src/gmock-matchers.cc index e742451..f8ddff1 100644 --- a/googlemock/src/gmock-matchers.cc +++ b/googlemock/src/gmock-matchers.cc @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // Google Mock - a framework for writing C++ mock classes. // @@ -38,98 +37,133 @@ #include "gmock/gmock-generated-matchers.h" #include <string.h> +#include <iostream> #include <sstream> #include <string> namespace testing { -// Constructs a matcher that matches a const string& whose value is +// Constructs a matcher that matches a const std::string& whose value is // equal to s. -Matcher<const internal::string&>::Matcher(const internal::string& s) { - *this = Eq(s); +Matcher<const std::string&>::Matcher(const std::string& s) { *this = Eq(s); } + +#if GTEST_HAS_GLOBAL_STRING +// Constructs a matcher that matches a const std::string& whose value is +// equal to s. +Matcher<const std::string&>::Matcher(const ::string& s) { + *this = Eq(static_cast<std::string>(s)); } +#endif // GTEST_HAS_GLOBAL_STRING -// Constructs a matcher that matches a const string& whose value is +// Constructs a matcher that matches a const std::string& whose value is // equal to s. -Matcher<const internal::string&>::Matcher(const char* s) { - *this = Eq(internal::string(s)); +Matcher<const std::string&>::Matcher(const char* s) { + *this = Eq(std::string(s)); } -// Constructs a matcher that matches a string whose value is equal to s. -Matcher<internal::string>::Matcher(const internal::string& s) { *this = Eq(s); } +// Constructs a matcher that matches a std::string whose value is equal to +// s. +Matcher<std::string>::Matcher(const std::string& s) { *this = Eq(s); } -// Constructs a matcher that matches a string whose value is equal to s. -Matcher<internal::string>::Matcher(const char* s) { - *this = Eq(internal::string(s)); +#if GTEST_HAS_GLOBAL_STRING +// Constructs a matcher that matches a std::string whose value is equal to +// s. +Matcher<std::string>::Matcher(const ::string& s) { + *this = Eq(static_cast<std::string>(s)); } +#endif // GTEST_HAS_GLOBAL_STRING + +// Constructs a matcher that matches a std::string whose value is equal to +// s. +Matcher<std::string>::Matcher(const char* s) { *this = Eq(std::string(s)); } -#if GTEST_HAS_STRING_PIECE_ -// Constructs a matcher that matches a const StringPiece& whose value is +#if GTEST_HAS_GLOBAL_STRING +// Constructs a matcher that matches a const ::string& whose value is // equal to s. -Matcher<const StringPiece&>::Matcher(const internal::string& s) { - *this = Eq(s); +Matcher<const ::string&>::Matcher(const std::string& s) { + *this = Eq(static_cast<::string>(s)); } -// Constructs a matcher that matches a const StringPiece& whose value is +// Constructs a matcher that matches a const ::string& whose value is // equal to s. -Matcher<const StringPiece&>::Matcher(const char* s) { - *this = Eq(internal::string(s)); -} +Matcher<const ::string&>::Matcher(const ::string& s) { *this = Eq(s); } -// Constructs a matcher that matches a const StringPiece& whose value is +// Constructs a matcher that matches a const ::string& whose value is // equal to s. -Matcher<const StringPiece&>::Matcher(StringPiece s) { - *this = Eq(s.ToString()); +Matcher<const ::string&>::Matcher(const char* s) { *this = Eq(::string(s)); } + +// Constructs a matcher that matches a ::string whose value is equal to s. +Matcher<::string>::Matcher(const std::string& s) { + *this = Eq(static_cast<::string>(s)); } -// Constructs a matcher that matches a StringPiece whose value is equal to s. -Matcher<StringPiece>::Matcher(const internal::string& s) { +// Constructs a matcher that matches a ::string whose value is equal to s. +Matcher<::string>::Matcher(const ::string& s) { *this = Eq(s); } + +// Constructs a matcher that matches a string whose value is equal to s. +Matcher<::string>::Matcher(const char* s) { *this = Eq(::string(s)); } +#endif // GTEST_HAS_GLOBAL_STRING + +#if GTEST_HAS_ABSL +// Constructs a matcher that matches a const absl::string_view& whose value is +// equal to s. +Matcher<const absl::string_view&>::Matcher(const std::string& s) { *this = Eq(s); } -// Constructs a matcher that matches a StringPiece whose value is equal to s. -Matcher<StringPiece>::Matcher(const char* s) { - *this = Eq(internal::string(s)); +#if GTEST_HAS_GLOBAL_STRING +// Constructs a matcher that matches a const absl::string_view& whose value is +// equal to s. +Matcher<const absl::string_view&>::Matcher(const ::string& s) { *this = Eq(s); } +#endif // GTEST_HAS_GLOBAL_STRING + +// Constructs a matcher that matches a const absl::string_view& whose value is +// equal to s. +Matcher<const absl::string_view&>::Matcher(const char* s) { + *this = Eq(std::string(s)); } -// Constructs a matcher that matches a StringPiece whose value is equal to s. -Matcher<StringPiece>::Matcher(StringPiece s) { - *this = Eq(s.ToString()); +// Constructs a matcher that matches a const absl::string_view& whose value is +// equal to s. +Matcher<const absl::string_view&>::Matcher(absl::string_view s) { + *this = Eq(std::string(s)); } -#endif // GTEST_HAS_STRING_PIECE_ -namespace internal { +// Constructs a matcher that matches a absl::string_view whose value is equal to +// s. +Matcher<absl::string_view>::Matcher(const std::string& s) { *this = Eq(s); } -// Joins a vector of strings as if they are fields of a tuple; returns -// the joined string. -GTEST_API_ string JoinAsTuple(const Strings& fields) { - switch (fields.size()) { - case 0: - return ""; - case 1: - return fields[0]; - default: - string result = "(" + fields[0]; - for (size_t i = 1; i < fields.size(); i++) { - result += ", "; - result += fields[i]; - } - result += ")"; - return result; - } +#if GTEST_HAS_GLOBAL_STRING +// Constructs a matcher that matches a absl::string_view whose value is equal to +// s. +Matcher<absl::string_view>::Matcher(const ::string& s) { *this = Eq(s); } +#endif // GTEST_HAS_GLOBAL_STRING + +// Constructs a matcher that matches a absl::string_view whose value is equal to +// s. +Matcher<absl::string_view>::Matcher(const char* s) { + *this = Eq(std::string(s)); } +// Constructs a matcher that matches a absl::string_view whose value is equal to +// s. +Matcher<absl::string_view>::Matcher(absl::string_view s) { + *this = Eq(std::string(s)); +} +#endif // GTEST_HAS_ABSL + +namespace internal { + // Returns the description for a matcher defined using the MATCHER*() // macro where the user-supplied description string is "", if // 'negation' is false; otherwise returns the description of the // negation of the matcher. 'param_values' contains a list of strings // that are the print-out of the matcher's parameters. -GTEST_API_ string FormatMatcherDescription(bool negation, - const char* matcher_name, - const Strings& param_values) { - string result = ConvertIdentifierNameToWords(matcher_name); - if (param_values.size() >= 1) - result += " " + JoinAsTuple(param_values); +GTEST_API_ std::string FormatMatcherDescription(bool negation, + const char* matcher_name, + const Strings& param_values) { + std::string result = ConvertIdentifierNameToWords(matcher_name); + if (param_values.size() >= 1) result += " " + JoinAsTuple(param_values); return negation ? "not (" + result + ")" : result; } @@ -200,8 +234,7 @@ class MaxBipartiteMatchState { explicit MaxBipartiteMatchState(const MatchMatrix& graph) : graph_(&graph), left_(graph_->LhsSize(), kUnused), - right_(graph_->RhsSize(), kUnused) { - } + right_(graph_->RhsSize(), kUnused) {} // Returns the edges of a maximal match, each in the form {left, right}. ElementMatcherPairs Compute() { @@ -258,10 +291,8 @@ class MaxBipartiteMatchState { // bool TryAugment(size_t ilhs, ::std::vector<char>* seen) { for (size_t irhs = 0; irhs < graph_->RhsSize(); ++irhs) { - if ((*seen)[irhs]) - continue; - if (!graph_->HasEdge(ilhs, irhs)) - continue; + if ((*seen)[irhs]) continue; + if (!graph_->HasEdge(ilhs, irhs)) continue; // There's an available edge from ilhs to irhs. (*seen)[irhs] = 1; // Next a search is performed to determine whether @@ -288,7 +319,7 @@ class MaxBipartiteMatchState { // Each element of the left_ vector represents a left hand side node // (i.e. an element) and each element of right_ is a right hand side // node (i.e. a matcher). The values in the left_ vector indicate - // outflow from that node to a node on the the right_ side. The values + // outflow from that node to a node on the right_ side. The values // in the right_ indicate inflow, and specify which left_ node is // feeding that right_ node, if any. For example, left_[3] == 1 means // there's a flow from element #3 to matcher #1. Such a flow would also @@ -304,8 +335,7 @@ class MaxBipartiteMatchState { const size_t MaxBipartiteMatchState::kUnused; -GTEST_API_ ElementMatcherPairs -FindMaxBipartiteMatching(const MatchMatrix& g) { +GTEST_API_ ElementMatcherPairs FindMaxBipartiteMatching(const MatchMatrix& g) { return MaxBipartiteMatchState(g).Compute(); } @@ -314,7 +344,7 @@ static void LogElementMatcherPairVec(const ElementMatcherPairs& pairs, typedef ElementMatcherPairs::const_iterator Iter; ::std::ostream& os = *stream; os << "{"; - const char *sep = ""; + const char* sep = ""; for (Iter it = pairs.begin(); it != pairs.end(); ++it) { os << sep << "\n (" << "element #" << it->first << ", " @@ -324,38 +354,6 @@ static void LogElementMatcherPairVec(const ElementMatcherPairs& pairs, os << "\n}"; } -// Tries to find a pairing, and explains the result. -GTEST_API_ bool FindPairing(const MatchMatrix& matrix, - MatchResultListener* listener) { - ElementMatcherPairs matches = FindMaxBipartiteMatching(matrix); - - size_t max_flow = matches.size(); - bool result = (max_flow == matrix.RhsSize()); - - if (!result) { - if (listener->IsInterested()) { - *listener << "where no permutation of the elements can " - "satisfy all matchers, and the closest match is " - << max_flow << " of " << matrix.RhsSize() - << " matchers with the pairings:\n"; - LogElementMatcherPairVec(matches, listener->stream()); - } - return false; - } - - if (matches.size() > 1) { - if (listener->IsInterested()) { - const char *sep = "where:\n"; - for (size_t mi = 0; mi < matches.size(); ++mi) { - *listener << sep << " - element #" << matches[mi].first - << " is matched by matcher #" << matches[mi].second; - sep = ",\n"; - } - } - } - return true; -} - bool MatchMatrix::NextGraph() { for (size_t ilhs = 0; ilhs < LhsSize(); ++ilhs) { for (size_t irhs = 0; irhs < RhsSize(); ++irhs) { @@ -379,9 +377,9 @@ void MatchMatrix::Randomize() { } } -string MatchMatrix::DebugString() const { +std::string MatchMatrix::DebugString() const { ::std::stringstream ss; - const char *sep = ""; + const char* sep = ""; for (size_t i = 0; i < LhsSize(); ++i) { ss << sep; for (size_t j = 0; j < RhsSize(); ++j) { @@ -394,44 +392,83 @@ string MatchMatrix::DebugString() const { void UnorderedElementsAreMatcherImplBase::DescribeToImpl( ::std::ostream* os) const { - if (matcher_describers_.empty()) { - *os << "is empty"; - return; - } - if (matcher_describers_.size() == 1) { - *os << "has " << Elements(1) << " and that element "; - matcher_describers_[0]->DescribeTo(os); - return; + switch (match_flags()) { + case UnorderedMatcherRequire::ExactMatch: + if (matcher_describers_.empty()) { + *os << "is empty"; + return; + } + if (matcher_describers_.size() == 1) { + *os << "has " << Elements(1) << " and that element "; + matcher_describers_[0]->DescribeTo(os); + return; + } + *os << "has " << Elements(matcher_describers_.size()) + << " and there exists some permutation of elements such that:\n"; + break; + case UnorderedMatcherRequire::Superset: + *os << "a surjection from elements to requirements exists such that:\n"; + break; + case UnorderedMatcherRequire::Subset: + *os << "an injection from elements to requirements exists such that:\n"; + break; } - *os << "has " << Elements(matcher_describers_.size()) - << " and there exists some permutation of elements such that:\n"; + const char* sep = ""; for (size_t i = 0; i != matcher_describers_.size(); ++i) { - *os << sep << " - element #" << i << " "; + *os << sep; + if (match_flags() == UnorderedMatcherRequire::ExactMatch) { + *os << " - element #" << i << " "; + } else { + *os << " - an element "; + } matcher_describers_[i]->DescribeTo(os); - sep = ", and\n"; + if (match_flags() == UnorderedMatcherRequire::ExactMatch) { + sep = ", and\n"; + } else { + sep = "\n"; + } } } void UnorderedElementsAreMatcherImplBase::DescribeNegationToImpl( ::std::ostream* os) const { - if (matcher_describers_.empty()) { - *os << "isn't empty"; - return; - } - if (matcher_describers_.size() == 1) { - *os << "doesn't have " << Elements(1) - << ", or has " << Elements(1) << " that "; - matcher_describers_[0]->DescribeNegationTo(os); - return; + switch (match_flags()) { + case UnorderedMatcherRequire::ExactMatch: + if (matcher_describers_.empty()) { + *os << "isn't empty"; + return; + } + if (matcher_describers_.size() == 1) { + *os << "doesn't have " << Elements(1) << ", or has " << Elements(1) + << " that "; + matcher_describers_[0]->DescribeNegationTo(os); + return; + } + *os << "doesn't have " << Elements(matcher_describers_.size()) + << ", or there exists no permutation of elements such that:\n"; + break; + case UnorderedMatcherRequire::Superset: + *os << "no surjection from elements to requirements exists such that:\n"; + break; + case UnorderedMatcherRequire::Subset: + *os << "no injection from elements to requirements exists such that:\n"; + break; } - *os << "doesn't have " << Elements(matcher_describers_.size()) - << ", or there exists no permutation of elements such that:\n"; const char* sep = ""; for (size_t i = 0; i != matcher_describers_.size(); ++i) { - *os << sep << " - element #" << i << " "; + *os << sep; + if (match_flags() == UnorderedMatcherRequire::ExactMatch) { + *os << " - element #" << i << " "; + } else { + *os << " - an element "; + } matcher_describers_[i]->DescribeTo(os); - sep = ", and\n"; + if (match_flags() == UnorderedMatcherRequire::ExactMatch) { + sep = ", and\n"; + } else { + sep = "\n"; + } } } @@ -440,11 +477,9 @@ void UnorderedElementsAreMatcherImplBase::DescribeNegationToImpl( // and better error reporting. // Returns false, writing an explanation to 'listener', if and only // if the success criteria are not met. -bool UnorderedElementsAreMatcherImplBase:: -VerifyAllElementsAndMatchersAreMatched( - const ::std::vector<string>& element_printouts, - const MatchMatrix& matrix, - MatchResultListener* listener) const { +bool UnorderedElementsAreMatcherImplBase::VerifyMatchMatrix( + const ::std::vector<std::string>& element_printouts, + const MatchMatrix& matrix, MatchResultListener* listener) const { bool result = true; ::std::vector<char> element_matched(matrix.LhsSize(), 0); ::std::vector<char> matcher_matched(matrix.RhsSize(), 0); @@ -457,12 +492,11 @@ VerifyAllElementsAndMatchersAreMatched( } } - { + if (match_flags() & UnorderedMatcherRequire::Superset) { const char* sep = "where the following matchers don't match any elements:\n"; for (size_t mi = 0; mi < matcher_matched.size(); ++mi) { - if (matcher_matched[mi]) - continue; + if (matcher_matched[mi]) continue; result = false; if (listener->IsInterested()) { *listener << sep << "matcher #" << mi << ": "; @@ -472,7 +506,7 @@ VerifyAllElementsAndMatchersAreMatched( } } - { + if (match_flags() & UnorderedMatcherRequire::Subset) { const char* sep = "where the following elements don't match any matchers:\n"; const char* outer_sep = ""; @@ -480,8 +514,7 @@ VerifyAllElementsAndMatchersAreMatched( outer_sep = "\nand "; } for (size_t ei = 0; ei < element_matched.size(); ++ei) { - if (element_matched[ei]) - continue; + if (element_matched[ei]) continue; result = false; if (listener->IsInterested()) { *listener << outer_sep << sep << "element #" << ei << ": " @@ -494,5 +527,46 @@ VerifyAllElementsAndMatchersAreMatched( return result; } +bool UnorderedElementsAreMatcherImplBase::FindPairing( + const MatchMatrix& matrix, MatchResultListener* listener) const { + ElementMatcherPairs matches = FindMaxBipartiteMatching(matrix); + + size_t max_flow = matches.size(); + if ((match_flags() & UnorderedMatcherRequire::Superset) && + max_flow < matrix.RhsSize()) { + if (listener->IsInterested()) { + *listener << "where no permutation of the elements can satisfy all " + "matchers, and the closest match is " + << max_flow << " of " << matrix.RhsSize() + << " matchers with the pairings:\n"; + LogElementMatcherPairVec(matches, listener->stream()); + } + return false; + } + if ((match_flags() & UnorderedMatcherRequire::Subset) && + max_flow < matrix.LhsSize()) { + if (listener->IsInterested()) { + *listener + << "where not all elements can be matched, and the closest match is " + << max_flow << " of " << matrix.RhsSize() + << " matchers with the pairings:\n"; + LogElementMatcherPairVec(matches, listener->stream()); + } + return false; + } + + if (matches.size() > 1) { + if (listener->IsInterested()) { + const char* sep = "where:\n"; + for (size_t mi = 0; mi < matches.size(); ++mi) { + *listener << sep << " - element #" << matches[mi].first + << " is matched by matcher #" << matches[mi].second; + sep = ",\n"; + } + } + } + return true; +} + } // namespace internal } // namespace testing diff --git a/googlemock/src/gmock-spec-builders.cc b/googlemock/src/gmock-spec-builders.cc index 5b0a830..5c20ed1 100644 --- a/googlemock/src/gmock-spec-builders.cc +++ b/googlemock/src/gmock-spec-builders.cc @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // Google Mock - a framework for writing C++ mock classes. // @@ -41,6 +40,7 @@ #include <map> #include <set> #include <string> +#include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" @@ -48,6 +48,15 @@ # include <unistd.h> // NOLINT #endif +// Silence C4800 (C4800: 'int *const ': forcing value +// to bool 'true' or 'false') for MSVC 14,15 +#ifdef _MSC_VER +#if _MSC_VER <= 1900 +# pragma warning(push) +# pragma warning(disable:4800) +#endif +#endif + namespace testing { namespace internal { @@ -58,16 +67,15 @@ GTEST_API_ GTEST_DEFINE_STATIC_MUTEX_(g_gmock_mutex); // Logs a message including file and line number information. GTEST_API_ void LogWithLocation(testing::internal::LogSeverity severity, const char* file, int line, - const string& message) { + const std::string& message) { ::std::ostringstream s; s << file << ":" << line << ": " << message << ::std::endl; Log(severity, s.str(), 0); } // Constructs an ExpectationBase object. -ExpectationBase::ExpectationBase(const char* a_file, - int a_line, - const string& a_source_text) +ExpectationBase::ExpectationBase(const char* a_file, int a_line, + const std::string& a_source_text) : file_(a_file), line_(a_line), source_text_(a_source_text), @@ -100,12 +108,19 @@ void ExpectationBase::RetireAllPreRequisites() return; } - for (ExpectationSet::const_iterator it = immediate_prerequisites_.begin(); - it != immediate_prerequisites_.end(); ++it) { - ExpectationBase* const prerequisite = it->expectation_base().get(); - if (!prerequisite->is_retired()) { - prerequisite->RetireAllPreRequisites(); - prerequisite->Retire(); + ::std::vector<ExpectationBase*> expectations(1, this); + while (!expectations.empty()) { + ExpectationBase* exp = expectations.back(); + expectations.pop_back(); + + for (ExpectationSet::const_iterator it = + exp->immediate_prerequisites_.begin(); + it != exp->immediate_prerequisites_.end(); ++it) { + ExpectationBase* next = it->expectation_base().get(); + if (!next->is_retired()) { + next->Retire(); + expectations.push_back(next); + } } } } @@ -115,11 +130,18 @@ void ExpectationBase::RetireAllPreRequisites() bool ExpectationBase::AllPrerequisitesAreSatisfied() const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { g_gmock_mutex.AssertHeld(); - for (ExpectationSet::const_iterator it = immediate_prerequisites_.begin(); - it != immediate_prerequisites_.end(); ++it) { - if (!(it->expectation_base()->IsSatisfied()) || - !(it->expectation_base()->AllPrerequisitesAreSatisfied())) - return false; + ::std::vector<const ExpectationBase*> expectations(1, this); + while (!expectations.empty()) { + const ExpectationBase* exp = expectations.back(); + expectations.pop_back(); + + for (ExpectationSet::const_iterator it = + exp->immediate_prerequisites_.begin(); + it != exp->immediate_prerequisites_.end(); ++it) { + const ExpectationBase* next = it->expectation_base().get(); + if (!next->IsSatisfied()) return false; + expectations.push_back(next); + } } return true; } @@ -128,19 +150,28 @@ bool ExpectationBase::AllPrerequisitesAreSatisfied() const void ExpectationBase::FindUnsatisfiedPrerequisites(ExpectationSet* result) const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { g_gmock_mutex.AssertHeld(); - for (ExpectationSet::const_iterator it = immediate_prerequisites_.begin(); - it != immediate_prerequisites_.end(); ++it) { - if (it->expectation_base()->IsSatisfied()) { - // If *it is satisfied and has a call count of 0, some of its - // pre-requisites may not be satisfied yet. - if (it->expectation_base()->call_count_ == 0) { - it->expectation_base()->FindUnsatisfiedPrerequisites(result); + ::std::vector<const ExpectationBase*> expectations(1, this); + while (!expectations.empty()) { + const ExpectationBase* exp = expectations.back(); + expectations.pop_back(); + + for (ExpectationSet::const_iterator it = + exp->immediate_prerequisites_.begin(); + it != exp->immediate_prerequisites_.end(); ++it) { + const ExpectationBase* next = it->expectation_base().get(); + + if (next->IsSatisfied()) { + // If *it is satisfied and has a call count of 0, some of its + // pre-requisites may not be satisfied yet. + if (next->call_count_ == 0) { + expectations.push_back(next); + } + } else { + // Now that we know next is unsatisfied, we are not so interested + // in whether its pre-requisites are satisfied. Therefore we + // don't iterate into it here. + *result += *it; } - } else { - // Now that we know *it is unsatisfied, we are not so interested - // in whether its pre-requisites are satisfied. Therefore we - // don't recursively call FindUnsatisfiedPrerequisites() here. - *result += *it; } } } @@ -244,7 +275,7 @@ GTEST_API_ ThreadLocal<Sequence*> g_gmock_implicit_sequence; // Reports an uninteresting call (whose description is in msg) in the // manner specified by 'reaction'. -void ReportUninterestingCall(CallReaction reaction, const string& msg) { +void ReportUninterestingCall(CallReaction reaction, const std::string& msg) { // Include a stack trace only if --gmock_verbose=info is specified. const int stack_frames_to_skip = GMOCK_FLAG(verbose) == kInfoVerbosity ? 3 : -1; @@ -255,20 +286,22 @@ void ReportUninterestingCall(CallReaction reaction, const string& msg) { case kWarn: Log(kWarning, msg + - "\nNOTE: You can safely ignore the above warning unless this " - "call should not happen. Do not suppress it by blindly adding " - "an EXPECT_CALL() if you don't mean to enforce the call. " - "See https://github.com/google/googletest/blob/master/googlemock/docs/CookBook.md#" - "knowing-when-to-expect for details.\n", + "\nNOTE: You can safely ignore the above warning unless this " + "call should not happen. Do not suppress it by blindly adding " + "an EXPECT_CALL() if you don't mean to enforce the call. " + "See " + "https://github.com/google/googletest/blob/master/googlemock/" + "docs/CookBook.md#" + "knowing-when-to-expect for details.\n", stack_frames_to_skip); break; default: // FAIL - Expect(false, NULL, -1, msg); + Expect(false, nullptr, -1, msg); } } UntypedFunctionMockerBase::UntypedFunctionMockerBase() - : mock_obj_(NULL), name_("") {} + : mock_obj_(nullptr), name_("") {} UntypedFunctionMockerBase::~UntypedFunctionMockerBase() {} @@ -307,7 +340,7 @@ const void* UntypedFunctionMockerBase::MockObject() const // We protect mock_obj_ under g_gmock_mutex in case this mock // function is called from two threads concurrently. MutexLock l(&g_gmock_mutex); - Assert(mock_obj_ != NULL, __FILE__, __LINE__, + Assert(mock_obj_ != nullptr, __FILE__, __LINE__, "MockObject() must not be called before RegisterOwner() or " "SetOwnerAndName() has been called."); mock_obj = mock_obj_; @@ -324,7 +357,7 @@ const char* UntypedFunctionMockerBase::Name() const // We protect name_ under g_gmock_mutex in case this mock // function is called from two threads concurrently. MutexLock l(&g_gmock_mutex); - Assert(name_ != NULL, __FILE__, __LINE__, + Assert(name_ != nullptr, __FILE__, __LINE__, "Name() must not be called before SetOwnerAndName() has " "been called."); name = name_; @@ -335,9 +368,10 @@ const char* UntypedFunctionMockerBase::Name() const // Calculates the result of invoking this mock function with the given // arguments, prints it, and returns it. The caller is responsible // for deleting the result. -UntypedActionResultHolderBase* -UntypedFunctionMockerBase::UntypedInvokeWith(const void* const untyped_args) - GTEST_LOCK_EXCLUDED_(g_gmock_mutex) { +UntypedActionResultHolderBase* UntypedFunctionMockerBase::UntypedInvokeWith( + void* const untyped_args) GTEST_LOCK_EXCLUDED_(g_gmock_mutex) { + // See the definition of untyped_expectations_ for why access to it + // is unprotected here. if (untyped_expectations_.size() == 0) { // No expectation is set on this mock method - we have an // uninteresting call. @@ -354,18 +388,21 @@ UntypedFunctionMockerBase::UntypedInvokeWith(const void* const untyped_args) // the behavior of ReportUninterestingCall(). const bool need_to_report_uninteresting_call = // If the user allows this uninteresting call, we print it - // only when he wants informational messages. + // only when they want informational messages. reaction == kAllow ? LogIsVisible(kInfo) : - // If the user wants this to be a warning, we print it only - // when he wants to see warnings. - reaction == kWarn ? LogIsVisible(kWarning) : - // Otherwise, the user wants this to be an error, and we - // should always print detailed information in the error. - true; + // If the user wants this to be a warning, we print + // it only when they want to see warnings. + reaction == kWarn + ? LogIsVisible(kWarning) + : + // Otherwise, the user wants this to be an error, and we + // should always print detailed information in the error. + true; if (!need_to_report_uninteresting_call) { // Perform the action without printing the call information. - return this->UntypedPerformDefaultAction(untyped_args, ""); + return this->UntypedPerformDefaultAction( + untyped_args, "Function call: " + std::string(Name())); } // Warns about the uninteresting call. @@ -377,8 +414,7 @@ UntypedFunctionMockerBase::UntypedInvokeWith(const void* const untyped_args) this->UntypedPerformDefaultAction(untyped_args, ss.str()); // Prints the function result. - if (result != NULL) - result->PrintAsActionResult(&ss); + if (result != nullptr) result->PrintAsActionResult(&ss); ReportUninterestingCall(reaction, ss.str()); return result; @@ -388,7 +424,7 @@ UntypedFunctionMockerBase::UntypedInvokeWith(const void* const untyped_args) ::std::stringstream ss; ::std::stringstream why; ::std::stringstream loc; - const void* untyped_action = NULL; + const void* untyped_action = nullptr; // The UntypedFindMatchingExpectation() function acquires and // releases g_gmock_mutex. @@ -396,7 +432,7 @@ UntypedFunctionMockerBase::UntypedInvokeWith(const void* const untyped_args) this->UntypedFindMatchingExpectation( untyped_args, &untyped_action, &is_excessive, &ss, &why); - const bool found = untyped_expectation != NULL; + const bool found = untyped_expectation != nullptr; // True iff we need to print the call's arguments and return value. // This definition must be kept in sync with the uses of Expect() @@ -405,10 +441,9 @@ UntypedFunctionMockerBase::UntypedInvokeWith(const void* const untyped_args) !found || is_excessive || LogIsVisible(kInfo); if (!need_to_report_call) { // Perform the action without printing the call information. - return - untyped_action == NULL ? - this->UntypedPerformDefaultAction(untyped_args, "") : - this->UntypedPerformAction(untyped_action, untyped_args); + return untyped_action == nullptr + ? this->UntypedPerformDefaultAction(untyped_args, "") + : this->UntypedPerformAction(untyped_action, untyped_args); } ss << " Function call: " << Name(); @@ -421,16 +456,15 @@ UntypedFunctionMockerBase::UntypedInvokeWith(const void* const untyped_args) } UntypedActionResultHolderBase* const result = - untyped_action == NULL ? - this->UntypedPerformDefaultAction(untyped_args, ss.str()) : - this->UntypedPerformAction(untyped_action, untyped_args); - if (result != NULL) - result->PrintAsActionResult(&ss); + untyped_action == nullptr + ? this->UntypedPerformDefaultAction(untyped_args, ss.str()) + : this->UntypedPerformAction(untyped_action, untyped_args); + if (result != nullptr) result->PrintAsActionResult(&ss); ss << "\n" << why.str(); if (!found) { // No expectation matches this call - reports a failure. - Expect(false, NULL, -1, ss.str()); + Expect(false, nullptr, -1, ss.str()); } else if (is_excessive) { // We had an upper-bound violation and the failure message is in ss. Expect(false, untyped_expectation->file(), @@ -447,6 +481,8 @@ UntypedFunctionMockerBase::UntypedInvokeWith(const void* const untyped_args) // Returns an Expectation object that references and co-owns exp, // which must be an expectation on this mock function. Expectation UntypedFunctionMockerBase::GetHandleOf(ExpectationBase* exp) { + // See the definition of untyped_expectations_ for why access to it + // is unprotected here. for (UntypedExpectations::const_iterator it = untyped_expectations_.begin(); it != untyped_expectations_.end(); ++it) { @@ -509,6 +545,13 @@ bool UntypedFunctionMockerBase::VerifyAndClearExpectationsLocked() return expectations_met; } +CallReaction intToCallReaction(int mock_behavior) { + if (mock_behavior >= kAllow && mock_behavior <= kFail) { + return static_cast<internal::CallReaction>(mock_behavior); + } + return kWarn; +} + } // namespace internal // Class Mock. @@ -522,7 +565,7 @@ typedef std::set<internal::UntypedFunctionMockerBase*> FunctionMockers; // expectations. struct MockObjectState { MockObjectState() - : first_used_file(NULL), first_used_line(-1), leakable(false) {} + : first_used_file(nullptr), first_used_line(-1), leakable(false) {} // Where in the source file an ON_CALL or EXPECT_CALL is first // invoked on this mock object. @@ -560,7 +603,7 @@ class MockObjectRegistry { if (it->second.leakable) // The user said it's fine to leak this object. continue; - // TODO(wan@google.com): Print the type of the leaked object. + // FIXME: Print the type of the leaked object. // This can help the user identify the leaked object. std::cout << "\n"; const MockObjectState& state = it->second; @@ -576,9 +619,15 @@ class MockObjectRegistry { leaked_count++; } if (leaked_count > 0) { - std::cout << "\nERROR: " << leaked_count - << " leaked mock " << (leaked_count == 1 ? "object" : "objects") - << " found at program exit.\n"; + std::cout << "\nERROR: " << leaked_count << " leaked mock " + << (leaked_count == 1 ? "object" : "objects") + << " found at program exit. Expectations on a mock object is " + "verified when the object is destructed. Leaking a mock " + "means that its expectations aren't verified, which is " + "usually a test bug. If you really intend to leak a mock, " + "you can suppress this error using " + "testing::Mock::AllowLeak(mock_object), or you may use a " + "fake or stub instead of a mock.\n"; std::cout.flush(); ::std::cerr.flush(); // RUN_ALL_TESTS() has already returned when this destructor is @@ -649,7 +698,8 @@ internal::CallReaction Mock::GetReactionOnUninterestingCalls( GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) { internal::MutexLock l(&internal::g_gmock_mutex); return (g_uninteresting_call_reaction.count(mock_obj) == 0) ? - internal::kDefault : g_uninteresting_call_reaction[mock_obj]; + internal::intToCallReaction(GMOCK_FLAG(default_mock_behavior)) : + g_uninteresting_call_reaction[mock_obj]; } // Tells Google Mock to ignore mock_obj when checking for leaked mock @@ -736,13 +786,13 @@ void Mock::RegisterUseByOnCallOrExpectCall(const void* mock_obj, GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) { internal::MutexLock l(&internal::g_gmock_mutex); MockObjectState& state = g_mock_object_registry.states()[mock_obj]; - if (state.first_used_file == NULL) { + if (state.first_used_file == nullptr) { state.first_used_file = file; state.first_used_line = line; const TestInfo* const test_info = UnitTest::GetInstance()->current_test_info(); - if (test_info != NULL) { - // TODO(wan@google.com): record the test case name when the + if (test_info != nullptr) { + // FIXME: record the test case name when the // ON_CALL or EXPECT_CALL is invoked from SetUpTestCase() or // TearDownTestCase(). state.first_used_test_case = test_info->test_case_name(); @@ -806,7 +856,7 @@ Expectation::~Expectation() {} // Adds an expectation to a sequence. void Sequence::AddExpectation(const Expectation& expectation) const { if (*last_expectation_ != expectation) { - if (last_expectation_->expectation_base() != NULL) { + if (last_expectation_->expectation_base() != nullptr) { expectation.expectation_base()->immediate_prerequisites_ += *last_expectation_; } @@ -834,3 +884,9 @@ InSequence::~InSequence() { } } // namespace testing + +#ifdef _MSC_VER +#if _MSC_VER <= 1900 +# pragma warning(pop) +#endif +#endif diff --git a/googlemock/src/gmock.cc b/googlemock/src/gmock.cc index eac3d84..675e8db 100644 --- a/googlemock/src/gmock.cc +++ b/googlemock/src/gmock.cc @@ -26,15 +26,14 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + #include "gmock/gmock.h" #include "gmock/internal/gmock-port.h" namespace testing { -// TODO(wan@google.com): support using environment variables to +// FIXME: support using environment variables to // control the flag values, like what Google Test does. GMOCK_DEFINE_bool_(catch_leaked_mocks, true, @@ -48,6 +47,13 @@ GMOCK_DEFINE_string_(verbose, internal::kWarningVerbosity, " warning - prints warnings and errors.\n" " error - prints errors only."); +GMOCK_DEFINE_int32_(default_mock_behavior, 1, + "Controls the default behavior of mocks." + " Valid values:\n" + " 0 - by default, mocks act as NiceMocks.\n" + " 1 - by default, mocks act as NaggyMocks.\n" + " 2 - by default, mocks act as StrictMocks."); + namespace internal { // Parses a string as a command line flag. The string should have the @@ -59,12 +65,12 @@ static const char* ParseGoogleMockFlagValue(const char* str, const char* flag, bool def_optional) { // str and flag must not be NULL. - if (str == NULL || flag == NULL) return NULL; + if (str == nullptr || flag == nullptr) return nullptr; // The flag must start with "--gmock_". const std::string flag_str = std::string("--gmock_") + flag; const size_t flag_len = flag_str.length(); - if (strncmp(str, flag_str.c_str(), flag_len) != 0) return NULL; + if (strncmp(str, flag_str.c_str(), flag_len) != 0) return nullptr; // Skips the flag name. const char* flag_end = str + flag_len; @@ -77,7 +83,7 @@ static const char* ParseGoogleMockFlagValue(const char* str, // If def_optional is true and there are more characters after the // flag name, or if def_optional is false, there must be a '=' after // the flag name. - if (flag_end[0] != '=') return NULL; + if (flag_end[0] != '=') return nullptr; // Returns the string after "=". return flag_end + 1; @@ -94,7 +100,7 @@ static bool ParseGoogleMockBoolFlag(const char* str, const char* flag, const char* const value_str = ParseGoogleMockFlagValue(str, flag, true); // Aborts if the parsing failed. - if (value_str == NULL) return false; + if (value_str == nullptr) return false; // Converts the string value to a bool. *value = !(*value_str == '0' || *value_str == 'f' || *value_str == 'F'); @@ -113,13 +119,26 @@ static bool ParseGoogleMockStringFlag(const char* str, const char* flag, const char* const value_str = ParseGoogleMockFlagValue(str, flag, false); // Aborts if the parsing failed. - if (value_str == NULL) return false; + if (value_str == nullptr) return false; // Sets *value to the value of the flag. *value = value_str; return true; } +static bool ParseGoogleMockIntFlag(const char* str, const char* flag, + int* value) { + // Gets the value of the flag as a string. + const char* const value_str = ParseGoogleMockFlagValue(str, flag, true); + + // Aborts if the parsing failed. + if (value_str == nullptr) return false; + + // Sets *value to the value of the flag. + return ParseInt32(Message() << "The value of flag --" << flag, + value_str, value); +} + // The internal implementation of InitGoogleMock(). // // The type parameter CharType can be instantiated to either char or @@ -138,7 +157,9 @@ void InitGoogleMockImpl(int* argc, CharType** argv) { // Do we see a Google Mock flag? if (ParseGoogleMockBoolFlag(arg, "catch_leaked_mocks", &GMOCK_FLAG(catch_leaked_mocks)) || - ParseGoogleMockStringFlag(arg, "verbose", &GMOCK_FLAG(verbose))) { + ParseGoogleMockStringFlag(arg, "verbose", &GMOCK_FLAG(verbose)) || + ParseGoogleMockIntFlag(arg, "default_mock_behavior", + &GMOCK_FLAG(default_mock_behavior))) { // Yes. Shift the remainder of the argv list left by one. Note // that argv has (*argc + 1) elements, the last one always being // NULL. The following loop moves the trailing NULL element as diff --git a/googlemock/src/gmock_main.cc b/googlemock/src/gmock_main.cc index bd5be03..a3a271e 100644 --- a/googlemock/src/gmock_main.cc +++ b/googlemock/src/gmock_main.cc @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + #include <iostream> #include "gmock/gmock.h" @@ -37,7 +36,8 @@ // causes a link error when _tmain is defined in a static library and UNICODE // is enabled. For this reason instead of _tmain, main function is used on // Windows. See the following link to track the current status of this bug: -// http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=394464 // NOLINT +// https://web.archive.org/web/20170912203238/connect.microsoft.com/VisualStudio/feedback/details/394464/wmain-link-error-in-the-static-library +// // NOLINT #if GTEST_OS_WINDOWS_MOBILE # include <tchar.h> // NOLINT diff --git a/googlemock/test/BUILD.bazel b/googlemock/test/BUILD.bazel new file mode 100644 index 0000000..0fe72a6 --- /dev/null +++ b/googlemock/test/BUILD.bazel @@ -0,0 +1,123 @@ +# Copyright 2017 Google Inc. +# All Rights Reserved. +# +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following disclaimer +# in the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# +# Author: misterg@google.com (Gennadiy Civil) +# +# Bazel Build for Google C++ Testing Framework(Google Test)-googlemock + +licenses(["notice"]) + +""" gmock own tests """ + +cc_test( + name = "gmock_all_test", + size = "small", + srcs = glob( + include = [ + "gmock-*.cc", + ], + ), + linkopts = select({ + "//:windows": [], + "//:windows_msvc": [], + "//conditions:default": [ + "-pthread", + ], + }), + deps = ["//:gtest"], +) + +# Py tests + +py_library( + name = "gmock_test_utils", + testonly = 1, + srcs = ["gmock_test_utils.py"], +) + +cc_binary( + name = "gmock_leak_test_", + testonly = 1, + srcs = ["gmock_leak_test_.cc"], + deps = [ + "//:gtest_main", + ], +) + +py_test( + name = "gmock_leak_test", + size = "medium", + srcs = ["gmock_leak_test.py"], + data = [ + ":gmock_leak_test_", + ":gmock_test_utils", + ], +) + +cc_test( + name = "gmock_link_test", + size = "small", + srcs = [ + "gmock_link2_test.cc", + "gmock_link_test.cc", + "gmock_link_test.h", + ], + deps = [ + "//:gtest_main", + ], +) + +cc_binary( + name = "gmock_output_test_", + srcs = ["gmock_output_test_.cc"], + deps = [ + "//:gtest", + ], +) + +py_test( + name = "gmock_output_test", + size = "medium", + srcs = ["gmock_output_test.py"], + data = [ + ":gmock_output_test_", + ":gmock_output_test_golden.txt", + ], + deps = [":gmock_test_utils"], +) + +cc_test( + name = "gmock_test", + size = "small", + srcs = ["gmock_test.cc"], + deps = [ + "//:gtest_main", + ], +) diff --git a/googlemock/test/gmock-actions_test.cc b/googlemock/test/gmock-actions_test.cc index f470de4..0de8481 100644 --- a/googlemock/test/gmock-actions_test.cc +++ b/googlemock/test/gmock-actions_test.cc @@ -26,13 +26,21 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // Google Mock - a framework for writing C++ mock classes. // // This file tests the built-in actions. +// Silence C4800 (C4800: 'int *const ': forcing value +// to bool 'true' or 'false') for MSVC 14,15 +#ifdef _MSC_VER +#if _MSC_VER <= 1900 +# pragma warning(push) +# pragma warning(disable:4800) +#endif +#endif + #include "gmock/gmock-actions.h" #include <algorithm> #include <iterator> @@ -65,28 +73,21 @@ using testing::ReturnRef; using testing::ReturnRefOfCopy; using testing::SetArgPointee; using testing::SetArgumentPointee; +using testing::Unused; using testing::_; -using testing::get; using testing::internal::BuiltInDefaultValue; using testing::internal::Int64; using testing::internal::UInt64; -using testing::make_tuple; -using testing::tuple; -using testing::tuple_element; #if !GTEST_OS_WINDOWS_MOBILE using testing::SetErrnoAndReturn; #endif -#if GTEST_HAS_PROTOBUF_ -using testing::internal::TestMessage; -#endif // GTEST_HAS_PROTOBUF_ - // Tests that BuiltInDefaultValue<T*>::Get() returns NULL. TEST(BuiltInDefaultValueTest, IsNullForPointerTypes) { - EXPECT_TRUE(BuiltInDefaultValue<int*>::Get() == NULL); - EXPECT_TRUE(BuiltInDefaultValue<const char*>::Get() == NULL); - EXPECT_TRUE(BuiltInDefaultValue<void*>::Get() == NULL); + EXPECT_TRUE(BuiltInDefaultValue<int*>::Get() == nullptr); + EXPECT_TRUE(BuiltInDefaultValue<const char*>::Get() == nullptr); + EXPECT_TRUE(BuiltInDefaultValue<void*>::Get() == nullptr); } // Tests that BuiltInDefaultValue<T*>::Exists() return true. @@ -107,7 +108,11 @@ TEST(BuiltInDefaultValueTest, IsZeroForNumericTypes) { EXPECT_EQ(0, BuiltInDefaultValue<signed wchar_t>::Get()); #endif #if GMOCK_WCHAR_T_IS_NATIVE_ +#if !defined(__WCHAR_UNSIGNED__) EXPECT_EQ(0, BuiltInDefaultValue<wchar_t>::Get()); +#else + EXPECT_EQ(0U, BuiltInDefaultValue<wchar_t>::Get()); +#endif #endif EXPECT_EQ(0U, BuiltInDefaultValue<unsigned short>::Get()); // NOLINT EXPECT_EQ(0, BuiltInDefaultValue<signed short>::Get()); // NOLINT @@ -187,7 +192,7 @@ TEST(BuiltInDefaultValueTest, ExistsForString) { TEST(BuiltInDefaultValueTest, WorksForConstTypes) { EXPECT_EQ("", BuiltInDefaultValue<const std::string>::Get()); EXPECT_EQ(0, BuiltInDefaultValue<const int>::Get()); - EXPECT_TRUE(BuiltInDefaultValue<char* const>::Get() == NULL); + EXPECT_TRUE(BuiltInDefaultValue<char* const>::Get() == nullptr); EXPECT_FALSE(BuiltInDefaultValue<const bool>::Get()); } @@ -214,7 +219,7 @@ class MyNonDefaultConstructible { int value_; }; -#if GTEST_HAS_STD_TYPE_TRAITS_ +#if GTEST_LANG_CXX11 TEST(BuiltInDefaultValueTest, ExistsForDefaultConstructibleType) { EXPECT_TRUE(BuiltInDefaultValue<MyDefaultConstructible>::Exists()); @@ -224,7 +229,7 @@ TEST(BuiltInDefaultValueTest, IsDefaultConstructedForDefaultConstructibleType) { EXPECT_EQ(42, BuiltInDefaultValue<MyDefaultConstructible>::Get().value()); } -#endif // GTEST_HAS_STD_TYPE_TRAITS_ +#endif // GTEST_LANG_CXX11 TEST(BuiltInDefaultValueTest, DoesNotExistForNonDefaultConstructibleType) { EXPECT_FALSE(BuiltInDefaultValue<MyNonDefaultConstructible>::Exists()); @@ -297,7 +302,7 @@ TEST(DefaultValueDeathTest, GetReturnsBuiltInDefaultValueWhenUnset) { #if GTEST_HAS_STD_UNIQUE_PTR_ TEST(DefaultValueTest, GetWorksForMoveOnlyIfSet) { EXPECT_TRUE(DefaultValue<std::unique_ptr<int>>::Exists()); - EXPECT_TRUE(DefaultValue<std::unique_ptr<int>>::Get() == NULL); + EXPECT_TRUE(DefaultValue<std::unique_ptr<int>>::Get() == nullptr); DefaultValue<std::unique_ptr<int>>::SetFactory([] { return std::unique_ptr<int>(new int(42)); }); @@ -373,8 +378,8 @@ typedef int MyGlobalFunction(bool, int); class MyActionImpl : public ActionInterface<MyGlobalFunction> { public: - virtual int Perform(const tuple<bool, int>& args) { - return get<0>(args) ? get<1>(args) : 0; + virtual int Perform(const std::tuple<bool, int>& args) { + return std::get<0>(args) ? std::get<1>(args) : 0; } }; @@ -390,8 +395,8 @@ TEST(ActionInterfaceTest, MakeAction) { // it a tuple whose size and type are compatible with F's argument // types. For example, if F is int(), then Perform() takes a // 0-tuple; if F is void(bool, int), then Perform() takes a - // tuple<bool, int>, and so on. - EXPECT_EQ(5, action.Perform(make_tuple(true, 5))); + // std::tuple<bool, int>, and so on. + EXPECT_EQ(5, action.Perform(std::make_tuple(true, 5))); } // Tests that Action<F> can be contructed from a pointer to @@ -404,8 +409,8 @@ TEST(ActionTest, CanBeConstructedFromActionInterface) { TEST(ActionTest, DelegatesWorkToActionInterface) { const Action<MyGlobalFunction> action(new MyActionImpl); - EXPECT_EQ(5, action.Perform(make_tuple(true, 5))); - EXPECT_EQ(0, action.Perform(make_tuple(false, 1))); + EXPECT_EQ(5, action.Perform(std::make_tuple(true, 5))); + EXPECT_EQ(0, action.Perform(std::make_tuple(false, 1))); } // Tests that Action<F> can be copied. @@ -414,22 +419,22 @@ TEST(ActionTest, IsCopyable) { Action<MyGlobalFunction> a2(a1); // Tests the copy constructor. // a1 should continue to work after being copied from. - EXPECT_EQ(5, a1.Perform(make_tuple(true, 5))); - EXPECT_EQ(0, a1.Perform(make_tuple(false, 1))); + EXPECT_EQ(5, a1.Perform(std::make_tuple(true, 5))); + EXPECT_EQ(0, a1.Perform(std::make_tuple(false, 1))); // a2 should work like the action it was copied from. - EXPECT_EQ(5, a2.Perform(make_tuple(true, 5))); - EXPECT_EQ(0, a2.Perform(make_tuple(false, 1))); + EXPECT_EQ(5, a2.Perform(std::make_tuple(true, 5))); + EXPECT_EQ(0, a2.Perform(std::make_tuple(false, 1))); a2 = a1; // Tests the assignment operator. // a1 should continue to work after being copied from. - EXPECT_EQ(5, a1.Perform(make_tuple(true, 5))); - EXPECT_EQ(0, a1.Perform(make_tuple(false, 1))); + EXPECT_EQ(5, a1.Perform(std::make_tuple(true, 5))); + EXPECT_EQ(0, a1.Perform(std::make_tuple(false, 1))); // a2 should work like the action it was copied from. - EXPECT_EQ(5, a2.Perform(make_tuple(true, 5))); - EXPECT_EQ(0, a2.Perform(make_tuple(false, 1))); + EXPECT_EQ(5, a2.Perform(std::make_tuple(true, 5))); + EXPECT_EQ(0, a2.Perform(std::make_tuple(false, 1))); } // Tests that an Action<From> object can be converted to a @@ -437,8 +442,8 @@ TEST(ActionTest, IsCopyable) { class IsNotZero : public ActionInterface<bool(int)> { // NOLINT public: - virtual bool Perform(const tuple<int>& arg) { - return get<0>(arg) != 0; + virtual bool Perform(const std::tuple<int>& arg) { + return std::get<0>(arg) != 0; } }; @@ -451,8 +456,8 @@ class IsNotZero : public ActionInterface<bool(int)> { // NOLINT TEST(ActionTest, CanBeConvertedToOtherActionType) { const Action<bool(int)> a1(new IsNotZero); // NOLINT const Action<int(char)> a2 = Action<int(char)>(a1); // NOLINT - EXPECT_EQ(1, a2.Perform(make_tuple('a'))); - EXPECT_EQ(0, a2.Perform(make_tuple('\0'))); + EXPECT_EQ(1, a2.Perform(std::make_tuple('a'))); + EXPECT_EQ(0, a2.Perform(std::make_tuple('\0'))); } #endif // !GTEST_OS_SYMBIAN @@ -466,7 +471,9 @@ class ReturnSecondArgumentAction { // polymorphic action whose Perform() method template is either // const or not. This lets us verify the non-const case. template <typename Result, typename ArgumentTuple> - Result Perform(const ArgumentTuple& args) { return get<1>(args); } + Result Perform(const ArgumentTuple& args) { + return std::get<1>(args); + } }; // Implements a polymorphic action that can be used in a nullary @@ -481,7 +488,9 @@ class ReturnZeroFromNullaryFunctionAction { // polymorphic action whose Perform() method template is either // const or not. This lets us verify the const case. template <typename Result> - Result Perform(const tuple<>&) const { return 0; } + Result Perform(const std::tuple<>&) const { + return 0; + } }; // These functions verify that MakePolymorphicAction() returns a @@ -500,42 +509,42 @@ ReturnZeroFromNullaryFunction() { // implementation class into a polymorphic action. TEST(MakePolymorphicActionTest, ConstructsActionFromImpl) { Action<int(bool, int, double)> a1 = ReturnSecondArgument(); // NOLINT - EXPECT_EQ(5, a1.Perform(make_tuple(false, 5, 2.0))); + EXPECT_EQ(5, a1.Perform(std::make_tuple(false, 5, 2.0))); } // Tests that MakePolymorphicAction() works when the implementation // class' Perform() method template has only one template parameter. TEST(MakePolymorphicActionTest, WorksWhenPerformHasOneTemplateParameter) { Action<int()> a1 = ReturnZeroFromNullaryFunction(); - EXPECT_EQ(0, a1.Perform(make_tuple())); + EXPECT_EQ(0, a1.Perform(std::make_tuple())); Action<void*()> a2 = ReturnZeroFromNullaryFunction(); - EXPECT_TRUE(a2.Perform(make_tuple()) == NULL); + EXPECT_TRUE(a2.Perform(std::make_tuple()) == nullptr); } // Tests that Return() works as an action for void-returning // functions. TEST(ReturnTest, WorksForVoid) { const Action<void(int)> ret = Return(); // NOLINT - return ret.Perform(make_tuple(1)); + return ret.Perform(std::make_tuple(1)); } // Tests that Return(v) returns v. TEST(ReturnTest, ReturnsGivenValue) { Action<int()> ret = Return(1); // NOLINT - EXPECT_EQ(1, ret.Perform(make_tuple())); + EXPECT_EQ(1, ret.Perform(std::make_tuple())); ret = Return(-5); - EXPECT_EQ(-5, ret.Perform(make_tuple())); + EXPECT_EQ(-5, ret.Perform(std::make_tuple())); } // Tests that Return("string literal") works. TEST(ReturnTest, AcceptsStringLiteral) { Action<const char*()> a1 = Return("Hello"); - EXPECT_STREQ("Hello", a1.Perform(make_tuple())); + EXPECT_STREQ("Hello", a1.Perform(std::make_tuple())); Action<std::string()> a2 = Return("world"); - EXPECT_EQ("world", a2.Perform(make_tuple())); + EXPECT_EQ("world", a2.Perform(std::make_tuple())); } // Test struct which wraps a vector of integers. Used in @@ -554,7 +563,7 @@ TEST(ReturnTest, SupportsWrapperReturnType) { // Return() called with 'v' as argument. The Action will return the same data // as 'v' (copy) but it will be wrapped in an IntegerVectorWrapper. Action<IntegerVectorWrapper()> a = Return(v); - const std::vector<int>& result = *(a.Perform(make_tuple()).v); + const std::vector<int>& result = *(a.Perform(std::make_tuple()).v); EXPECT_THAT(result, ::testing::ElementsAre(0, 1, 2, 3, 4)); } @@ -572,10 +581,10 @@ TEST(ReturnTest, IsCovariant) { Base base; Derived derived; Action<Base*()> ret = Return(&base); - EXPECT_EQ(&base, ret.Perform(make_tuple())); + EXPECT_EQ(&base, ret.Perform(std::make_tuple())); ret = Return(&derived); - EXPECT_EQ(&derived, ret.Perform(make_tuple())); + EXPECT_EQ(&derived, ret.Perform(std::make_tuple())); } // Tests that the type of the value passed into Return is converted into T @@ -606,7 +615,7 @@ TEST(ReturnTest, ConvertsArgumentWhenConverted) { EXPECT_TRUE(converted) << "Return must convert its argument in its own " << "conversion operator."; converted = false; - action.Perform(tuple<>()); + action.Perform(std::tuple<>()); EXPECT_FALSE(converted) << "Action must NOT convert its argument " << "when performed."; } @@ -627,10 +636,10 @@ TEST(ReturnTest, CanConvertArgumentUsingNonConstTypeCastOperator) { // Tests that ReturnNull() returns NULL in a pointer-returning function. TEST(ReturnNullTest, WorksInPointerReturningFunction) { const Action<int*()> a1 = ReturnNull(); - EXPECT_TRUE(a1.Perform(make_tuple()) == NULL); + EXPECT_TRUE(a1.Perform(std::make_tuple()) == nullptr); const Action<const char*(bool)> a2 = ReturnNull(); // NOLINT - EXPECT_TRUE(a2.Perform(make_tuple(true)) == NULL); + EXPECT_TRUE(a2.Perform(std::make_tuple(true)) == nullptr); } #if GTEST_HAS_STD_UNIQUE_PTR_ @@ -638,10 +647,10 @@ TEST(ReturnNullTest, WorksInPointerReturningFunction) { // functions. TEST(ReturnNullTest, WorksInSmartPointerReturningFunction) { const Action<std::unique_ptr<const int>()> a1 = ReturnNull(); - EXPECT_TRUE(a1.Perform(make_tuple()) == nullptr); + EXPECT_TRUE(a1.Perform(std::make_tuple()) == nullptr); const Action<std::shared_ptr<int>(std::string)> a2 = ReturnNull(); - EXPECT_TRUE(a2.Perform(make_tuple("foo")) == nullptr); + EXPECT_TRUE(a2.Perform(std::make_tuple("foo")) == nullptr); } #endif // GTEST_HAS_STD_UNIQUE_PTR_ @@ -650,7 +659,7 @@ TEST(ReturnRefTest, WorksForReference) { const int n = 0; const Action<const int&(bool)> ret = ReturnRef(n); // NOLINT - EXPECT_EQ(&n, &ret.Perform(make_tuple(true))); + EXPECT_EQ(&n, &ret.Perform(std::make_tuple(true))); } // Tests that ReturnRef(v) is covariant. @@ -658,10 +667,10 @@ TEST(ReturnRefTest, IsCovariant) { Base base; Derived derived; Action<Base&()> a = ReturnRef(base); - EXPECT_EQ(&base, &a.Perform(make_tuple())); + EXPECT_EQ(&base, &a.Perform(std::make_tuple())); a = ReturnRef(derived); - EXPECT_EQ(&derived, &a.Perform(make_tuple())); + EXPECT_EQ(&derived, &a.Perform(std::make_tuple())); } // Tests that ReturnRefOfCopy(v) works for reference types. @@ -669,12 +678,12 @@ TEST(ReturnRefOfCopyTest, WorksForReference) { int n = 42; const Action<const int&()> ret = ReturnRefOfCopy(n); - EXPECT_NE(&n, &ret.Perform(make_tuple())); - EXPECT_EQ(42, ret.Perform(make_tuple())); + EXPECT_NE(&n, &ret.Perform(std::make_tuple())); + EXPECT_EQ(42, ret.Perform(std::make_tuple())); n = 43; - EXPECT_NE(&n, &ret.Perform(make_tuple())); - EXPECT_EQ(42, ret.Perform(make_tuple())); + EXPECT_NE(&n, &ret.Perform(std::make_tuple())); + EXPECT_EQ(42, ret.Perform(std::make_tuple())); } // Tests that ReturnRefOfCopy(v) is covariant. @@ -682,10 +691,10 @@ TEST(ReturnRefOfCopyTest, IsCovariant) { Base base; Derived derived; Action<Base&()> a = ReturnRefOfCopy(base); - EXPECT_NE(&base, &a.Perform(make_tuple())); + EXPECT_NE(&base, &a.Perform(std::make_tuple())); a = ReturnRefOfCopy(derived); - EXPECT_NE(&derived, &a.Perform(make_tuple())); + EXPECT_NE(&derived, &a.Perform(std::make_tuple())); } // Tests that DoDefault() does the default action for the mock method. @@ -700,6 +709,9 @@ class MockClass { MOCK_METHOD0(MakeUnique, std::unique_ptr<int>()); MOCK_METHOD0(MakeUniqueBase, std::unique_ptr<Base>()); MOCK_METHOD0(MakeVectorUnique, std::vector<std::unique_ptr<int>>()); + MOCK_METHOD1(TakeUnique, int(std::unique_ptr<int>)); + MOCK_METHOD2(TakeUnique, + int(const std::unique_ptr<int>&, std::unique_ptr<int>)); #endif private: @@ -788,14 +800,14 @@ TEST(SetArgPointeeTest, SetsTheNthPointee) { int n = 0; char ch = '\0'; - a.Perform(make_tuple(true, &n, &ch)); + a.Perform(std::make_tuple(true, &n, &ch)); EXPECT_EQ(2, n); EXPECT_EQ('\0', ch); a = SetArgPointee<2>('a'); n = 0; ch = '\0'; - a.Perform(make_tuple(true, &n, &ch)); + a.Perform(std::make_tuple(true, &n, &ch)); EXPECT_EQ(0, n); EXPECT_EQ('a', ch); } @@ -807,14 +819,14 @@ TEST(SetArgPointeeTest, AcceptsStringLiteral) { typedef void MyFunction(std::string*, const char**); Action<MyFunction> a = SetArgPointee<0>("hi"); std::string str; - const char* ptr = NULL; - a.Perform(make_tuple(&str, &ptr)); + const char* ptr = nullptr; + a.Perform(std::make_tuple(&str, &ptr)); EXPECT_EQ("hi", str); - EXPECT_TRUE(ptr == NULL); + EXPECT_TRUE(ptr == nullptr); a = SetArgPointee<1>("world"); str = ""; - a.Perform(make_tuple(&str, &ptr)); + a.Perform(std::make_tuple(&str, &ptr)); EXPECT_EQ("", str); EXPECT_STREQ("world", ptr); } @@ -822,8 +834,8 @@ TEST(SetArgPointeeTest, AcceptsStringLiteral) { TEST(SetArgPointeeTest, AcceptsWideStringLiteral) { typedef void MyFunction(const wchar_t**); Action<MyFunction> a = SetArgPointee<0>(L"world"); - const wchar_t* ptr = NULL; - a.Perform(make_tuple(&ptr)); + const wchar_t* ptr = nullptr; + a.Perform(std::make_tuple(&ptr)); EXPECT_STREQ(L"world", ptr); # if GTEST_HAS_STD_WSTRING @@ -831,7 +843,7 @@ TEST(SetArgPointeeTest, AcceptsWideStringLiteral) { typedef void MyStringFunction(std::wstring*); Action<MyStringFunction> a2 = SetArgPointee<0>(L"world"); std::wstring str = L""; - a2.Perform(make_tuple(&str)); + a2.Perform(std::make_tuple(&str)); EXPECT_EQ(L"world", str); # endif @@ -844,16 +856,16 @@ TEST(SetArgPointeeTest, AcceptsCharPointer) { const char* const hi = "hi"; Action<MyFunction> a = SetArgPointee<1>(hi); std::string str; - const char* ptr = NULL; - a.Perform(make_tuple(true, &str, &ptr)); + const char* ptr = nullptr; + a.Perform(std::make_tuple(true, &str, &ptr)); EXPECT_EQ("hi", str); - EXPECT_TRUE(ptr == NULL); + EXPECT_TRUE(ptr == nullptr); char world_array[] = "world"; char* const world = world_array; a = SetArgPointee<2>(world); str = ""; - a.Perform(make_tuple(true, &str, &ptr)); + a.Perform(std::make_tuple(true, &str, &ptr)); EXPECT_EQ("", str); EXPECT_EQ(world, ptr); } @@ -862,8 +874,8 @@ TEST(SetArgPointeeTest, AcceptsWideCharPointer) { typedef void MyFunction(bool, const wchar_t**); const wchar_t* const hi = L"hi"; Action<MyFunction> a = SetArgPointee<1>(hi); - const wchar_t* ptr = NULL; - a.Perform(make_tuple(true, &ptr)); + const wchar_t* ptr = nullptr; + a.Perform(std::make_tuple(true, &ptr)); EXPECT_EQ(hi, ptr); # if GTEST_HAS_STD_WSTRING @@ -873,110 +885,11 @@ TEST(SetArgPointeeTest, AcceptsWideCharPointer) { wchar_t* const world = world_array; Action<MyStringFunction> a2 = SetArgPointee<1>(world); std::wstring str; - a2.Perform(make_tuple(true, &str)); + a2.Perform(std::make_tuple(true, &str)); EXPECT_EQ(world_array, str); # endif } -#if GTEST_HAS_PROTOBUF_ - -// Tests that SetArgPointee<N>(proto_buffer) sets the v1 protobuf -// variable pointed to by the N-th (0-based) argument to proto_buffer. -TEST(SetArgPointeeTest, SetsTheNthPointeeOfProtoBufferType) { - TestMessage* const msg = new TestMessage; - msg->set_member("yes"); - TestMessage orig_msg; - orig_msg.CopyFrom(*msg); - - Action<void(bool, TestMessage*)> a = SetArgPointee<1>(*msg); - // SetArgPointee<N>(proto_buffer) makes a copy of proto_buffer - // s.t. the action works even when the original proto_buffer has - // died. We ensure this behavior by deleting msg before using the - // action. - delete msg; - - TestMessage dest; - EXPECT_FALSE(orig_msg.Equals(dest)); - a.Perform(make_tuple(true, &dest)); - EXPECT_TRUE(orig_msg.Equals(dest)); -} - -// Tests that SetArgPointee<N>(proto_buffer) sets the -// ::ProtocolMessage variable pointed to by the N-th (0-based) -// argument to proto_buffer. -TEST(SetArgPointeeTest, SetsTheNthPointeeOfProtoBufferBaseType) { - TestMessage* const msg = new TestMessage; - msg->set_member("yes"); - TestMessage orig_msg; - orig_msg.CopyFrom(*msg); - - Action<void(bool, ::ProtocolMessage*)> a = SetArgPointee<1>(*msg); - // SetArgPointee<N>(proto_buffer) makes a copy of proto_buffer - // s.t. the action works even when the original proto_buffer has - // died. We ensure this behavior by deleting msg before using the - // action. - delete msg; - - TestMessage dest; - ::ProtocolMessage* const dest_base = &dest; - EXPECT_FALSE(orig_msg.Equals(dest)); - a.Perform(make_tuple(true, dest_base)); - EXPECT_TRUE(orig_msg.Equals(dest)); -} - -// Tests that SetArgPointee<N>(proto2_buffer) sets the v2 -// protobuf variable pointed to by the N-th (0-based) argument to -// proto2_buffer. -TEST(SetArgPointeeTest, SetsTheNthPointeeOfProto2BufferType) { - using testing::internal::FooMessage; - FooMessage* const msg = new FooMessage; - msg->set_int_field(2); - msg->set_string_field("hi"); - FooMessage orig_msg; - orig_msg.CopyFrom(*msg); - - Action<void(bool, FooMessage*)> a = SetArgPointee<1>(*msg); - // SetArgPointee<N>(proto2_buffer) makes a copy of - // proto2_buffer s.t. the action works even when the original - // proto2_buffer has died. We ensure this behavior by deleting msg - // before using the action. - delete msg; - - FooMessage dest; - dest.set_int_field(0); - a.Perform(make_tuple(true, &dest)); - EXPECT_EQ(2, dest.int_field()); - EXPECT_EQ("hi", dest.string_field()); -} - -// Tests that SetArgPointee<N>(proto2_buffer) sets the -// proto2::Message variable pointed to by the N-th (0-based) argument -// to proto2_buffer. -TEST(SetArgPointeeTest, SetsTheNthPointeeOfProto2BufferBaseType) { - using testing::internal::FooMessage; - FooMessage* const msg = new FooMessage; - msg->set_int_field(2); - msg->set_string_field("hi"); - FooMessage orig_msg; - orig_msg.CopyFrom(*msg); - - Action<void(bool, ::proto2::Message*)> a = SetArgPointee<1>(*msg); - // SetArgPointee<N>(proto2_buffer) makes a copy of - // proto2_buffer s.t. the action works even when the original - // proto2_buffer has died. We ensure this behavior by deleting msg - // before using the action. - delete msg; - - FooMessage dest; - dest.set_int_field(0); - ::proto2::Message* const dest_base = &dest; - a.Perform(make_tuple(true, dest_base)); - EXPECT_EQ(2, dest.int_field()); - EXPECT_EQ("hi", dest.string_field()); -} - -#endif // GTEST_HAS_PROTOBUF_ - // Tests that SetArgumentPointee<N>(v) sets the variable pointed to by // the N-th (0-based) argument to v. TEST(SetArgumentPointeeTest, SetsTheNthPointee) { @@ -985,117 +898,18 @@ TEST(SetArgumentPointeeTest, SetsTheNthPointee) { int n = 0; char ch = '\0'; - a.Perform(make_tuple(true, &n, &ch)); + a.Perform(std::make_tuple(true, &n, &ch)); EXPECT_EQ(2, n); EXPECT_EQ('\0', ch); a = SetArgumentPointee<2>('a'); n = 0; ch = '\0'; - a.Perform(make_tuple(true, &n, &ch)); + a.Perform(std::make_tuple(true, &n, &ch)); EXPECT_EQ(0, n); EXPECT_EQ('a', ch); } -#if GTEST_HAS_PROTOBUF_ - -// Tests that SetArgumentPointee<N>(proto_buffer) sets the v1 protobuf -// variable pointed to by the N-th (0-based) argument to proto_buffer. -TEST(SetArgumentPointeeTest, SetsTheNthPointeeOfProtoBufferType) { - TestMessage* const msg = new TestMessage; - msg->set_member("yes"); - TestMessage orig_msg; - orig_msg.CopyFrom(*msg); - - Action<void(bool, TestMessage*)> a = SetArgumentPointee<1>(*msg); - // SetArgumentPointee<N>(proto_buffer) makes a copy of proto_buffer - // s.t. the action works even when the original proto_buffer has - // died. We ensure this behavior by deleting msg before using the - // action. - delete msg; - - TestMessage dest; - EXPECT_FALSE(orig_msg.Equals(dest)); - a.Perform(make_tuple(true, &dest)); - EXPECT_TRUE(orig_msg.Equals(dest)); -} - -// Tests that SetArgumentPointee<N>(proto_buffer) sets the -// ::ProtocolMessage variable pointed to by the N-th (0-based) -// argument to proto_buffer. -TEST(SetArgumentPointeeTest, SetsTheNthPointeeOfProtoBufferBaseType) { - TestMessage* const msg = new TestMessage; - msg->set_member("yes"); - TestMessage orig_msg; - orig_msg.CopyFrom(*msg); - - Action<void(bool, ::ProtocolMessage*)> a = SetArgumentPointee<1>(*msg); - // SetArgumentPointee<N>(proto_buffer) makes a copy of proto_buffer - // s.t. the action works even when the original proto_buffer has - // died. We ensure this behavior by deleting msg before using the - // action. - delete msg; - - TestMessage dest; - ::ProtocolMessage* const dest_base = &dest; - EXPECT_FALSE(orig_msg.Equals(dest)); - a.Perform(make_tuple(true, dest_base)); - EXPECT_TRUE(orig_msg.Equals(dest)); -} - -// Tests that SetArgumentPointee<N>(proto2_buffer) sets the v2 -// protobuf variable pointed to by the N-th (0-based) argument to -// proto2_buffer. -TEST(SetArgumentPointeeTest, SetsTheNthPointeeOfProto2BufferType) { - using testing::internal::FooMessage; - FooMessage* const msg = new FooMessage; - msg->set_int_field(2); - msg->set_string_field("hi"); - FooMessage orig_msg; - orig_msg.CopyFrom(*msg); - - Action<void(bool, FooMessage*)> a = SetArgumentPointee<1>(*msg); - // SetArgumentPointee<N>(proto2_buffer) makes a copy of - // proto2_buffer s.t. the action works even when the original - // proto2_buffer has died. We ensure this behavior by deleting msg - // before using the action. - delete msg; - - FooMessage dest; - dest.set_int_field(0); - a.Perform(make_tuple(true, &dest)); - EXPECT_EQ(2, dest.int_field()); - EXPECT_EQ("hi", dest.string_field()); -} - -// Tests that SetArgumentPointee<N>(proto2_buffer) sets the -// proto2::Message variable pointed to by the N-th (0-based) argument -// to proto2_buffer. -TEST(SetArgumentPointeeTest, SetsTheNthPointeeOfProto2BufferBaseType) { - using testing::internal::FooMessage; - FooMessage* const msg = new FooMessage; - msg->set_int_field(2); - msg->set_string_field("hi"); - FooMessage orig_msg; - orig_msg.CopyFrom(*msg); - - Action<void(bool, ::proto2::Message*)> a = SetArgumentPointee<1>(*msg); - // SetArgumentPointee<N>(proto2_buffer) makes a copy of - // proto2_buffer s.t. the action works even when the original - // proto2_buffer has died. We ensure this behavior by deleting msg - // before using the action. - delete msg; - - FooMessage dest; - dest.set_int_field(0); - ::proto2::Message* const dest_base = &dest; - a.Perform(make_tuple(true, dest_base)); - EXPECT_EQ(2, dest.int_field()); - EXPECT_EQ("hi", dest.string_field()); -} - -#endif // GTEST_HAS_PROTOBUF_ - // Sample functions and functors for testing Invoke() and etc. int Nullary() { return 1; } @@ -1126,16 +940,16 @@ class Foo { TEST(InvokeWithoutArgsTest, Function) { // As an action that takes one argument. Action<int(int)> a = InvokeWithoutArgs(Nullary); // NOLINT - EXPECT_EQ(1, a.Perform(make_tuple(2))); + EXPECT_EQ(1, a.Perform(std::make_tuple(2))); // As an action that takes two arguments. Action<int(int, double)> a2 = InvokeWithoutArgs(Nullary); // NOLINT - EXPECT_EQ(1, a2.Perform(make_tuple(2, 3.5))); + EXPECT_EQ(1, a2.Perform(std::make_tuple(2, 3.5))); // As an action that returns void. Action<void(int)> a3 = InvokeWithoutArgs(VoidNullary); // NOLINT g_done = false; - a3.Perform(make_tuple(1)); + a3.Perform(std::make_tuple(1)); EXPECT_TRUE(g_done); } @@ -1143,17 +957,17 @@ TEST(InvokeWithoutArgsTest, Function) { TEST(InvokeWithoutArgsTest, Functor) { // As an action that takes no argument. Action<int()> a = InvokeWithoutArgs(NullaryFunctor()); // NOLINT - EXPECT_EQ(2, a.Perform(make_tuple())); + EXPECT_EQ(2, a.Perform(std::make_tuple())); // As an action that takes three arguments. Action<int(int, double, char)> a2 = // NOLINT InvokeWithoutArgs(NullaryFunctor()); - EXPECT_EQ(2, a2.Perform(make_tuple(3, 3.5, 'a'))); + EXPECT_EQ(2, a2.Perform(std::make_tuple(3, 3.5, 'a'))); // As an action that returns void. Action<void()> a3 = InvokeWithoutArgs(VoidNullaryFunctor()); g_done = false; - a3.Perform(make_tuple()); + a3.Perform(std::make_tuple()); EXPECT_TRUE(g_done); } @@ -1162,13 +976,13 @@ TEST(InvokeWithoutArgsTest, Method) { Foo foo; Action<int(bool, char)> a = // NOLINT InvokeWithoutArgs(&foo, &Foo::Nullary); - EXPECT_EQ(123, a.Perform(make_tuple(true, 'a'))); + EXPECT_EQ(123, a.Perform(std::make_tuple(true, 'a'))); } // Tests using IgnoreResult() on a polymorphic action. TEST(IgnoreResultTest, PolymorphicAction) { Action<void(int)> a = IgnoreResult(Return(5)); // NOLINT - a.Perform(make_tuple(1)); + a.Perform(std::make_tuple(1)); } // Tests using IgnoreResult() on a monomorphic action. @@ -1181,7 +995,7 @@ int ReturnOne() { TEST(IgnoreResultTest, MonomorphicAction) { g_done = false; Action<void()> a = IgnoreResult(Invoke(ReturnOne)); - a.Perform(make_tuple()); + a.Perform(std::make_tuple()); EXPECT_TRUE(g_done); } @@ -1196,28 +1010,28 @@ TEST(IgnoreResultTest, ActionReturningClass) { g_done = false; Action<void(int)> a = IgnoreResult(Invoke(ReturnMyNonDefaultConstructible)); // NOLINT - a.Perform(make_tuple(2)); + a.Perform(std::make_tuple(2)); EXPECT_TRUE(g_done); } TEST(AssignTest, Int) { int x = 0; Action<void(int)> a = Assign(&x, 5); - a.Perform(make_tuple(0)); + a.Perform(std::make_tuple(0)); EXPECT_EQ(5, x); } TEST(AssignTest, String) { ::std::string x; Action<void(void)> a = Assign(&x, "Hello, world"); - a.Perform(make_tuple()); + a.Perform(std::make_tuple()); EXPECT_EQ("Hello, world", x); } TEST(AssignTest, CompatibleTypes) { double x = 0; Action<void(int)> a = Assign(&x, 5); - a.Perform(make_tuple(0)); + a.Perform(std::make_tuple(0)); EXPECT_DOUBLE_EQ(5, x); } @@ -1231,20 +1045,20 @@ class SetErrnoAndReturnTest : public testing::Test { TEST_F(SetErrnoAndReturnTest, Int) { Action<int(void)> a = SetErrnoAndReturn(ENOTTY, -5); - EXPECT_EQ(-5, a.Perform(make_tuple())); + EXPECT_EQ(-5, a.Perform(std::make_tuple())); EXPECT_EQ(ENOTTY, errno); } TEST_F(SetErrnoAndReturnTest, Ptr) { int x; Action<int*(void)> a = SetErrnoAndReturn(ENOTTY, &x); - EXPECT_EQ(&x, a.Perform(make_tuple())); + EXPECT_EQ(&x, a.Perform(std::make_tuple())); EXPECT_EQ(ENOTTY, errno); } TEST_F(SetErrnoAndReturnTest, CompatibleTypes) { Action<double()> a = SetErrnoAndReturn(EINVAL, 5); - EXPECT_DOUBLE_EQ(5.0, a.Perform(make_tuple())); + EXPECT_DOUBLE_EQ(5.0, a.Perform(std::make_tuple())); EXPECT_EQ(EINVAL, errno); } @@ -1406,6 +1220,153 @@ TEST(MockMethodTest, CanReturnMoveOnlyValue_Invoke) { EXPECT_EQ(7, *vresult[0]); } +TEST(MockMethodTest, CanTakeMoveOnlyValue) { + MockClass mock; + auto make = [](int i) { return std::unique_ptr<int>(new int(i)); }; + + EXPECT_CALL(mock, TakeUnique(_)).WillRepeatedly([](std::unique_ptr<int> i) { + return *i; + }); + // DoAll() does not compile, since it would move from its arguments twice. + // EXPECT_CALL(mock, TakeUnique(_, _)) + // .WillRepeatedly(DoAll(Invoke([](std::unique_ptr<int> j) {}), + // Return(1))); + EXPECT_CALL(mock, TakeUnique(testing::Pointee(7))) + .WillOnce(Return(-7)) + .RetiresOnSaturation(); + EXPECT_CALL(mock, TakeUnique(testing::IsNull())) + .WillOnce(Return(-1)) + .RetiresOnSaturation(); + + EXPECT_EQ(5, mock.TakeUnique(make(5))); + EXPECT_EQ(-7, mock.TakeUnique(make(7))); + EXPECT_EQ(7, mock.TakeUnique(make(7))); + EXPECT_EQ(7, mock.TakeUnique(make(7))); + EXPECT_EQ(-1, mock.TakeUnique({})); + + // Some arguments are moved, some passed by reference. + auto lvalue = make(6); + EXPECT_CALL(mock, TakeUnique(_, _)) + .WillOnce([](const std::unique_ptr<int>& i, std::unique_ptr<int> j) { + return *i * *j; + }); + EXPECT_EQ(42, mock.TakeUnique(lvalue, make(7))); + + // The unique_ptr can be saved by the action. + std::unique_ptr<int> saved; + EXPECT_CALL(mock, TakeUnique(_)).WillOnce([&saved](std::unique_ptr<int> i) { + saved = std::move(i); + return 0; + }); + EXPECT_EQ(0, mock.TakeUnique(make(42))); + EXPECT_EQ(42, *saved); +} + #endif // GTEST_HAS_STD_UNIQUE_PTR_ +#if GTEST_LANG_CXX11 +// Tests for std::function based action. + +int Add(int val, int& ref, int* ptr) { // NOLINT + int result = val + ref + *ptr; + ref = 42; + *ptr = 43; + return result; +} + +int Deref(std::unique_ptr<int> ptr) { return *ptr; } + +struct Double { + template <typename T> + T operator()(T t) { return 2 * t; } +}; + +std::unique_ptr<int> UniqueInt(int i) { + return std::unique_ptr<int>(new int(i)); +} + +TEST(FunctorActionTest, ActionFromFunction) { + Action<int(int, int&, int*)> a = &Add; + int x = 1, y = 2, z = 3; + EXPECT_EQ(6, a.Perform(std::forward_as_tuple(x, y, &z))); + EXPECT_EQ(42, y); + EXPECT_EQ(43, z); + + Action<int(std::unique_ptr<int>)> a1 = &Deref; + EXPECT_EQ(7, a1.Perform(std::make_tuple(UniqueInt(7)))); +} + +TEST(FunctorActionTest, ActionFromLambda) { + Action<int(bool, int)> a1 = [](bool b, int i) { return b ? i : 0; }; + EXPECT_EQ(5, a1.Perform(std::make_tuple(true, 5))); + EXPECT_EQ(0, a1.Perform(std::make_tuple(false, 5))); + + std::unique_ptr<int> saved; + Action<void(std::unique_ptr<int>)> a2 = [&saved](std::unique_ptr<int> p) { + saved = std::move(p); + }; + a2.Perform(std::make_tuple(UniqueInt(5))); + EXPECT_EQ(5, *saved); +} + +TEST(FunctorActionTest, PolymorphicFunctor) { + Action<int(int)> ai = Double(); + EXPECT_EQ(2, ai.Perform(std::make_tuple(1))); + Action<double(double)> ad = Double(); // Double? Double double! + EXPECT_EQ(3.0, ad.Perform(std::make_tuple(1.5))); +} + +TEST(FunctorActionTest, TypeConversion) { + // Numeric promotions are allowed. + const Action<bool(int)> a1 = [](int i) { return i > 1; }; + const Action<int(bool)> a2 = Action<int(bool)>(a1); + EXPECT_EQ(1, a1.Perform(std::make_tuple(42))); + EXPECT_EQ(0, a2.Perform(std::make_tuple(42))); + + // Implicit constructors are allowed. + const Action<bool(std::string)> s1 = [](std::string s) { return !s.empty(); }; + const Action<int(const char*)> s2 = Action<int(const char*)>(s1); + EXPECT_EQ(0, s2.Perform(std::make_tuple(""))); + EXPECT_EQ(1, s2.Perform(std::make_tuple("hello"))); + + // Also between the lambda and the action itself. + const Action<bool(std::string)> x = [](Unused) { return 42; }; + EXPECT_TRUE(x.Perform(std::make_tuple("hello"))); +} + +TEST(FunctorActionTest, UnusedArguments) { + // Verify that users can ignore uninteresting arguments. + Action<int(int, double y, double z)> a = + [](int i, Unused, Unused) { return 2 * i; }; + std::tuple<int, double, double> dummy = std::make_tuple(3, 7.3, 9.44); + EXPECT_EQ(6, a.Perform(dummy)); +} + +// Test that basic built-in actions work with move-only arguments. +// FIXME: Currently, almost all ActionInterface-based actions will not +// work, even if they only try to use other, copyable arguments. Implement them +// if necessary (but note that DoAll cannot work on non-copyable types anyway - +// so maybe it's better to make users use lambdas instead. +TEST(MoveOnlyArgumentsTest, ReturningActions) { + Action<int(std::unique_ptr<int>)> a = Return(1); + EXPECT_EQ(1, a.Perform(std::make_tuple(nullptr))); + + a = testing::WithoutArgs([]() { return 7; }); + EXPECT_EQ(7, a.Perform(std::make_tuple(nullptr))); + + Action<void(std::unique_ptr<int>, int*)> a2 = testing::SetArgPointee<1>(3); + int x = 0; + a2.Perform(std::make_tuple(nullptr, &x)); + EXPECT_EQ(x, 3); +} + +#endif // GTEST_LANG_CXX11 + } // Unnamed namespace + +#ifdef _MSC_VER +#if _MSC_VER == 1900 +# pragma warning(pop) +#endif +#endif + diff --git a/googlemock/test/gmock-cardinalities_test.cc b/googlemock/test/gmock-cardinalities_test.cc index 64815e5..132591b 100644 --- a/googlemock/test/gmock-cardinalities_test.cc +++ b/googlemock/test/gmock-cardinalities_test.cc @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // Google Mock - a framework for writing C++ mock classes. // @@ -391,7 +390,7 @@ TEST(ExactlyTest, HasCorrectBounds) { EXPECT_EQ(3, c.ConservativeUpperBound()); } -// Tests that a user can make his own cardinality by implementing +// Tests that a user can make their own cardinality by implementing // CardinalityInterface and calling MakeCardinality(). class EvenCardinality : public CardinalityInterface { diff --git a/googlemock/test/gmock-generated-actions_test.cc b/googlemock/test/gmock-generated-actions_test.cc index 5ca5bc7..2d663a5 100644 --- a/googlemock/test/gmock-generated-actions_test.cc +++ b/googlemock/test/gmock-generated-actions_test.cc @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // Google Mock - a framework for writing C++ mock classes. // @@ -46,10 +45,6 @@ namespace gmock_generated_actions_test { using ::std::plus; using ::std::string; -using testing::get; -using testing::make_tuple; -using testing::tuple; -using testing::tuple_element; using testing::_; using testing::Action; using testing::ActionInterface; @@ -81,12 +76,12 @@ bool Unary(int x) { return x < 0; } const char* Plus1(const char* s) { return s + 1; } -bool ByConstRef(const string& s) { return s == "Hi"; } +bool ByConstRef(const std::string& s) { return s == "Hi"; } const double g_double = 0; bool ReferencesGlobalDouble(const double& x) { return &x == &g_double; } -string ByNonConstRef(string& s) { return s += "+"; } // NOLINT +std::string ByNonConstRef(std::string& s) { return s += "+"; } // NOLINT struct UnaryFunctor { int operator()(bool x) { return x ? 1 : -1; } @@ -102,9 +97,9 @@ void VoidTernary(int, char, bool) { g_done = true; } int SumOf4(int a, int b, int c, int d) { return a + b + c + d; } -string Concat4(const char* s1, const char* s2, const char* s3, - const char* s4) { - return string(s1) + s2 + s3 + s4; +std::string Concat4(const char* s1, const char* s2, const char* s3, + const char* s4) { + return std::string(s1) + s2 + s3 + s4; } int SumOf5(int a, int b, int c, int d, int e) { return a + b + c + d + e; } @@ -115,9 +110,9 @@ struct SumOf5Functor { } }; -string Concat5(const char* s1, const char* s2, const char* s3, - const char* s4, const char* s5) { - return string(s1) + s2 + s3 + s4 + s5; +std::string Concat5(const char* s1, const char* s2, const char* s3, + const char* s4, const char* s5) { + return std::string(s1) + s2 + s3 + s4 + s5; } int SumOf6(int a, int b, int c, int d, int e, int f) { @@ -130,34 +125,34 @@ struct SumOf6Functor { } }; -string Concat6(const char* s1, const char* s2, const char* s3, - const char* s4, const char* s5, const char* s6) { - return string(s1) + s2 + s3 + s4 + s5 + s6; +std::string Concat6(const char* s1, const char* s2, const char* s3, + const char* s4, const char* s5, const char* s6) { + return std::string(s1) + s2 + s3 + s4 + s5 + s6; } -string Concat7(const char* s1, const char* s2, const char* s3, - const char* s4, const char* s5, const char* s6, - const char* s7) { - return string(s1) + s2 + s3 + s4 + s5 + s6 + s7; +std::string Concat7(const char* s1, const char* s2, const char* s3, + const char* s4, const char* s5, const char* s6, + const char* s7) { + return std::string(s1) + s2 + s3 + s4 + s5 + s6 + s7; } -string Concat8(const char* s1, const char* s2, const char* s3, - const char* s4, const char* s5, const char* s6, - const char* s7, const char* s8) { - return string(s1) + s2 + s3 + s4 + s5 + s6 + s7 + s8; +std::string Concat8(const char* s1, const char* s2, const char* s3, + const char* s4, const char* s5, const char* s6, + const char* s7, const char* s8) { + return std::string(s1) + s2 + s3 + s4 + s5 + s6 + s7 + s8; } -string Concat9(const char* s1, const char* s2, const char* s3, - const char* s4, const char* s5, const char* s6, - const char* s7, const char* s8, const char* s9) { - return string(s1) + s2 + s3 + s4 + s5 + s6 + s7 + s8 + s9; +std::string Concat9(const char* s1, const char* s2, const char* s3, + const char* s4, const char* s5, const char* s6, + const char* s7, const char* s8, const char* s9) { + return std::string(s1) + s2 + s3 + s4 + s5 + s6 + s7 + s8 + s9; } -string Concat10(const char* s1, const char* s2, const char* s3, - const char* s4, const char* s5, const char* s6, - const char* s7, const char* s8, const char* s9, - const char* s10) { - return string(s1) + s2 + s3 + s4 + s5 + s6 + s7 + s8 + s9 + s10; +std::string Concat10(const char* s1, const char* s2, const char* s3, + const char* s4, const char* s5, const char* s6, + const char* s7, const char* s8, const char* s9, + const char* s10) { + return std::string(s1) + s2 + s3 + s4 + s5 + s6 + s7 + s8 + s9 + s10; } // A helper that turns the type of a C-string literal from const @@ -169,85 +164,84 @@ inline const char* CharPtr(const char* s) { return s; } // Tests using InvokeArgument with a nullary function. TEST(InvokeArgumentTest, Function0) { Action<int(int, int(*)())> a = InvokeArgument<1>(); // NOLINT - EXPECT_EQ(1, a.Perform(make_tuple(2, &Nullary))); + EXPECT_EQ(1, a.Perform(std::make_tuple(2, &Nullary))); } // Tests using InvokeArgument with a unary function. TEST(InvokeArgumentTest, Functor1) { Action<int(UnaryFunctor)> a = InvokeArgument<0>(true); // NOLINT - EXPECT_EQ(1, a.Perform(make_tuple(UnaryFunctor()))); + EXPECT_EQ(1, a.Perform(std::make_tuple(UnaryFunctor()))); } // Tests using InvokeArgument with a 5-ary function. TEST(InvokeArgumentTest, Function5) { Action<int(int(*)(int, int, int, int, int))> a = // NOLINT InvokeArgument<0>(10000, 2000, 300, 40, 5); - EXPECT_EQ(12345, a.Perform(make_tuple(&SumOf5))); + EXPECT_EQ(12345, a.Perform(std::make_tuple(&SumOf5))); } // Tests using InvokeArgument with a 5-ary functor. TEST(InvokeArgumentTest, Functor5) { Action<int(SumOf5Functor)> a = // NOLINT InvokeArgument<0>(10000, 2000, 300, 40, 5); - EXPECT_EQ(12345, a.Perform(make_tuple(SumOf5Functor()))); + EXPECT_EQ(12345, a.Perform(std::make_tuple(SumOf5Functor()))); } // Tests using InvokeArgument with a 6-ary function. TEST(InvokeArgumentTest, Function6) { Action<int(int(*)(int, int, int, int, int, int))> a = // NOLINT InvokeArgument<0>(100000, 20000, 3000, 400, 50, 6); - EXPECT_EQ(123456, a.Perform(make_tuple(&SumOf6))); + EXPECT_EQ(123456, a.Perform(std::make_tuple(&SumOf6))); } // Tests using InvokeArgument with a 6-ary functor. TEST(InvokeArgumentTest, Functor6) { Action<int(SumOf6Functor)> a = // NOLINT InvokeArgument<0>(100000, 20000, 3000, 400, 50, 6); - EXPECT_EQ(123456, a.Perform(make_tuple(SumOf6Functor()))); + EXPECT_EQ(123456, a.Perform(std::make_tuple(SumOf6Functor()))); } // Tests using InvokeArgument with a 7-ary function. TEST(InvokeArgumentTest, Function7) { - Action<string(string(*)(const char*, const char*, const char*, - const char*, const char*, const char*, - const char*))> a = - InvokeArgument<0>("1", "2", "3", "4", "5", "6", "7"); - EXPECT_EQ("1234567", a.Perform(make_tuple(&Concat7))); + Action<std::string(std::string(*)(const char*, const char*, const char*, + const char*, const char*, const char*, + const char*))> + a = InvokeArgument<0>("1", "2", "3", "4", "5", "6", "7"); + EXPECT_EQ("1234567", a.Perform(std::make_tuple(&Concat7))); } // Tests using InvokeArgument with a 8-ary function. TEST(InvokeArgumentTest, Function8) { - Action<string(string(*)(const char*, const char*, const char*, - const char*, const char*, const char*, - const char*, const char*))> a = - InvokeArgument<0>("1", "2", "3", "4", "5", "6", "7", "8"); - EXPECT_EQ("12345678", a.Perform(make_tuple(&Concat8))); + Action<std::string(std::string(*)(const char*, const char*, const char*, + const char*, const char*, const char*, + const char*, const char*))> + a = InvokeArgument<0>("1", "2", "3", "4", "5", "6", "7", "8"); + EXPECT_EQ("12345678", a.Perform(std::make_tuple(&Concat8))); } // Tests using InvokeArgument with a 9-ary function. TEST(InvokeArgumentTest, Function9) { - Action<string(string(*)(const char*, const char*, const char*, - const char*, const char*, const char*, - const char*, const char*, const char*))> a = - InvokeArgument<0>("1", "2", "3", "4", "5", "6", "7", "8", "9"); - EXPECT_EQ("123456789", a.Perform(make_tuple(&Concat9))); + Action<std::string(std::string(*)(const char*, const char*, const char*, + const char*, const char*, const char*, + const char*, const char*, const char*))> + a = InvokeArgument<0>("1", "2", "3", "4", "5", "6", "7", "8", "9"); + EXPECT_EQ("123456789", a.Perform(std::make_tuple(&Concat9))); } // Tests using InvokeArgument with a 10-ary function. TEST(InvokeArgumentTest, Function10) { - Action<string(string(*)(const char*, const char*, const char*, - const char*, const char*, const char*, - const char*, const char*, const char*, - const char*))> a = - InvokeArgument<0>("1", "2", "3", "4", "5", "6", "7", "8", "9", "0"); - EXPECT_EQ("1234567890", a.Perform(make_tuple(&Concat10))); + Action<std::string(std::string(*)( + const char*, const char*, const char*, const char*, const char*, + const char*, const char*, const char*, const char*, const char*))> + a = InvokeArgument<0>("1", "2", "3", "4", "5", "6", "7", "8", "9", "0"); + EXPECT_EQ("1234567890", a.Perform(std::make_tuple(&Concat10))); } // Tests using InvokeArgument with a function that takes a pointer argument. TEST(InvokeArgumentTest, ByPointerFunction) { Action<const char*(const char*(*)(const char* input, short n))> a = // NOLINT InvokeArgument<0>(static_cast<const char*>("Hi"), Short(1)); - EXPECT_STREQ("i", a.Perform(make_tuple(&Binary))); + EXPECT_STREQ("i", a.Perform(std::make_tuple(&Binary))); } // Tests using InvokeArgument with a function that takes a const char* @@ -255,17 +249,17 @@ TEST(InvokeArgumentTest, ByPointerFunction) { TEST(InvokeArgumentTest, FunctionWithCStringLiteral) { Action<const char*(const char*(*)(const char* input, short n))> a = // NOLINT InvokeArgument<0>("Hi", Short(1)); - EXPECT_STREQ("i", a.Perform(make_tuple(&Binary))); + EXPECT_STREQ("i", a.Perform(std::make_tuple(&Binary))); } // Tests using InvokeArgument with a function that takes a const reference. TEST(InvokeArgumentTest, ByConstReferenceFunction) { - Action<bool(bool(*function)(const string& s))> a = // NOLINT - InvokeArgument<0>(string("Hi")); + Action<bool(bool (*function)(const std::string& s))> a = // NOLINT + InvokeArgument<0>(std::string("Hi")); // When action 'a' is constructed, it makes a copy of the temporary // string object passed to it, so it's OK to use 'a' later, when the // temporary object has already died. - EXPECT_TRUE(a.Perform(make_tuple(&ByConstRef))); + EXPECT_TRUE(a.Perform(std::make_tuple(&ByConstRef))); } // Tests using InvokeArgument with ByRef() and a function that takes a @@ -274,18 +268,18 @@ TEST(InvokeArgumentTest, ByExplicitConstReferenceFunction) { Action<bool(bool(*)(const double& x))> a = // NOLINT InvokeArgument<0>(ByRef(g_double)); // The above line calls ByRef() on a const value. - EXPECT_TRUE(a.Perform(make_tuple(&ReferencesGlobalDouble))); + EXPECT_TRUE(a.Perform(std::make_tuple(&ReferencesGlobalDouble))); double x = 0; a = InvokeArgument<0>(ByRef(x)); // This calls ByRef() on a non-const. - EXPECT_FALSE(a.Perform(make_tuple(&ReferencesGlobalDouble))); + EXPECT_FALSE(a.Perform(std::make_tuple(&ReferencesGlobalDouble))); } // Tests using WithArgs and with an action that takes 1 argument. TEST(WithArgsTest, OneArg) { Action<bool(double x, int n)> a = WithArgs<1>(Invoke(Unary)); // NOLINT - EXPECT_TRUE(a.Perform(make_tuple(1.5, -1))); - EXPECT_FALSE(a.Perform(make_tuple(1.5, 1))); + EXPECT_TRUE(a.Perform(std::make_tuple(1.5, -1))); + EXPECT_FALSE(a.Perform(std::make_tuple(1.5, 1))); } // Tests using WithArgs with an action that takes 2 arguments. @@ -293,105 +287,105 @@ TEST(WithArgsTest, TwoArgs) { Action<const char*(const char* s, double x, short n)> a = WithArgs<0, 2>(Invoke(Binary)); const char s[] = "Hello"; - EXPECT_EQ(s + 2, a.Perform(make_tuple(CharPtr(s), 0.5, Short(2)))); + EXPECT_EQ(s + 2, a.Perform(std::make_tuple(CharPtr(s), 0.5, Short(2)))); } // Tests using WithArgs with an action that takes 3 arguments. TEST(WithArgsTest, ThreeArgs) { Action<int(int, double, char, short)> a = // NOLINT WithArgs<0, 2, 3>(Invoke(Ternary)); - EXPECT_EQ(123, a.Perform(make_tuple(100, 6.5, Char(20), Short(3)))); + EXPECT_EQ(123, a.Perform(std::make_tuple(100, 6.5, Char(20), Short(3)))); } // Tests using WithArgs with an action that takes 4 arguments. TEST(WithArgsTest, FourArgs) { - Action<string(const char*, const char*, double, const char*, const char*)> a = - WithArgs<4, 3, 1, 0>(Invoke(Concat4)); - EXPECT_EQ("4310", a.Perform(make_tuple(CharPtr("0"), CharPtr("1"), 2.5, - CharPtr("3"), CharPtr("4")))); + Action<std::string(const char*, const char*, double, const char*, + const char*)> + a = WithArgs<4, 3, 1, 0>(Invoke(Concat4)); + EXPECT_EQ("4310", a.Perform(std::make_tuple(CharPtr("0"), CharPtr("1"), 2.5, + CharPtr("3"), CharPtr("4")))); } // Tests using WithArgs with an action that takes 5 arguments. TEST(WithArgsTest, FiveArgs) { - Action<string(const char*, const char*, const char*, - const char*, const char*)> a = - WithArgs<4, 3, 2, 1, 0>(Invoke(Concat5)); + Action<std::string(const char*, const char*, const char*, const char*, + const char*)> + a = WithArgs<4, 3, 2, 1, 0>(Invoke(Concat5)); EXPECT_EQ("43210", - a.Perform(make_tuple(CharPtr("0"), CharPtr("1"), CharPtr("2"), - CharPtr("3"), CharPtr("4")))); + a.Perform(std::make_tuple(CharPtr("0"), CharPtr("1"), CharPtr("2"), + CharPtr("3"), CharPtr("4")))); } // Tests using WithArgs with an action that takes 6 arguments. TEST(WithArgsTest, SixArgs) { - Action<string(const char*, const char*, const char*)> a = + Action<std::string(const char*, const char*, const char*)> a = WithArgs<0, 1, 2, 2, 1, 0>(Invoke(Concat6)); - EXPECT_EQ("012210", - a.Perform(make_tuple(CharPtr("0"), CharPtr("1"), CharPtr("2")))); + EXPECT_EQ("012210", a.Perform(std::make_tuple(CharPtr("0"), CharPtr("1"), + CharPtr("2")))); } // Tests using WithArgs with an action that takes 7 arguments. TEST(WithArgsTest, SevenArgs) { - Action<string(const char*, const char*, const char*, const char*)> a = + Action<std::string(const char*, const char*, const char*, const char*)> a = WithArgs<0, 1, 2, 3, 2, 1, 0>(Invoke(Concat7)); - EXPECT_EQ("0123210", - a.Perform(make_tuple(CharPtr("0"), CharPtr("1"), CharPtr("2"), - CharPtr("3")))); + EXPECT_EQ("0123210", a.Perform(std::make_tuple(CharPtr("0"), CharPtr("1"), + CharPtr("2"), CharPtr("3")))); } // Tests using WithArgs with an action that takes 8 arguments. TEST(WithArgsTest, EightArgs) { - Action<string(const char*, const char*, const char*, const char*)> a = + Action<std::string(const char*, const char*, const char*, const char*)> a = WithArgs<0, 1, 2, 3, 0, 1, 2, 3>(Invoke(Concat8)); - EXPECT_EQ("01230123", - a.Perform(make_tuple(CharPtr("0"), CharPtr("1"), CharPtr("2"), - CharPtr("3")))); + EXPECT_EQ("01230123", a.Perform(std::make_tuple(CharPtr("0"), CharPtr("1"), + CharPtr("2"), CharPtr("3")))); } // Tests using WithArgs with an action that takes 9 arguments. TEST(WithArgsTest, NineArgs) { - Action<string(const char*, const char*, const char*, const char*)> a = + Action<std::string(const char*, const char*, const char*, const char*)> a = WithArgs<0, 1, 2, 3, 1, 2, 3, 2, 3>(Invoke(Concat9)); EXPECT_EQ("012312323", - a.Perform(make_tuple(CharPtr("0"), CharPtr("1"), CharPtr("2"), - CharPtr("3")))); + a.Perform(std::make_tuple(CharPtr("0"), CharPtr("1"), CharPtr("2"), + CharPtr("3")))); } // Tests using WithArgs with an action that takes 10 arguments. TEST(WithArgsTest, TenArgs) { - Action<string(const char*, const char*, const char*, const char*)> a = + Action<std::string(const char*, const char*, const char*, const char*)> a = WithArgs<0, 1, 2, 3, 2, 1, 0, 1, 2, 3>(Invoke(Concat10)); EXPECT_EQ("0123210123", - a.Perform(make_tuple(CharPtr("0"), CharPtr("1"), CharPtr("2"), - CharPtr("3")))); + a.Perform(std::make_tuple(CharPtr("0"), CharPtr("1"), CharPtr("2"), + CharPtr("3")))); } // Tests using WithArgs with an action that is not Invoke(). class SubstractAction : public ActionInterface<int(int, int)> { // NOLINT public: - virtual int Perform(const tuple<int, int>& args) { - return get<0>(args) - get<1>(args); + virtual int Perform(const std::tuple<int, int>& args) { + return std::get<0>(args) - std::get<1>(args); } }; TEST(WithArgsTest, NonInvokeAction) { - Action<int(const string&, int, int)> a = // NOLINT + Action<int(const std::string&, int, int)> a = // NOLINT WithArgs<2, 1>(MakeAction(new SubstractAction)); - string s("hello"); - EXPECT_EQ(8, a.Perform(tuple<const string&, int, int>(s, 2, 10))); + std::tuple<std::string, int, int> dummy = + std::make_tuple(std::string("hi"), 2, 10); + EXPECT_EQ(8, a.Perform(dummy)); } // Tests using WithArgs to pass all original arguments in the original order. TEST(WithArgsTest, Identity) { Action<int(int x, char y, short z)> a = // NOLINT WithArgs<0, 1, 2>(Invoke(Ternary)); - EXPECT_EQ(123, a.Perform(make_tuple(100, Char(20), Short(3)))); + EXPECT_EQ(123, a.Perform(std::make_tuple(100, Char(20), Short(3)))); } // Tests using WithArgs with repeated arguments. TEST(WithArgsTest, RepeatedArguments) { Action<int(bool, int m, int n)> a = // NOLINT WithArgs<1, 1, 1, 1>(Invoke(SumOf4)); - EXPECT_EQ(4, a.Perform(make_tuple(false, 1, 10))); + EXPECT_EQ(4, a.Perform(std::make_tuple(false, 1, 10))); } // Tests using WithArgs with reversed argument order. @@ -399,21 +393,22 @@ TEST(WithArgsTest, ReversedArgumentOrder) { Action<const char*(short n, const char* input)> a = // NOLINT WithArgs<1, 0>(Invoke(Binary)); const char s[] = "Hello"; - EXPECT_EQ(s + 2, a.Perform(make_tuple(Short(2), CharPtr(s)))); + EXPECT_EQ(s + 2, a.Perform(std::make_tuple(Short(2), CharPtr(s)))); } // Tests using WithArgs with compatible, but not identical, argument types. TEST(WithArgsTest, ArgsOfCompatibleTypes) { Action<long(short x, char y, double z, char c)> a = // NOLINT WithArgs<0, 1, 3>(Invoke(Ternary)); - EXPECT_EQ(123, a.Perform(make_tuple(Short(100), Char(20), 5.6, Char(3)))); + EXPECT_EQ(123, + a.Perform(std::make_tuple(Short(100), Char(20), 5.6, Char(3)))); } // Tests using WithArgs with an action that returns void. TEST(WithArgsTest, VoidAction) { Action<void(double x, char c, int n)> a = WithArgs<2, 1>(Invoke(VoidBinary)); g_done = false; - a.Perform(make_tuple(1.5, 'a', 3)); + a.Perform(std::make_tuple(1.5, 'a', 3)); EXPECT_TRUE(g_done); } @@ -422,7 +417,7 @@ TEST(DoAllTest, TwoActions) { int n = 0; Action<int(int*)> a = DoAll(SetArgPointee<0>(1), // NOLINT Return(2)); - EXPECT_EQ(2, a.Perform(make_tuple(&n))); + EXPECT_EQ(2, a.Perform(std::make_tuple(&n))); EXPECT_EQ(1, n); } @@ -432,7 +427,7 @@ TEST(DoAllTest, ThreeActions) { Action<int(int*, int*)> a = DoAll(SetArgPointee<0>(1), // NOLINT SetArgPointee<1>(2), Return(3)); - EXPECT_EQ(3, a.Perform(make_tuple(&m, &n))); + EXPECT_EQ(3, a.Perform(std::make_tuple(&m, &n))); EXPECT_EQ(1, m); EXPECT_EQ(2, n); } @@ -446,7 +441,7 @@ TEST(DoAllTest, FourActions) { SetArgPointee<1>(2), SetArgPointee<2>('a'), Return(3)); - EXPECT_EQ(3, a.Perform(make_tuple(&m, &n, &ch))); + EXPECT_EQ(3, a.Perform(std::make_tuple(&m, &n, &ch))); EXPECT_EQ(1, m); EXPECT_EQ(2, n); EXPECT_EQ('a', ch); @@ -462,7 +457,7 @@ TEST(DoAllTest, FiveActions) { SetArgPointee<2>('a'), SetArgPointee<3>('b'), Return(3)); - EXPECT_EQ(3, action.Perform(make_tuple(&m, &n, &a, &b))); + EXPECT_EQ(3, action.Perform(std::make_tuple(&m, &n, &a, &b))); EXPECT_EQ(1, m); EXPECT_EQ(2, n); EXPECT_EQ('a', a); @@ -480,7 +475,7 @@ TEST(DoAllTest, SixActions) { SetArgPointee<3>('b'), SetArgPointee<4>('c'), Return(3)); - EXPECT_EQ(3, action.Perform(make_tuple(&m, &n, &a, &b, &c))); + EXPECT_EQ(3, action.Perform(std::make_tuple(&m, &n, &a, &b, &c))); EXPECT_EQ(1, m); EXPECT_EQ(2, n); EXPECT_EQ('a', a); @@ -500,7 +495,7 @@ TEST(DoAllTest, SevenActions) { SetArgPointee<4>('c'), SetArgPointee<5>('d'), Return(3)); - EXPECT_EQ(3, action.Perform(make_tuple(&m, &n, &a, &b, &c, &d))); + EXPECT_EQ(3, action.Perform(std::make_tuple(&m, &n, &a, &b, &c, &d))); EXPECT_EQ(1, m); EXPECT_EQ(2, n); EXPECT_EQ('a', a); @@ -523,7 +518,7 @@ TEST(DoAllTest, EightActions) { SetArgPointee<5>('d'), SetArgPointee<6>('e'), Return(3)); - EXPECT_EQ(3, action.Perform(make_tuple(&m, &n, &a, &b, &c, &d, &e))); + EXPECT_EQ(3, action.Perform(std::make_tuple(&m, &n, &a, &b, &c, &d, &e))); EXPECT_EQ(1, m); EXPECT_EQ(2, n); EXPECT_EQ('a', a); @@ -548,7 +543,7 @@ TEST(DoAllTest, NineActions) { SetArgPointee<6>('e'), SetArgPointee<7>('f'), Return(3)); - EXPECT_EQ(3, action.Perform(make_tuple(&m, &n, &a, &b, &c, &d, &e, &f))); + EXPECT_EQ(3, action.Perform(std::make_tuple(&m, &n, &a, &b, &c, &d, &e, &f))); EXPECT_EQ(1, m); EXPECT_EQ(2, n); EXPECT_EQ('a', a); @@ -576,7 +571,8 @@ TEST(DoAllTest, TenActions) { SetArgPointee<7>('f'), SetArgPointee<8>('g'), Return(3)); - EXPECT_EQ(3, action.Perform(make_tuple(&m, &n, &a, &b, &c, &d, &e, &f, &g))); + EXPECT_EQ( + 3, action.Perform(std::make_tuple(&m, &n, &a, &b, &c, &d, &e, &f, &g))); EXPECT_EQ(1, m); EXPECT_EQ(2, n); EXPECT_EQ('a', a); @@ -606,10 +602,10 @@ ACTION(Return5) { return 5; } TEST(ActionMacroTest, WorksWhenNotReferencingArguments) { Action<double()> a1 = Return5(); - EXPECT_DOUBLE_EQ(5, a1.Perform(make_tuple())); + EXPECT_DOUBLE_EQ(5, a1.Perform(std::make_tuple())); Action<int(double, bool)> a2 = Return5(); - EXPECT_EQ(5, a2.Perform(make_tuple(1, true))); + EXPECT_EQ(5, a2.Perform(std::make_tuple(1, true))); } // Tests that ACTION() can define an action that returns void. @@ -618,7 +614,7 @@ ACTION(IncrementArg1) { (*arg1)++; } TEST(ActionMacroTest, WorksWhenReturningVoid) { Action<void(int, int*)> a1 = IncrementArg1(); int n = 0; - a1.Perform(make_tuple(5, &n)); + a1.Perform(std::make_tuple(5, &n)); EXPECT_EQ(1, n); } @@ -633,22 +629,22 @@ ACTION(IncrementArg2) { TEST(ActionMacroTest, CanReferenceArgumentType) { Action<void(int, bool, int*)> a1 = IncrementArg2(); int n = 0; - a1.Perform(make_tuple(5, false, &n)); + a1.Perform(std::make_tuple(5, false, &n)); EXPECT_EQ(1, n); } // Tests that the body of ACTION() can reference the argument tuple // via args_type and args. ACTION(Sum2) { - StaticAssertTypeEq<tuple<int, char, int*>, args_type>(); + StaticAssertTypeEq<std::tuple<int, char, int*>, args_type>(); args_type args_copy = args; - return get<0>(args_copy) + get<1>(args_copy); + return std::get<0>(args_copy) + std::get<1>(args_copy); } TEST(ActionMacroTest, CanReferenceArgumentTuple) { Action<int(int, char, int*)> a1 = Sum2(); int dummy = 0; - EXPECT_EQ(11, a1.Perform(make_tuple(5, Char(6), &dummy))); + EXPECT_EQ(11, a1.Perform(std::make_tuple(5, Char(6), &dummy))); } // Tests that the body of ACTION() can reference the mock function @@ -663,8 +659,8 @@ ACTION(InvokeDummy) { TEST(ActionMacroTest, CanReferenceMockFunctionType) { Action<int(bool)> a1 = InvokeDummy(); - EXPECT_EQ(1, a1.Perform(make_tuple(true))); - EXPECT_EQ(1, a1.Perform(make_tuple(false))); + EXPECT_EQ(1, a1.Perform(std::make_tuple(true))); + EXPECT_EQ(1, a1.Perform(std::make_tuple(false))); } // Tests that the body of ACTION() can reference the mock function's @@ -677,8 +673,8 @@ ACTION(InvokeDummy2) { TEST(ActionMacroTest, CanReferenceMockFunctionReturnType) { Action<int(bool)> a1 = InvokeDummy2(); - EXPECT_EQ(1, a1.Perform(make_tuple(true))); - EXPECT_EQ(1, a1.Perform(make_tuple(false))); + EXPECT_EQ(1, a1.Perform(std::make_tuple(true))); + EXPECT_EQ(1, a1.Perform(std::make_tuple(false))); } // Tests that ACTION() works for arguments passed by const reference. @@ -690,7 +686,7 @@ ACTION(ReturnAddrOfConstBoolReferenceArg) { TEST(ActionMacroTest, WorksForConstReferenceArg) { Action<const bool*(int, const bool&)> a = ReturnAddrOfConstBoolReferenceArg(); const bool b = false; - EXPECT_EQ(&b, a.Perform(tuple<int, const bool&>(0, b))); + EXPECT_EQ(&b, a.Perform(std::tuple<int, const bool&>(0, b))); } // Tests that ACTION() works for arguments passed by non-const reference. @@ -702,7 +698,7 @@ ACTION(ReturnAddrOfIntReferenceArg) { TEST(ActionMacroTest, WorksForNonConstReferenceArg) { Action<int*(int&, bool, int)> a = ReturnAddrOfIntReferenceArg(); int n = 0; - EXPECT_EQ(&n, a.Perform(tuple<int&, bool, int>(n, true, 1))); + EXPECT_EQ(&n, a.Perform(std::tuple<int&, bool, int>(n, true, 1))); } // Tests that ACTION() can be used in a namespace. @@ -712,7 +708,7 @@ ACTION(Sum) { return arg0 + arg1; } TEST(ActionMacroTest, WorksInNamespace) { Action<int(int, int)> a1 = action_test::Sum(); - EXPECT_EQ(3, a1.Perform(make_tuple(1, 2))); + EXPECT_EQ(3, a1.Perform(std::make_tuple(1, 2))); } // Tests that the same ACTION definition works for mock functions with @@ -721,11 +717,11 @@ ACTION(PlusTwo) { return arg0 + 2; } TEST(ActionMacroTest, WorksForDifferentArgumentNumbers) { Action<int(int)> a1 = PlusTwo(); - EXPECT_EQ(4, a1.Perform(make_tuple(2))); + EXPECT_EQ(4, a1.Perform(std::make_tuple(2))); Action<double(float, void*)> a2 = PlusTwo(); int dummy; - EXPECT_DOUBLE_EQ(6, a2.Perform(make_tuple(4.0f, &dummy))); + EXPECT_DOUBLE_EQ(6, a2.Perform(std::make_tuple(4.0f, &dummy))); } // Tests that ACTION_P can define a parameterized action. @@ -733,7 +729,7 @@ ACTION_P(Plus, n) { return arg0 + n; } TEST(ActionPMacroTest, DefinesParameterizedAction) { Action<int(int m, bool t)> a1 = Plus(9); - EXPECT_EQ(10, a1.Perform(make_tuple(1, true))); + EXPECT_EQ(10, a1.Perform(std::make_tuple(1, true))); } // Tests that the body of ACTION_P can reference the argument types @@ -746,7 +742,7 @@ ACTION_P(TypedPlus, n) { TEST(ActionPMacroTest, CanReferenceArgumentAndParameterTypes) { Action<int(char m, bool t)> a1 = TypedPlus(9); - EXPECT_EQ(10, a1.Perform(make_tuple(Char(1), true))); + EXPECT_EQ(10, a1.Perform(std::make_tuple(Char(1), true))); } // Tests that a parameterized action can be used in any mock function @@ -754,7 +750,8 @@ TEST(ActionPMacroTest, CanReferenceArgumentAndParameterTypes) { TEST(ActionPMacroTest, WorksInCompatibleMockFunction) { Action<std::string(const std::string& s)> a1 = Plus("tail"); const std::string re = "re"; - EXPECT_EQ("retail", a1.Perform(tuple<const std::string&>(re))); + std::tuple<const std::string> dummy = std::make_tuple(re); + EXPECT_EQ("retail", a1.Perform(dummy)); } // Tests that we can use ACTION*() to define actions overloaded on the @@ -774,16 +771,16 @@ TEST(ActionMacroTest, CanDefineOverloadedActions) { typedef Action<const char*(bool, const char*)> MyAction; const MyAction a1 = OverloadedAction(); - EXPECT_STREQ("hello", a1.Perform(make_tuple(false, CharPtr("world")))); - EXPECT_STREQ("world", a1.Perform(make_tuple(true, CharPtr("world")))); + EXPECT_STREQ("hello", a1.Perform(std::make_tuple(false, CharPtr("world")))); + EXPECT_STREQ("world", a1.Perform(std::make_tuple(true, CharPtr("world")))); const MyAction a2 = OverloadedAction("hi"); - EXPECT_STREQ("hi", a2.Perform(make_tuple(false, CharPtr("world")))); - EXPECT_STREQ("world", a2.Perform(make_tuple(true, CharPtr("world")))); + EXPECT_STREQ("hi", a2.Perform(std::make_tuple(false, CharPtr("world")))); + EXPECT_STREQ("world", a2.Perform(std::make_tuple(true, CharPtr("world")))); const MyAction a3 = OverloadedAction("hi", "you"); - EXPECT_STREQ("hi", a3.Perform(make_tuple(true, CharPtr("world")))); - EXPECT_STREQ("you", a3.Perform(make_tuple(false, CharPtr("world")))); + EXPECT_STREQ("hi", a3.Perform(std::make_tuple(true, CharPtr("world")))); + EXPECT_STREQ("you", a3.Perform(std::make_tuple(false, CharPtr("world")))); } // Tests ACTION_Pn where n >= 3. @@ -792,25 +789,26 @@ ACTION_P3(Plus, m, n, k) { return arg0 + m + n + k; } TEST(ActionPnMacroTest, WorksFor3Parameters) { Action<double(int m, bool t)> a1 = Plus(100, 20, 3.4); - EXPECT_DOUBLE_EQ(3123.4, a1.Perform(make_tuple(3000, true))); + EXPECT_DOUBLE_EQ(3123.4, a1.Perform(std::make_tuple(3000, true))); Action<std::string(const std::string& s)> a2 = Plus("tail", "-", ">"); const std::string re = "re"; - EXPECT_EQ("retail->", a2.Perform(tuple<const std::string&>(re))); + std::tuple<const std::string> dummy = std::make_tuple(re); + EXPECT_EQ("retail->", a2.Perform(dummy)); } ACTION_P4(Plus, p0, p1, p2, p3) { return arg0 + p0 + p1 + p2 + p3; } TEST(ActionPnMacroTest, WorksFor4Parameters) { Action<int(int)> a1 = Plus(1, 2, 3, 4); - EXPECT_EQ(10 + 1 + 2 + 3 + 4, a1.Perform(make_tuple(10))); + EXPECT_EQ(10 + 1 + 2 + 3 + 4, a1.Perform(std::make_tuple(10))); } ACTION_P5(Plus, p0, p1, p2, p3, p4) { return arg0 + p0 + p1 + p2 + p3 + p4; } TEST(ActionPnMacroTest, WorksFor5Parameters) { Action<int(int)> a1 = Plus(1, 2, 3, 4, 5); - EXPECT_EQ(10 + 1 + 2 + 3 + 4 + 5, a1.Perform(make_tuple(10))); + EXPECT_EQ(10 + 1 + 2 + 3 + 4 + 5, a1.Perform(std::make_tuple(10))); } ACTION_P6(Plus, p0, p1, p2, p3, p4, p5) { @@ -819,7 +817,7 @@ ACTION_P6(Plus, p0, p1, p2, p3, p4, p5) { TEST(ActionPnMacroTest, WorksFor6Parameters) { Action<int(int)> a1 = Plus(1, 2, 3, 4, 5, 6); - EXPECT_EQ(10 + 1 + 2 + 3 + 4 + 5 + 6, a1.Perform(make_tuple(10))); + EXPECT_EQ(10 + 1 + 2 + 3 + 4 + 5 + 6, a1.Perform(std::make_tuple(10))); } ACTION_P7(Plus, p0, p1, p2, p3, p4, p5, p6) { @@ -828,7 +826,7 @@ ACTION_P7(Plus, p0, p1, p2, p3, p4, p5, p6) { TEST(ActionPnMacroTest, WorksFor7Parameters) { Action<int(int)> a1 = Plus(1, 2, 3, 4, 5, 6, 7); - EXPECT_EQ(10 + 1 + 2 + 3 + 4 + 5 + 6 + 7, a1.Perform(make_tuple(10))); + EXPECT_EQ(10 + 1 + 2 + 3 + 4 + 5 + 6 + 7, a1.Perform(std::make_tuple(10))); } ACTION_P8(Plus, p0, p1, p2, p3, p4, p5, p6, p7) { @@ -837,7 +835,8 @@ ACTION_P8(Plus, p0, p1, p2, p3, p4, p5, p6, p7) { TEST(ActionPnMacroTest, WorksFor8Parameters) { Action<int(int)> a1 = Plus(1, 2, 3, 4, 5, 6, 7, 8); - EXPECT_EQ(10 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8, a1.Perform(make_tuple(10))); + EXPECT_EQ(10 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8, + a1.Perform(std::make_tuple(10))); } ACTION_P9(Plus, p0, p1, p2, p3, p4, p5, p6, p7, p8) { @@ -846,7 +845,8 @@ ACTION_P9(Plus, p0, p1, p2, p3, p4, p5, p6, p7, p8) { TEST(ActionPnMacroTest, WorksFor9Parameters) { Action<int(int)> a1 = Plus(1, 2, 3, 4, 5, 6, 7, 8, 9); - EXPECT_EQ(10 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9, a1.Perform(make_tuple(10))); + EXPECT_EQ(10 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9, + a1.Perform(std::make_tuple(10))); } ACTION_P10(Plus, p0, p1, p2, p3, p4, p5, p6, p7, p8, last_param) { @@ -858,7 +858,7 @@ ACTION_P10(Plus, p0, p1, p2, p3, p4, p5, p6, p7, p8, last_param) { TEST(ActionPnMacroTest, WorksFor10Parameters) { Action<int(int)> a1 = Plus(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); EXPECT_EQ(10 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10, - a1.Perform(make_tuple(10))); + a1.Perform(std::make_tuple(10))); } // Tests that the action body can promote the parameter types. @@ -875,8 +875,8 @@ TEST(ActionPnMacroTest, SimpleTypePromotion) { PadArgument(std::string("foo"), 'r'); Action<std::string(const char*)> promo = PadArgument("foo", static_cast<int>('r')); - EXPECT_EQ("foobar", no_promo.Perform(make_tuple(CharPtr("ba")))); - EXPECT_EQ("foobar", promo.Perform(make_tuple(CharPtr("ba")))); + EXPECT_EQ("foobar", no_promo.Perform(std::make_tuple(CharPtr("ba")))); + EXPECT_EQ("foobar", promo.Perform(std::make_tuple(CharPtr("ba")))); } // Tests that we can partially restrict parameter types using a @@ -925,10 +925,10 @@ Concat(T1 a, int b, T2 c) { TEST(ActionPnMacroTest, CanPartiallyRestrictParameterTypes) { Action<const std::string()> a1 = Concat("Hello", "1", 2); - EXPECT_EQ("Hello12", a1.Perform(make_tuple())); + EXPECT_EQ("Hello12", a1.Perform(std::make_tuple())); a1 = Concat(1, 2, 3); - EXPECT_EQ("123", a1.Perform(make_tuple())); + EXPECT_EQ("123", a1.Perform(std::make_tuple())); } // Verifies the type of an ACTION*. @@ -986,7 +986,7 @@ ACTION_P10(Plus10, a0, a1, a2, a3, a4, a5, a6, a7, a8, a9) { TEST(ActionPnMacroTest, CanExplicitlyInstantiateWithReferenceTypes) { int x = 1, y = 2, z = 3; - const tuple<> empty = make_tuple(); + const std::tuple<> empty = std::make_tuple(); Action<int()> a = Plus1<int&>(x); EXPECT_EQ(1, a.Perform(empty)); @@ -1013,7 +1013,7 @@ class NullaryConstructorClass { // Tests using ReturnNew() with a nullary constructor. TEST(ReturnNewTest, NoArgs) { Action<NullaryConstructorClass*()> a = ReturnNew<NullaryConstructorClass>(); - NullaryConstructorClass* c = a.Perform(make_tuple()); + NullaryConstructorClass* c = a.Perform(std::make_tuple()); EXPECT_EQ(123, c->value_); delete c; } @@ -1027,7 +1027,7 @@ class UnaryConstructorClass { // Tests using ReturnNew() with a unary constructor. TEST(ReturnNewTest, Unary) { Action<UnaryConstructorClass*()> a = ReturnNew<UnaryConstructorClass>(4000); - UnaryConstructorClass* c = a.Perform(make_tuple()); + UnaryConstructorClass* c = a.Perform(std::make_tuple()); EXPECT_EQ(4000, c->value_); delete c; } @@ -1035,7 +1035,7 @@ TEST(ReturnNewTest, Unary) { TEST(ReturnNewTest, UnaryWorksWhenMockMethodHasArgs) { Action<UnaryConstructorClass*(bool, int)> a = ReturnNew<UnaryConstructorClass>(4000); - UnaryConstructorClass* c = a.Perform(make_tuple(false, 5)); + UnaryConstructorClass* c = a.Perform(std::make_tuple(false, 5)); EXPECT_EQ(4000, c->value_); delete c; } @@ -1043,7 +1043,7 @@ TEST(ReturnNewTest, UnaryWorksWhenMockMethodHasArgs) { TEST(ReturnNewTest, UnaryWorksWhenMockMethodReturnsPointerToConst) { Action<const UnaryConstructorClass*()> a = ReturnNew<UnaryConstructorClass>(4000); - const UnaryConstructorClass* c = a.Perform(make_tuple()); + const UnaryConstructorClass* c = a.Perform(std::make_tuple()); EXPECT_EQ(4000, c->value_); delete c; } @@ -1063,7 +1063,7 @@ TEST(ReturnNewTest, ConstructorThatTakes10Arguments) { ReturnNew<TenArgConstructorClass>(1000000000, 200000000, 30000000, 4000000, 500000, 60000, 7000, 800, 90, 0); - TenArgConstructorClass* c = a.Perform(make_tuple()); + TenArgConstructorClass* c = a.Perform(std::make_tuple()); EXPECT_EQ(1234567890, c->value_); delete c; } @@ -1077,7 +1077,7 @@ ACTION_TEMPLATE(CreateNew, TEST(ActionTemplateTest, WorksWithoutValueParam) { const Action<int*()> a = CreateNew<int>(); - int* p = a.Perform(make_tuple()); + int* p = a.Perform(std::make_tuple()); delete p; } @@ -1090,7 +1090,7 @@ ACTION_TEMPLATE(CreateNew, TEST(ActionTemplateTest, WorksWithValueParams) { const Action<int*()> a = CreateNew<int>(42); - int* p = a.Perform(make_tuple()); + int* p = a.Perform(std::make_tuple()); EXPECT_EQ(42, *p); delete p; } @@ -1099,7 +1099,7 @@ TEST(ActionTemplateTest, WorksWithValueParams) { ACTION_TEMPLATE(MyDeleteArg, HAS_1_TEMPLATE_PARAMS(int, k), AND_0_VALUE_PARAMS()) { - delete get<k>(args); + delete std::get<k>(args); } // Resets a bool variable in the destructor. @@ -1116,7 +1116,7 @@ TEST(ActionTemplateTest, WorksForIntegralTemplateParams) { int n = 0; bool b = true; BoolResetter* resetter = new BoolResetter(&b); - a.Perform(make_tuple(&n, resetter)); + a.Perform(std::make_tuple(&n, resetter)); EXPECT_FALSE(b); // Verifies that resetter is deleted. } @@ -1131,7 +1131,7 @@ ACTION_TEMPLATE(ReturnSmartPointer, TEST(ActionTemplateTest, WorksForTemplateTemplateParameters) { using ::testing::internal::linked_ptr; const Action<linked_ptr<int>()> a = ReturnSmartPointer<linked_ptr>(42); - linked_ptr<int> p = a.Perform(make_tuple()); + linked_ptr<int> p = a.Perform(std::make_tuple()); EXPECT_EQ(42, *p); } @@ -1166,7 +1166,7 @@ TEST(ActionTemplateTest, WorksFor10TemplateParameters) { true, 6, char, unsigned, int> Giant; const Action<Giant()> a = ReturnGiant< int, bool, double, 5, true, 6, char, unsigned, int, linked_ptr>(42); - Giant giant = a.Perform(make_tuple()); + Giant giant = a.Perform(std::make_tuple()); EXPECT_EQ(42, giant.value); } @@ -1179,7 +1179,7 @@ ACTION_TEMPLATE(ReturnSum, TEST(ActionTemplateTest, WorksFor10ValueParameters) { const Action<int()> a = ReturnSum<int>(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); - EXPECT_EQ(55, a.Perform(make_tuple())); + EXPECT_EQ(55, a.Perform(std::make_tuple())); } // Tests that ACTION_TEMPLATE and ACTION/ACTION_P* can be overloaded @@ -1213,11 +1213,11 @@ TEST(ActionTemplateTest, CanBeOverloadedOnNumberOfValueParameters) { const Action<int()> a2 = ReturnSum<int>(1, 2); const Action<int()> a3 = ReturnSum<int>(1, 2, 3); const Action<int()> a4 = ReturnSum<int, 10000>(2000, 300, 40, 5); - EXPECT_EQ(0, a0.Perform(make_tuple())); - EXPECT_EQ(1, a1.Perform(make_tuple())); - EXPECT_EQ(3, a2.Perform(make_tuple())); - EXPECT_EQ(6, a3.Perform(make_tuple())); - EXPECT_EQ(12345, a4.Perform(make_tuple())); + EXPECT_EQ(0, a0.Perform(std::make_tuple())); + EXPECT_EQ(1, a1.Perform(std::make_tuple())); + EXPECT_EQ(3, a2.Perform(std::make_tuple())); + EXPECT_EQ(6, a3.Perform(std::make_tuple())); + EXPECT_EQ(12345, a4.Perform(std::make_tuple())); } #ifdef _MSC_VER diff --git a/googlemock/test/gmock-generated-function-mockers_test.cc b/googlemock/test/gmock-generated-function-mockers_test.cc index a86a613..820a2b6 100644 --- a/googlemock/test/gmock-generated-function-mockers_test.cc +++ b/googlemock/test/gmock-generated-function-mockers_test.cc @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // Google Mock - a framework for writing C++ mock classes. // @@ -57,7 +56,6 @@ namespace testing { namespace gmock_generated_function_mockers_test { -using testing::internal::string; using testing::_; using testing::A; using testing::An; @@ -82,11 +80,11 @@ class FooInterface { virtual bool Unary(int x) = 0; virtual long Binary(short x, int y) = 0; // NOLINT virtual int Decimal(bool b, char c, short d, int e, long f, // NOLINT - float g, double h, unsigned i, char* j, const string& k) - = 0; + float g, double h, unsigned i, char* j, + const std::string& k) = 0; virtual bool TakesNonConstReference(int& n) = 0; // NOLINT - virtual string TakesConstReference(const int& n) = 0; + virtual std::string TakesConstReference(const int& n) = 0; #ifdef GMOCK_ALLOWS_CONST_PARAM_FUNCTIONS virtual bool TakesConst(const int x) = 0; #endif // GMOCK_ALLOWS_CONST_PARAM_FUNCTIONS @@ -101,13 +99,14 @@ class FooInterface { virtual char OverloadedOnConstness() const = 0; virtual int TypeWithHole(int (*func)()) = 0; - virtual int TypeWithComma(const std::map<int, string>& a_map) = 0; + virtual int TypeWithComma(const std::map<int, std::string>& a_map) = 0; #if GTEST_OS_WINDOWS STDMETHOD_(int, CTNullary)() = 0; STDMETHOD_(bool, CTUnary)(int x) = 0; - STDMETHOD_(int, CTDecimal)(bool b, char c, short d, int e, long f, // NOLINT - float g, double h, unsigned i, char* j, const string& k) = 0; + STDMETHOD_(int, CTDecimal) + (bool b, char c, short d, int e, long f, // NOLINT + float g, double h, unsigned i, char* j, const std::string& k) = 0; STDMETHOD_(char, CTConst)(int x) const = 0; #endif // GTEST_OS_WINDOWS }; @@ -133,19 +132,19 @@ class MockFoo : public FooInterface { MOCK_METHOD1(Unary, bool(int)); // NOLINT MOCK_METHOD2(Binary, long(short, int)); // NOLINT MOCK_METHOD10(Decimal, int(bool, char, short, int, long, float, // NOLINT - double, unsigned, char*, const string& str)); + double, unsigned, char*, const std::string& str)); MOCK_METHOD1(TakesNonConstReference, bool(int&)); // NOLINT - MOCK_METHOD1(TakesConstReference, string(const int&)); + MOCK_METHOD1(TakesConstReference, std::string(const int&)); #ifdef GMOCK_ALLOWS_CONST_PARAM_FUNCTIONS MOCK_METHOD1(TakesConst, bool(const int)); // NOLINT #endif // Tests that the function return type can contain unprotected comma. - MOCK_METHOD0(ReturnTypeWithComma, std::map<int, string>()); + MOCK_METHOD0(ReturnTypeWithComma, std::map<int, std::string>()); MOCK_CONST_METHOD1(ReturnTypeWithComma, - std::map<int, string>(int)); // NOLINT + std::map<int, std::string>(int)); // NOLINT MOCK_METHOD0(OverloadedOnArgumentNumber, int()); // NOLINT MOCK_METHOD1(OverloadedOnArgumentNumber, int(int)); // NOLINT @@ -157,19 +156,21 @@ class MockFoo : public FooInterface { MOCK_CONST_METHOD0(OverloadedOnConstness, char()); // NOLINT MOCK_METHOD1(TypeWithHole, int(int (*)())); // NOLINT - MOCK_METHOD1(TypeWithComma, int(const std::map<int, string>&)); // NOLINT + MOCK_METHOD1(TypeWithComma, + int(const std::map<int, std::string>&)); // NOLINT #if GTEST_OS_WINDOWS MOCK_METHOD0_WITH_CALLTYPE(STDMETHODCALLTYPE, CTNullary, int()); MOCK_METHOD1_WITH_CALLTYPE(STDMETHODCALLTYPE, CTUnary, bool(int)); - MOCK_METHOD10_WITH_CALLTYPE(STDMETHODCALLTYPE, CTDecimal, int(bool b, char c, - short d, int e, long f, float g, double h, unsigned i, char* j, - const string& k)); + MOCK_METHOD10_WITH_CALLTYPE(STDMETHODCALLTYPE, CTDecimal, + int(bool b, char c, short d, int e, long f, + float g, double h, unsigned i, char* j, + const std::string& k)); MOCK_CONST_METHOD1_WITH_CALLTYPE(STDMETHODCALLTYPE, CTConst, char(int)); // Tests that the function return type can contain unprotected comma. MOCK_METHOD0_WITH_CALLTYPE(STDMETHODCALLTYPE, CTReturnTypeWithComma, - std::map<int, string>()); + std::map<int, std::string>()); #endif // GTEST_OS_WINDOWS private: @@ -227,7 +228,7 @@ TEST_F(FunctionMockerTest, MocksDecimalFunction) { Lt(100), 5U, NULL, "hi")) .WillOnce(Return(5)); - EXPECT_EQ(5, foo_->Decimal(true, 'a', 0, 0, 1, 0, 0, 5, NULL, "hi")); + EXPECT_EQ(5, foo_->Decimal(true, 'a', 0, 0, 1, 0, 0, 5, nullptr, "hi")); } // Tests mocking a function that takes a non-const reference. @@ -291,7 +292,7 @@ TEST_F(FunctionMockerTest, MocksFunctionsOverloadedOnConstnessOfThis) { } TEST_F(FunctionMockerTest, MocksReturnTypeWithComma) { - const std::map<int, string> a_map; + const std::map<int, std::string> a_map; EXPECT_CALL(mock_foo_, ReturnTypeWithComma()) .WillOnce(Return(a_map)); EXPECT_CALL(mock_foo_, ReturnTypeWithComma(42)) @@ -341,7 +342,7 @@ TEST_F(FunctionMockerTest, MocksFunctionsConstFunctionWithCallType) { } TEST_F(FunctionMockerTest, MocksReturnTypeWithCommaAndCallType) { - const std::map<int, string> a_map; + const std::map<int, std::string> a_map; EXPECT_CALL(mock_foo_, CTReturnTypeWithComma()) .WillOnce(Return(a_map)); @@ -616,7 +617,41 @@ TEST(MockFunctionTest, AsStdFunctionReturnsReference) { value = 2; EXPECT_EQ(2, ref); } + +TEST(MockFunctionTest, AsStdFunctionWithReferenceParameter) { + MockFunction<int(int &)> foo; + auto call = [](const std::function<int(int& )> &f, int &i) { + return f(i); + }; + int i = 42; + EXPECT_CALL(foo, Call(i)).WillOnce(Return(-1)); + EXPECT_EQ(-1, call(foo.AsStdFunction(), i)); +} + #endif // GTEST_HAS_STD_FUNCTION_ +struct MockMethodSizes0 { + MOCK_METHOD0(func, void()); +}; +struct MockMethodSizes1 { + MOCK_METHOD1(func, void(int)); +}; +struct MockMethodSizes2 { + MOCK_METHOD2(func, void(int, int)); +}; +struct MockMethodSizes3 { + MOCK_METHOD3(func, void(int, int, int)); +}; +struct MockMethodSizes4 { + MOCK_METHOD4(func, void(int, int, int, int)); +}; + +TEST(MockFunctionTest, MockMethodSizeOverhead) { + EXPECT_EQ(sizeof(MockMethodSizes0), sizeof(MockMethodSizes1)); + EXPECT_EQ(sizeof(MockMethodSizes0), sizeof(MockMethodSizes2)); + EXPECT_EQ(sizeof(MockMethodSizes0), sizeof(MockMethodSizes3)); + EXPECT_EQ(sizeof(MockMethodSizes0), sizeof(MockMethodSizes4)); +} + } // namespace gmock_generated_function_mockers_test } // namespace testing diff --git a/googlemock/test/gmock-generated-internal-utils_test.cc b/googlemock/test/gmock-generated-internal-utils_test.cc index e0a535a..965cbaa 100644 --- a/googlemock/test/gmock-generated-internal-utils_test.cc +++ b/googlemock/test/gmock-generated-internal-utils_test.cc @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // Google Mock - a framework for writing C++ mock classes. // @@ -39,7 +38,6 @@ namespace { -using ::testing::tuple; using ::testing::Matcher; using ::testing::internal::CompileAssertTypesEqual; using ::testing::internal::MatcherTuple; @@ -49,24 +47,24 @@ using ::testing::internal::IgnoredValue; // Tests the MatcherTuple template struct. TEST(MatcherTupleTest, ForSize0) { - CompileAssertTypesEqual<tuple<>, MatcherTuple<tuple<> >::type>(); + CompileAssertTypesEqual<std::tuple<>, MatcherTuple<std::tuple<> >::type>(); } TEST(MatcherTupleTest, ForSize1) { - CompileAssertTypesEqual<tuple<Matcher<int> >, - MatcherTuple<tuple<int> >::type>(); + CompileAssertTypesEqual<std::tuple<Matcher<int> >, + MatcherTuple<std::tuple<int> >::type>(); } TEST(MatcherTupleTest, ForSize2) { - CompileAssertTypesEqual<tuple<Matcher<int>, Matcher<char> >, - MatcherTuple<tuple<int, char> >::type>(); + CompileAssertTypesEqual<std::tuple<Matcher<int>, Matcher<char> >, + MatcherTuple<std::tuple<int, char> >::type>(); } TEST(MatcherTupleTest, ForSize5) { - CompileAssertTypesEqual<tuple<Matcher<int>, Matcher<char>, Matcher<bool>, - Matcher<double>, Matcher<char*> >, - MatcherTuple<tuple<int, char, bool, double, char*> - >::type>(); + CompileAssertTypesEqual< + std::tuple<Matcher<int>, Matcher<char>, Matcher<bool>, Matcher<double>, + Matcher<char*> >, + MatcherTuple<std::tuple<int, char, bool, double, char*> >::type>(); } // Tests the Function template struct. @@ -74,8 +72,8 @@ TEST(MatcherTupleTest, ForSize5) { TEST(FunctionTest, Nullary) { typedef Function<int()> F; // NOLINT CompileAssertTypesEqual<int, F::Result>(); - CompileAssertTypesEqual<tuple<>, F::ArgumentTuple>(); - CompileAssertTypesEqual<tuple<>, F::ArgumentMatcherTuple>(); + CompileAssertTypesEqual<std::tuple<>, F::ArgumentTuple>(); + CompileAssertTypesEqual<std::tuple<>, F::ArgumentMatcherTuple>(); CompileAssertTypesEqual<void(), F::MakeResultVoid>(); CompileAssertTypesEqual<IgnoredValue(), F::MakeResultIgnoredValue>(); } @@ -84,8 +82,9 @@ TEST(FunctionTest, Unary) { typedef Function<int(bool)> F; // NOLINT CompileAssertTypesEqual<int, F::Result>(); CompileAssertTypesEqual<bool, F::Argument1>(); - CompileAssertTypesEqual<tuple<bool>, F::ArgumentTuple>(); - CompileAssertTypesEqual<tuple<Matcher<bool> >, F::ArgumentMatcherTuple>(); + CompileAssertTypesEqual<std::tuple<bool>, F::ArgumentTuple>(); + CompileAssertTypesEqual<std::tuple<Matcher<bool> >, + F::ArgumentMatcherTuple>(); CompileAssertTypesEqual<void(bool), F::MakeResultVoid>(); // NOLINT CompileAssertTypesEqual<IgnoredValue(bool), // NOLINT F::MakeResultIgnoredValue>(); @@ -96,9 +95,11 @@ TEST(FunctionTest, Binary) { CompileAssertTypesEqual<int, F::Result>(); CompileAssertTypesEqual<bool, F::Argument1>(); CompileAssertTypesEqual<const long&, F::Argument2>(); // NOLINT - CompileAssertTypesEqual<tuple<bool, const long&>, F::ArgumentTuple>(); // NOLINT - CompileAssertTypesEqual<tuple<Matcher<bool>, Matcher<const long&> >, // NOLINT - F::ArgumentMatcherTuple>(); + CompileAssertTypesEqual<std::tuple<bool, const long&>, // NOLINT + F::ArgumentTuple>(); + CompileAssertTypesEqual< + std::tuple<Matcher<bool>, Matcher<const long&> >, // NOLINT + F::ArgumentMatcherTuple>(); CompileAssertTypesEqual<void(bool, const long&), F::MakeResultVoid>(); // NOLINT CompileAssertTypesEqual<IgnoredValue(bool, const long&), // NOLINT F::MakeResultIgnoredValue>(); @@ -112,11 +113,13 @@ TEST(FunctionTest, LongArgumentList) { CompileAssertTypesEqual<char*, F::Argument3>(); CompileAssertTypesEqual<int&, F::Argument4>(); CompileAssertTypesEqual<const long&, F::Argument5>(); // NOLINT - CompileAssertTypesEqual<tuple<bool, int, char*, int&, const long&>, // NOLINT - F::ArgumentTuple>(); - CompileAssertTypesEqual<tuple<Matcher<bool>, Matcher<int>, Matcher<char*>, - Matcher<int&>, Matcher<const long&> >, // NOLINT - F::ArgumentMatcherTuple>(); + CompileAssertTypesEqual< + std::tuple<bool, int, char*, int&, const long&>, // NOLINT + F::ArgumentTuple>(); + CompileAssertTypesEqual< + std::tuple<Matcher<bool>, Matcher<int>, Matcher<char*>, Matcher<int&>, + Matcher<const long&> >, // NOLINT + F::ArgumentMatcherTuple>(); CompileAssertTypesEqual<void(bool, int, char*, int&, const long&), // NOLINT F::MakeResultVoid>(); CompileAssertTypesEqual< diff --git a/googlemock/test/gmock-generated-matchers_test.cc b/googlemock/test/gmock-generated-matchers_test.cc index 0e9f77f..fdbfb54 100644 --- a/googlemock/test/gmock-generated-matchers_test.cc +++ b/googlemock/test/gmock-generated-matchers_test.cc @@ -31,10 +31,19 @@ // // This file tests the built-in matchers generated by a script. +// Silence warning C4244: 'initializing': conversion from 'int' to 'short', +// possible loss of data and C4100, unreferenced local parameter +#ifdef _MSC_VER +# pragma warning(push) +# pragma warning(disable:4244) +# pragma warning(disable:4100) +#endif + #include "gmock/gmock-generated-matchers.h" #include <list> #include <map> +#include <memory> #include <set> #include <sstream> #include <string> @@ -53,10 +62,9 @@ using std::pair; using std::set; using std::stringstream; using std::vector; -using testing::get; -using testing::make_tuple; -using testing::tuple; using testing::_; +using testing::AllOf; +using testing::AnyOf; using testing::Args; using testing::Contains; using testing::ElementsAre; @@ -79,11 +87,10 @@ using testing::StaticAssertTypeEq; using testing::StrEq; using testing::Value; using testing::internal::ElementsAreArrayMatcher; -using testing::internal::string; // Returns the description of the given matcher. template <typename T> -string Describe(const Matcher<T>& m) { +std::string Describe(const Matcher<T>& m) { stringstream ss; m.DescribeTo(&ss); return ss.str(); @@ -91,7 +98,7 @@ string Describe(const Matcher<T>& m) { // Returns the description of the negation of the given matcher. template <typename T> -string DescribeNegation(const Matcher<T>& m) { +std::string DescribeNegation(const Matcher<T>& m) { stringstream ss; m.DescribeNegationTo(&ss); return ss.str(); @@ -99,7 +106,7 @@ string DescribeNegation(const Matcher<T>& m) { // Returns the reason why x matches, or doesn't match, m. template <typename MatcherType, typename Value> -string Explain(const MatcherType& m, const Value& x) { +std::string Explain(const MatcherType& m, const Value& x) { stringstream ss; m.ExplainMatchResultTo(x, &ss); return ss.str(); @@ -108,20 +115,20 @@ string Explain(const MatcherType& m, const Value& x) { // Tests Args<k0, ..., kn>(m). TEST(ArgsTest, AcceptsZeroTemplateArg) { - const tuple<int, bool> t(5, true); - EXPECT_THAT(t, Args<>(Eq(tuple<>()))); - EXPECT_THAT(t, Not(Args<>(Ne(tuple<>())))); + const std::tuple<int, bool> t(5, true); + EXPECT_THAT(t, Args<>(Eq(std::tuple<>()))); + EXPECT_THAT(t, Not(Args<>(Ne(std::tuple<>())))); } TEST(ArgsTest, AcceptsOneTemplateArg) { - const tuple<int, bool> t(5, true); - EXPECT_THAT(t, Args<0>(Eq(make_tuple(5)))); - EXPECT_THAT(t, Args<1>(Eq(make_tuple(true)))); - EXPECT_THAT(t, Not(Args<1>(Eq(make_tuple(false))))); + const std::tuple<int, bool> t(5, true); + EXPECT_THAT(t, Args<0>(Eq(std::make_tuple(5)))); + EXPECT_THAT(t, Args<1>(Eq(std::make_tuple(true)))); + EXPECT_THAT(t, Not(Args<1>(Eq(std::make_tuple(false))))); } TEST(ArgsTest, AcceptsTwoTemplateArgs) { - const tuple<short, int, long> t(4, 5, 6L); // NOLINT + const std::tuple<short, int, long> t(4, 5, 6L); // NOLINT EXPECT_THAT(t, (Args<0, 1>(Lt()))); EXPECT_THAT(t, (Args<1, 2>(Lt()))); @@ -129,13 +136,13 @@ TEST(ArgsTest, AcceptsTwoTemplateArgs) { } TEST(ArgsTest, AcceptsRepeatedTemplateArgs) { - const tuple<short, int, long> t(4, 5, 6L); // NOLINT + const std::tuple<short, int, long> t(4, 5, 6L); // NOLINT EXPECT_THAT(t, (Args<0, 0>(Eq()))); EXPECT_THAT(t, Not(Args<1, 1>(Ne()))); } TEST(ArgsTest, AcceptsDecreasingTemplateArgs) { - const tuple<short, int, long> t(4, 5, 6L); // NOLINT + const std::tuple<short, int, long> t(4, 5, 6L); // NOLINT EXPECT_THAT(t, (Args<2, 0>(Gt()))); EXPECT_THAT(t, Not(Args<2, 1>(Lt()))); } @@ -151,29 +158,29 @@ TEST(ArgsTest, AcceptsDecreasingTemplateArgs) { #endif MATCHER(SumIsZero, "") { - return get<0>(arg) + get<1>(arg) + get<2>(arg) == 0; + return std::get<0>(arg) + std::get<1>(arg) + std::get<2>(arg) == 0; } TEST(ArgsTest, AcceptsMoreTemplateArgsThanArityOfOriginalTuple) { - EXPECT_THAT(make_tuple(-1, 2), (Args<0, 0, 1>(SumIsZero()))); - EXPECT_THAT(make_tuple(1, 2), Not(Args<0, 0, 1>(SumIsZero()))); + EXPECT_THAT(std::make_tuple(-1, 2), (Args<0, 0, 1>(SumIsZero()))); + EXPECT_THAT(std::make_tuple(1, 2), Not(Args<0, 0, 1>(SumIsZero()))); } TEST(ArgsTest, CanBeNested) { - const tuple<short, int, long, int> t(4, 5, 6L, 6); // NOLINT + const std::tuple<short, int, long, int> t(4, 5, 6L, 6); // NOLINT EXPECT_THAT(t, (Args<1, 2, 3>(Args<1, 2>(Eq())))); EXPECT_THAT(t, (Args<0, 1, 3>(Args<0, 2>(Lt())))); } TEST(ArgsTest, CanMatchTupleByValue) { - typedef tuple<char, int, int> Tuple3; + typedef std::tuple<char, int, int> Tuple3; const Matcher<Tuple3> m = Args<1, 2>(Lt()); EXPECT_TRUE(m.Matches(Tuple3('a', 1, 2))); EXPECT_FALSE(m.Matches(Tuple3('b', 2, 2))); } TEST(ArgsTest, CanMatchTupleByReference) { - typedef tuple<char, char, int> Tuple3; + typedef std::tuple<char, char, int> Tuple3; const Matcher<const Tuple3&> m = Args<0, 1>(Lt()); EXPECT_TRUE(m.Matches(Tuple3('a', 'b', 2))); EXPECT_FALSE(m.Matches(Tuple3('b', 'b', 2))); @@ -185,23 +192,23 @@ MATCHER_P(PrintsAs, str, "") { } TEST(ArgsTest, AcceptsTenTemplateArgs) { - EXPECT_THAT(make_tuple(0, 1L, 2, 3L, 4, 5, 6, 7, 8, 9), + EXPECT_THAT(std::make_tuple(0, 1L, 2, 3L, 4, 5, 6, 7, 8, 9), (Args<9, 8, 7, 6, 5, 4, 3, 2, 1, 0>( PrintsAs("(9, 8, 7, 6, 5, 4, 3, 2, 1, 0)")))); - EXPECT_THAT(make_tuple(0, 1L, 2, 3L, 4, 5, 6, 7, 8, 9), + EXPECT_THAT(std::make_tuple(0, 1L, 2, 3L, 4, 5, 6, 7, 8, 9), Not(Args<9, 8, 7, 6, 5, 4, 3, 2, 1, 0>( - PrintsAs("(0, 8, 7, 6, 5, 4, 3, 2, 1, 0)")))); + PrintsAs("(0, 8, 7, 6, 5, 4, 3, 2, 1, 0)")))); } TEST(ArgsTest, DescirbesSelfCorrectly) { - const Matcher<tuple<int, bool, char> > m = Args<2, 0>(Lt()); + const Matcher<std::tuple<int, bool, char> > m = Args<2, 0>(Lt()); EXPECT_EQ("are a tuple whose fields (#2, #0) are a pair where " "the first < the second", Describe(m)); } TEST(ArgsTest, DescirbesNestedArgsCorrectly) { - const Matcher<const tuple<int, bool, char, int>&> m = + const Matcher<const std::tuple<int, bool, char, int>&> m = Args<0, 2, 3>(Args<2, 0>(Lt())); EXPECT_EQ("are a tuple whose fields (#0, #2, #3) are a tuple " "whose fields (#2, #0) are a pair where the first < the second", @@ -209,28 +216,28 @@ TEST(ArgsTest, DescirbesNestedArgsCorrectly) { } TEST(ArgsTest, DescribesNegationCorrectly) { - const Matcher<tuple<int, char> > m = Args<1, 0>(Gt()); + const Matcher<std::tuple<int, char> > m = Args<1, 0>(Gt()); EXPECT_EQ("are a tuple whose fields (#1, #0) aren't a pair " "where the first > the second", DescribeNegation(m)); } TEST(ArgsTest, ExplainsMatchResultWithoutInnerExplanation) { - const Matcher<tuple<bool, int, int> > m = Args<1, 2>(Eq()); + const Matcher<std::tuple<bool, int, int> > m = Args<1, 2>(Eq()); EXPECT_EQ("whose fields (#1, #2) are (42, 42)", - Explain(m, make_tuple(false, 42, 42))); + Explain(m, std::make_tuple(false, 42, 42))); EXPECT_EQ("whose fields (#1, #2) are (42, 43)", - Explain(m, make_tuple(false, 42, 43))); + Explain(m, std::make_tuple(false, 42, 43))); } // For testing Args<>'s explanation. -class LessThanMatcher : public MatcherInterface<tuple<char, int> > { +class LessThanMatcher : public MatcherInterface<std::tuple<char, int> > { public: virtual void DescribeTo(::std::ostream* os) const {} - virtual bool MatchAndExplain(tuple<char, int> value, + virtual bool MatchAndExplain(std::tuple<char, int> value, MatchResultListener* listener) const { - const int diff = get<0>(value) - get<1>(value); + const int diff = std::get<0>(value) - std::get<1>(value); if (diff > 0) { *listener << "where the first value is " << diff << " more than the second"; @@ -239,17 +246,18 @@ class LessThanMatcher : public MatcherInterface<tuple<char, int> > { } }; -Matcher<tuple<char, int> > LessThan() { +Matcher<std::tuple<char, int> > LessThan() { return MakeMatcher(new LessThanMatcher); } TEST(ArgsTest, ExplainsMatchResultWithInnerExplanation) { - const Matcher<tuple<char, int, int> > m = Args<0, 2>(LessThan()); - EXPECT_EQ("whose fields (#0, #2) are ('a' (97, 0x61), 42), " - "where the first value is 55 more than the second", - Explain(m, make_tuple('a', 42, 42))); + const Matcher<std::tuple<char, int, int> > m = Args<0, 2>(LessThan()); + EXPECT_EQ( + "whose fields (#0, #2) are ('a' (97, 0x61), 42), " + "where the first value is 55 more than the second", + Explain(m, std::make_tuple('a', 42, 42))); EXPECT_EQ("whose fields (#0, #2) are ('\\0', 43)", - Explain(m, make_tuple('\0', 42, 43))); + Explain(m, std::make_tuple('\0', 42, 43))); } // For testing ExplainMatchResultTo(). @@ -296,7 +304,7 @@ TEST(ElementsAreTest, CanDescribeExpectingOneElement) { } TEST(ElementsAreTest, CanDescribeExpectingManyElements) { - Matcher<list<string> > m = ElementsAre(StrEq("one"), "two"); + Matcher<list<std::string> > m = ElementsAre(StrEq("one"), "two"); EXPECT_EQ("has 2 elements where\n" "element #0 is equal to \"one\",\n" "element #1 is equal to \"two\"", Describe(m)); @@ -314,7 +322,7 @@ TEST(ElementsAreTest, CanDescribeNegationOfExpectingOneElment) { } TEST(ElementsAreTest, CanDescribeNegationOfExpectingManyElements) { - Matcher<const list<string>& > m = ElementsAre("one", "two"); + Matcher<const list<std::string>&> m = ElementsAre("one", "two"); EXPECT_EQ("doesn't have 2 elements, or\n" "element #0 isn't equal to \"one\", or\n" "element #1 isn't equal to \"two\"", DescribeNegation(m)); @@ -365,21 +373,21 @@ TEST(ElementsAreTest, CanExplainMismatchRightSize) { } TEST(ElementsAreTest, MatchesOneElementVector) { - vector<string> test_vector; + vector<std::string> test_vector; test_vector.push_back("test string"); EXPECT_THAT(test_vector, ElementsAre(StrEq("test string"))); } TEST(ElementsAreTest, MatchesOneElementList) { - list<string> test_list; + list<std::string> test_list; test_list.push_back("test string"); EXPECT_THAT(test_list, ElementsAre("test string")); } TEST(ElementsAreTest, MatchesThreeElementVector) { - vector<string> test_vector; + vector<std::string> test_vector; test_vector.push_back("one"); test_vector.push_back("two"); test_vector.push_back("three"); @@ -428,30 +436,30 @@ TEST(ElementsAreTest, MatchesTenElementVector) { } TEST(ElementsAreTest, DoesNotMatchWrongSize) { - vector<string> test_vector; + vector<std::string> test_vector; test_vector.push_back("test string"); test_vector.push_back("test string"); - Matcher<vector<string> > m = ElementsAre(StrEq("test string")); + Matcher<vector<std::string> > m = ElementsAre(StrEq("test string")); EXPECT_FALSE(m.Matches(test_vector)); } TEST(ElementsAreTest, DoesNotMatchWrongValue) { - vector<string> test_vector; + vector<std::string> test_vector; test_vector.push_back("other string"); - Matcher<vector<string> > m = ElementsAre(StrEq("test string")); + Matcher<vector<std::string> > m = ElementsAre(StrEq("test string")); EXPECT_FALSE(m.Matches(test_vector)); } TEST(ElementsAreTest, DoesNotMatchWrongOrder) { - vector<string> test_vector; + vector<std::string> test_vector; test_vector.push_back("one"); test_vector.push_back("three"); test_vector.push_back("two"); - Matcher<vector<string> > m = ElementsAre( - StrEq("one"), StrEq("two"), StrEq("three")); + Matcher<vector<std::string> > m = + ElementsAre(StrEq("one"), StrEq("two"), StrEq("three")); EXPECT_FALSE(m.Matches(test_vector)); } @@ -507,7 +515,7 @@ class NativeArrayPassedAsPointerAndSize { TEST(ElementsAreTest, WorksWithNativeArrayPassedAsPointerAndSize) { int array[] = { 0, 1 }; - ::testing::tuple<int*, size_t> array_as_tuple(array, 2); + ::std::tuple<int*, size_t> array_as_tuple(array, 2); EXPECT_THAT(array_as_tuple, ElementsAre(0, 1)); EXPECT_THAT(array_as_tuple, Not(ElementsAre(0))); @@ -527,7 +535,7 @@ TEST(ElementsAreTest, WorksWithTwoDimensionalNativeArray) { } TEST(ElementsAreTest, AcceptsStringLiteral) { - string array[] = { "hi", "one", "two" }; + std::string array[] = {"hi", "one", "two"}; EXPECT_THAT(array, ElementsAre("hi", "one", "two")); EXPECT_THAT(array, Not(ElementsAre("hi", "one", "too"))); } @@ -546,10 +554,10 @@ TEST(ElementsAreTest, AcceptsArrayWithUnknownSize) { // The size of kHi is not known in this test, but ElementsAre() should // still accept it. - string array1[] = { "hi" }; + std::string array1[] = {"hi"}; EXPECT_THAT(array1, ElementsAre(kHi)); - string array2[] = { "ho" }; + std::string array2[] = {"ho"}; EXPECT_THAT(array2, Not(ElementsAre(kHi))); } @@ -561,8 +569,8 @@ TEST(ElementsAreTest, MakesCopyOfArguments) { int x = 1; int y = 2; // This should make a copy of x and y. - ::testing::internal::ElementsAreMatcher<testing::tuple<int, int> > - polymorphic_matcher = ElementsAre(x, y); + ::testing::internal::ElementsAreMatcher<std::tuple<int, int> > + polymorphic_matcher = ElementsAre(x, y); // Changing x and y now shouldn't affect the meaning of the above matcher. x = y = 0; const int array1[] = { 1, 2 }; @@ -589,7 +597,7 @@ TEST(ElementsAreArrayTest, CanBeCreatedWithValueArray) { TEST(ElementsAreArrayTest, CanBeCreatedWithArraySize) { const char* a[] = { "one", "two", "three" }; - vector<string> test_vector(a, a + GTEST_ARRAY_SIZE_(a)); + vector<std::string> test_vector(a, a + GTEST_ARRAY_SIZE_(a)); EXPECT_THAT(test_vector, ElementsAreArray(a, GTEST_ARRAY_SIZE_(a))); const char** p = a; @@ -600,7 +608,7 @@ TEST(ElementsAreArrayTest, CanBeCreatedWithArraySize) { TEST(ElementsAreArrayTest, CanBeCreatedWithoutArraySize) { const char* a[] = { "one", "two", "three" }; - vector<string> test_vector(a, a + GTEST_ARRAY_SIZE_(a)); + vector<std::string> test_vector(a, a + GTEST_ARRAY_SIZE_(a)); EXPECT_THAT(test_vector, ElementsAreArray(a)); test_vector[0] = "1"; @@ -608,10 +616,10 @@ TEST(ElementsAreArrayTest, CanBeCreatedWithoutArraySize) { } TEST(ElementsAreArrayTest, CanBeCreatedWithMatcherArray) { - const Matcher<string> kMatcherArray[] = - { StrEq("one"), StrEq("two"), StrEq("three") }; + const Matcher<std::string> kMatcherArray[] = {StrEq("one"), StrEq("two"), + StrEq("three")}; - vector<string> test_vector; + vector<std::string> test_vector; test_vector.push_back("one"); test_vector.push_back("two"); test_vector.push_back("three"); @@ -640,7 +648,7 @@ TEST(ElementsAreArrayTest, TakesInitializerList) { } TEST(ElementsAreArrayTest, TakesInitializerListOfCStrings) { - const string a[5] = { "a", "b", "c", "d", "e" }; + const std::string a[5] = {"a", "b", "c", "d", "e"}; EXPECT_THAT(a, ElementsAreArray({ "a", "b", "c", "d", "e" })); EXPECT_THAT(a, Not(ElementsAreArray({ "a", "b", "c", "e", "d" }))); EXPECT_THAT(a, Not(ElementsAreArray({ "a", "b", "c", "d", "ef" }))); @@ -687,7 +695,7 @@ TEST(ElementsAreArrayTest, CanBeCreatedWithIteratorRange) { // Pointers are iterators, too. EXPECT_THAT(test_vector, ElementsAreArray(a, a + GTEST_ARRAY_SIZE_(a))); // The empty range of NULL pointers should also be okay. - int* const null_int = NULL; + int* const null_int = nullptr; EXPECT_THAT(test_vector, Not(ElementsAreArray(null_int, null_int))); EXPECT_THAT((vector<int>()), ElementsAreArray(null_int, null_int)); } @@ -751,16 +759,16 @@ MATCHER(IsEven2, negation ? "is odd" : "is even") { // This also tests that the description string can reference matcher // parameters. -MATCHER_P2(EqSumOf, x, y, - string(negation ? "doesn't equal" : "equals") + " the sum of " + - PrintToString(x) + " and " + PrintToString(y)) { +MATCHER_P2(EqSumOf, x, y, std::string(negation ? "doesn't equal" : "equals") + + " the sum of " + PrintToString(x) + " and " + + PrintToString(y)) { if (arg == (x + y)) { *result_listener << "OK"; return true; } else { // Verifies that we can stream to the underlying stream of // result_listener. - if (result_listener->stream() != NULL) { + if (result_listener->stream() != nullptr) { *result_listener->stream() << "diff == " << (x + y - arg); } return false; @@ -1117,12 +1125,12 @@ TEST(ContainsTest, ListMatchesWhenElementIsInContainer) { EXPECT_THAT(some_list, Contains(Gt(2.5))); EXPECT_THAT(some_list, Contains(Eq(2.0f))); - list<string> another_list; + list<std::string> another_list; another_list.push_back("fee"); another_list.push_back("fie"); another_list.push_back("foe"); another_list.push_back("fum"); - EXPECT_THAT(another_list, Contains(string("fee"))); + EXPECT_THAT(another_list, Contains(std::string("fee"))); } TEST(ContainsTest, ListDoesNotMatchWhenElementIsNotInContainer) { @@ -1146,7 +1154,7 @@ TEST(ContainsTest, SetMatchesWhenElementIsInContainer) { another_set.insert("fie"); another_set.insert("foe"); another_set.insert("fum"); - EXPECT_THAT(another_set, Contains(Eq(string("fum")))); + EXPECT_THAT(another_set, Contains(Eq(std::string("fum")))); } TEST(ContainsTest, SetDoesNotMatchWhenElementIsNotInContainer) { @@ -1157,7 +1165,7 @@ TEST(ContainsTest, SetDoesNotMatchWhenElementIsNotInContainer) { set<const char*> c_string_set; c_string_set.insert("hello"); - EXPECT_THAT(c_string_set, Not(Contains(string("hello").c_str()))); + EXPECT_THAT(c_string_set, Not(Contains(std::string("hello").c_str()))); } TEST(ContainsTest, ExplainsMatchResultCorrectly) { @@ -1189,13 +1197,14 @@ TEST(ContainsTest, MapMatchesWhenElementIsInContainer) { my_map[bar] = 2; EXPECT_THAT(my_map, Contains(pair<const char* const, int>(bar, 2))); - map<string, int> another_map; + map<std::string, int> another_map; another_map["fee"] = 1; another_map["fie"] = 2; another_map["foe"] = 3; another_map["fum"] = 4; - EXPECT_THAT(another_map, Contains(pair<const string, int>(string("fee"), 1))); - EXPECT_THAT(another_map, Contains(pair<const string, int>("fie", 2))); + EXPECT_THAT(another_map, + Contains(pair<const std::string, int>(std::string("fee"), 1))); + EXPECT_THAT(another_map, Contains(pair<const std::string, int>("fie", 2))); } TEST(ContainsTest, MapDoesNotMatchWhenElementIsNotInContainer) { @@ -1207,7 +1216,7 @@ TEST(ContainsTest, MapDoesNotMatchWhenElementIsNotInContainer) { TEST(ContainsTest, ArrayMatchesWhenElementIsInContainer) { const char* string_array[] = { "fee", "fie", "foe", "fum" }; - EXPECT_THAT(string_array, Contains(Eq(string("fum")))); + EXPECT_THAT(string_array, Contains(Eq(std::string("fum")))); } TEST(ContainsTest, ArrayDoesNotMatchWhenElementIsNotInContainer) { @@ -1224,8 +1233,8 @@ TEST(ContainsTest, AcceptsMatcher) { TEST(ContainsTest, WorksForNativeArrayAsTuple) { const int a[] = { 1, 2 }; const int* const pointer = a; - EXPECT_THAT(make_tuple(pointer, 2), Contains(1)); - EXPECT_THAT(make_tuple(pointer, 2), Not(Contains(Gt(3)))); + EXPECT_THAT(std::make_tuple(pointer, 2), Contains(1)); + EXPECT_THAT(std::make_tuple(pointer, 2), Not(Contains(Gt(3)))); } TEST(ContainsTest, WorksForTwoDimensionalNativeArray) { @@ -1283,4 +1292,48 @@ TEST(AnyOfTest, DoesNotCallAnyOfUnqualified) { # pragma warning(pop) #endif +#if GTEST_LANG_CXX11 + +TEST(AllOfTest, WorksOnMoveOnlyType) { + std::unique_ptr<int> p(new int(3)); + EXPECT_THAT(p, AllOf(Pointee(Eq(3)), Pointee(Gt(0)), Pointee(Lt(5)))); + EXPECT_THAT(p, Not(AllOf(Pointee(Eq(3)), Pointee(Gt(0)), Pointee(Lt(3))))); +} + +TEST(AnyOfTest, WorksOnMoveOnlyType) { + std::unique_ptr<int> p(new int(3)); + EXPECT_THAT(p, AnyOf(Pointee(Eq(5)), Pointee(Lt(0)), Pointee(Lt(5)))); + EXPECT_THAT(p, Not(AnyOf(Pointee(Eq(5)), Pointee(Lt(0)), Pointee(Gt(5))))); +} + +MATCHER(IsNotNull, "") { + return arg != nullptr; +} + +// Verifies that a matcher defined using MATCHER() can work on +// move-only types. +TEST(MatcherMacroTest, WorksOnMoveOnlyType) { + std::unique_ptr<int> p(new int(3)); + EXPECT_THAT(p, IsNotNull()); + EXPECT_THAT(std::unique_ptr<int>(), Not(IsNotNull())); +} + +MATCHER_P(UniquePointee, pointee, "") { + return *arg == pointee; +} + +// Verifies that a matcher defined using MATCHER_P*() can work on +// move-only types. +TEST(MatcherPMacroTest, WorksOnMoveOnlyType) { + std::unique_ptr<int> p(new int(3)); + EXPECT_THAT(p, UniquePointee(3)); + EXPECT_THAT(p, Not(UniquePointee(2))); +} + +#endif // GTEST_LASNG_CXX11 + } // namespace + +#ifdef _MSC_VER +# pragma warning(pop) +#endif diff --git a/googlemock/test/gmock-internal-utils_test.cc b/googlemock/test/gmock-internal-utils_test.cc index 9d5ec60..41498f0 100644 --- a/googlemock/test/gmock-internal-utils_test.cc +++ b/googlemock/test/gmock-internal-utils_test.cc @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // Google Mock - a framework for writing C++ mock classes. // @@ -49,7 +48,7 @@ // implementation. It must come before gtest-internal-inl.h is // included, or there will be a compiler error. This trick is to // prevent a user from accidentally including gtest-internal-inl.h in -// his code. +// their code. #define GTEST_IMPLEMENTATION_ 1 #include "src/gtest-internal-inl.h" #undef GTEST_IMPLEMENTATION_ @@ -69,6 +68,26 @@ namespace internal { namespace { +TEST(JoinAsTupleTest, JoinsEmptyTuple) { + EXPECT_EQ("", JoinAsTuple(Strings())); +} + +TEST(JoinAsTupleTest, JoinsOneTuple) { + const char* fields[] = {"1"}; + EXPECT_EQ("1", JoinAsTuple(Strings(fields, fields + 1))); +} + +TEST(JoinAsTupleTest, JoinsTwoTuple) { + const char* fields[] = {"1", "a"}; + EXPECT_EQ("(1, a)", JoinAsTuple(Strings(fields, fields + 2))); +} + +TEST(JoinAsTupleTest, JoinsTenTuple) { + const char* fields[] = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10"}; + EXPECT_EQ("(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)", + JoinAsTuple(Strings(fields, fields + 10))); +} + TEST(ConvertIdentifierNameToWordsTest, WorksWhenNameContainsNoWord) { EXPECT_EQ("", ConvertIdentifierNameToWords("")); EXPECT_EQ("", ConvertIdentifierNameToWords("_")); @@ -139,9 +158,9 @@ TEST(GetRawPointerTest, WorksForSmartPointers) { } TEST(GetRawPointerTest, WorksForRawPointers) { - int* p = NULL; + int* p = nullptr; // Don't use EXPECT_EQ as no NULL-testing magic on Symbian. - EXPECT_TRUE(NULL == GetRawPointer(p)); + EXPECT_TRUE(nullptr == GetRawPointer(p)); int n = 1; EXPECT_EQ(&n, GetRawPointer(&n)); } @@ -289,26 +308,23 @@ TEST(LosslessArithmeticConvertibleTest, FloatingPointToFloatingPoint) { // Tests the TupleMatches() template function. TEST(TupleMatchesTest, WorksForSize0) { - tuple<> matchers; - tuple<> values; + std::tuple<> matchers; + std::tuple<> values; EXPECT_TRUE(TupleMatches(matchers, values)); } TEST(TupleMatchesTest, WorksForSize1) { - tuple<Matcher<int> > matchers(Eq(1)); - tuple<int> values1(1), - values2(2); + std::tuple<Matcher<int> > matchers(Eq(1)); + std::tuple<int> values1(1), values2(2); EXPECT_TRUE(TupleMatches(matchers, values1)); EXPECT_FALSE(TupleMatches(matchers, values2)); } TEST(TupleMatchesTest, WorksForSize2) { - tuple<Matcher<int>, Matcher<char> > matchers(Eq(1), Eq('a')); - tuple<int, char> values1(1, 'a'), - values2(1, 'b'), - values3(2, 'a'), + std::tuple<Matcher<int>, Matcher<char> > matchers(Eq(1), Eq('a')); + std::tuple<int, char> values1(1, 'a'), values2(1, 'b'), values3(2, 'a'), values4(2, 'b'); EXPECT_TRUE(TupleMatches(matchers, values1)); @@ -318,12 +334,12 @@ TEST(TupleMatchesTest, WorksForSize2) { } TEST(TupleMatchesTest, WorksForSize5) { - tuple<Matcher<int>, Matcher<char>, Matcher<bool>, Matcher<long>, // NOLINT - Matcher<string> > + std::tuple<Matcher<int>, Matcher<char>, Matcher<bool>, + Matcher<long>, // NOLINT + Matcher<std::string> > matchers(Eq(1), Eq('a'), Eq(true), Eq(2L), Eq("hi")); - tuple<int, char, bool, long, string> // NOLINT - values1(1, 'a', true, 2L, "hi"), - values2(1, 'a', true, 2L, "hello"), + std::tuple<int, char, bool, long, std::string> // NOLINT + values1(1, 'a', true, 2L, "hi"), values2(1, 'a', true, 2L, "hello"), values3(2, 'a', true, 2L, "hi"); EXPECT_TRUE(TupleMatches(matchers, values1)); @@ -375,7 +391,7 @@ class LogIsVisibleTest : public ::testing::Test { virtual void TearDown() { GMOCK_FLAG(verbose) = original_verbose_; } - string original_verbose_; + std::string original_verbose_; }; TEST_F(LogIsVisibleTest, AlwaysReturnsTrueIfVerbosityIsInfo) { @@ -402,9 +418,9 @@ TEST_F(LogIsVisibleTest, WorksWhenVerbosityIsWarning) { // Verifies that Log() behaves correctly for the given verbosity level // and log severity. -void TestLogWithSeverity(const string& verbosity, LogSeverity severity, +void TestLogWithSeverity(const std::string& verbosity, LogSeverity severity, bool should_print) { - const string old_flag = GMOCK_FLAG(verbose); + const std::string old_flag = GMOCK_FLAG(verbose); GMOCK_FLAG(verbose) = verbosity; CaptureStdout(); Log(severity, "Test log.\n", 0); @@ -423,7 +439,7 @@ void TestLogWithSeverity(const string& verbosity, LogSeverity severity, // Tests that when the stack_frames_to_skip parameter is negative, // Log() doesn't include the stack trace in the output. TEST(LogTest, NoStackTraceWhenStackFramesToSkipIsNegative) { - const string saved_flag = GMOCK_FLAG(verbose); + const std::string saved_flag = GMOCK_FLAG(verbose); GMOCK_FLAG(verbose) = kInfoVerbosity; CaptureStdout(); Log(kInfo, "Test log.\n", -1); @@ -432,7 +448,7 @@ TEST(LogTest, NoStackTraceWhenStackFramesToSkipIsNegative) { } struct MockStackTraceGetter : testing::internal::OsStackTraceGetterInterface { - virtual string CurrentStackTrace(int max_depth, int skip_count) { + virtual std::string CurrentStackTrace(int max_depth, int skip_count) { return (testing::Message() << max_depth << "::" << skip_count << "\n") .GetString(); } @@ -447,11 +463,11 @@ TEST(LogTest, NoSkippingStackFrameInOptMode) { CaptureStdout(); Log(kWarning, "Test log.\n", 100); - const string log = GetCapturedStdout(); + const std::string log = GetCapturedStdout(); - string expected_trace = + std::string expected_trace = (testing::Message() << GTEST_FLAG(stack_trace_depth) << "::").GetString(); - string expected_message = + std::string expected_message = "\nGMOCK WARNING:\n" "Test log.\n" "Stack trace:\n" + @@ -474,7 +490,7 @@ TEST(LogTest, NoSkippingStackFrameInOptMode) { AllOf(Ge(expected_skip_count), Le(expected_skip_count + 10))); // Restores the default OS stack trace getter. - GetUnitTestImpl()->set_os_stack_trace_getter(NULL); + GetUnitTestImpl()->set_os_stack_trace_getter(nullptr); } // Tests that all logs are printed when the value of the @@ -547,7 +563,7 @@ TEST(TypeTraitsTest, remove_reference) { // Verifies that Log() behaves correctly for the given verbosity level // and log severity. std::string GrabOutput(void(*logger)(), const char* verbosity) { - const string saved_flag = GMOCK_FLAG(verbose); + const std::string saved_flag = GMOCK_FLAG(verbose); GMOCK_FLAG(verbose) = verbosity; CaptureStdout(); logger(); @@ -668,22 +684,25 @@ TEST(StlContainerViewTest, WorksForStaticNativeArray) { TEST(StlContainerViewTest, WorksForDynamicNativeArray) { StaticAssertTypeEq<NativeArray<int>, - StlContainerView<tuple<const int*, size_t> >::type>(); - StaticAssertTypeEq<NativeArray<double>, - StlContainerView<tuple<linked_ptr<double>, int> >::type>(); + StlContainerView<std::tuple<const int*, size_t> >::type>(); + StaticAssertTypeEq< + NativeArray<double>, + StlContainerView<std::tuple<linked_ptr<double>, int> >::type>(); - StaticAssertTypeEq<const NativeArray<int>, - StlContainerView<tuple<const int*, int> >::const_reference>(); + StaticAssertTypeEq< + const NativeArray<int>, + StlContainerView<std::tuple<const int*, int> >::const_reference>(); int a1[3] = { 0, 1, 2 }; const int* const p1 = a1; - NativeArray<int> a2 = StlContainerView<tuple<const int*, int> >:: - ConstReference(make_tuple(p1, 3)); + NativeArray<int> a2 = + StlContainerView<std::tuple<const int*, int> >::ConstReference( + std::make_tuple(p1, 3)); EXPECT_EQ(3U, a2.size()); EXPECT_EQ(a1, a2.begin()); - const NativeArray<int> a3 = StlContainerView<tuple<int*, size_t> >:: - Copy(make_tuple(static_cast<int*>(a1), 3)); + const NativeArray<int> a3 = StlContainerView<std::tuple<int*, size_t> >::Copy( + std::make_tuple(static_cast<int*>(a1), 3)); ASSERT_EQ(3U, a3.size()); EXPECT_EQ(0, a3.begin()[0]); EXPECT_EQ(1, a3.begin()[1]); diff --git a/googlemock/test/gmock-matchers_test.cc b/googlemock/test/gmock-matchers_test.cc index 9f62c3d..f4e9e9f 100644 --- a/googlemock/test/gmock-matchers_test.cc +++ b/googlemock/test/gmock-matchers_test.cc @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // Google Mock - a framework for writing C++ mock classes. // @@ -45,6 +44,7 @@ #include <limits> #include <list> #include <map> +#include <memory> #include <set> #include <sstream> #include <string> @@ -58,12 +58,11 @@ # include <forward_list> // NOLINT #endif -namespace testing { - -namespace internal { -GTEST_API_ string JoinAsTuple(const Strings& fields); -} // namespace internal +#if GTEST_LANG_CXX11 +# include <type_traits> +#endif +namespace testing { namespace gmock_matchers_test { using std::greater; @@ -137,7 +136,6 @@ using testing::Value; using testing::WhenSorted; using testing::WhenSortedBy; using testing::_; -using testing::get; using testing::internal::DummyMatchResultListener; using testing::internal::ElementMatcherPair; using testing::internal::ElementMatcherPairs; @@ -145,7 +143,6 @@ using testing::internal::ExplainMatchFailureTupleTo; using testing::internal::FloatingEqMatcher; using testing::internal::FormatMatcherDescription; using testing::internal::IsReadableTypeName; -using testing::internal::JoinAsTuple; using testing::internal::linked_ptr; using testing::internal::MatchMatrix; using testing::internal::RE; @@ -155,8 +152,6 @@ using testing::internal::Strings; using testing::internal::linked_ptr; using testing::internal::scoped_ptr; using testing::internal::string; -using testing::make_tuple; -using testing::tuple; // For testing ExplainMatchResultTo(). class GreaterThanMatcher : public MatcherInterface<int> { @@ -189,7 +184,7 @@ Matcher<int> GreaterThan(int n) { return MakeMatcher(new GreaterThanMatcher(n)); } -string OfType(const string& type_name) { +std::string OfType(const std::string& type_name) { #if GTEST_HAS_RTTI return " (of type " + type_name + ")"; #else @@ -199,28 +194,30 @@ string OfType(const string& type_name) { // Returns the description of the given matcher. template <typename T> -string Describe(const Matcher<T>& m) { - stringstream ss; - m.DescribeTo(&ss); - return ss.str(); +std::string Describe(const Matcher<T>& m) { + return DescribeMatcher<T>(m); } // Returns the description of the negation of the given matcher. template <typename T> -string DescribeNegation(const Matcher<T>& m) { - stringstream ss; - m.DescribeNegationTo(&ss); - return ss.str(); +std::string DescribeNegation(const Matcher<T>& m) { + return DescribeMatcher<T>(m, true); } // Returns the reason why x matches, or doesn't match, m. template <typename MatcherType, typename Value> -string Explain(const MatcherType& m, const Value& x) { +std::string Explain(const MatcherType& m, const Value& x) { StringMatchResultListener listener; ExplainMatchResult(m, x, &listener); return listener.str(); } +TEST(MonotonicMatcherTest, IsPrintable) { + stringstream ss; + ss << GreaterThan(5); + EXPECT_EQ("is > 5", ss.str()); +} + TEST(MatchResultListenerTest, StreamingWorks) { StringMatchResultListener listener; listener << "hi" << 5; @@ -238,8 +235,8 @@ TEST(MatchResultListenerTest, StreamingWorks) { } TEST(MatchResultListenerTest, CanAccessUnderlyingStream) { - EXPECT_TRUE(DummyMatchResultListener().stream() == NULL); - EXPECT_TRUE(StreamMatchResultListener(NULL).stream() == NULL); + EXPECT_TRUE(DummyMatchResultListener().stream() == nullptr); + EXPECT_TRUE(StreamMatchResultListener(nullptr).stream() == nullptr); EXPECT_EQ(&std::cout, StreamMatchResultListener(&std::cout).stream()); } @@ -249,7 +246,7 @@ TEST(MatchResultListenerTest, IsInterestedWorks) { EXPECT_TRUE(StreamMatchResultListener(&std::cout).IsInterested()); EXPECT_FALSE(DummyMatchResultListener().IsInterested()); - EXPECT_FALSE(StreamMatchResultListener(NULL).IsInterested()); + EXPECT_FALSE(StreamMatchResultListener(nullptr).IsInterested()); } // Makes sure that the MatcherInterface<T> interface doesn't @@ -283,7 +280,7 @@ class NewEvenMatcherImpl : public MatcherInterface<int> { const bool match = x % 2 == 0; // Verifies that we can stream to a listener directly. *listener << "value % " << 2; - if (listener->stream() != NULL) { + if (listener->stream() != nullptr) { // Verifies that we can stream to a listener's underlying stream // too. *listener->stream() << " == " << (x % 2); @@ -327,11 +324,27 @@ TEST(MatcherTest, CanBeImplicitlyConstructedFromValue) { // Tests that NULL can be used in place of Eq(NULL). TEST(MatcherTest, CanBeImplicitlyConstructedFromNULL) { Matcher<int*> m1 = NULL; - EXPECT_TRUE(m1.Matches(NULL)); + EXPECT_TRUE(m1.Matches(nullptr)); int n = 0; EXPECT_FALSE(m1.Matches(&n)); } +// Tests that matchers can be constructed from a variable that is not properly +// defined. This should be illegal, but many users rely on this accidentally. +struct Undefined { + virtual ~Undefined() = 0; + static const int kInt = 1; +}; + +TEST(MatcherTest, CanBeConstructedFromUndefinedVariable) { + Matcher<int> m1 = Undefined::kInt; + EXPECT_TRUE(m1.Matches(1)); + EXPECT_FALSE(m1.Matches(2)); +} + +// Test that a matcher parameterized with an abstract class compiles. +TEST(MatcherTest, CanAcceptAbstractClass) { Matcher<const Undefined&> m = _; } + // Tests that matchers are copyable. TEST(MatcherTest, IsCopyable) { // Tests the copy constructor. @@ -365,72 +378,138 @@ TEST(MatcherTest, MatchAndExplain) { } // Tests that a C-string literal can be implicitly converted to a -// Matcher<string> or Matcher<const string&>. +// Matcher<std::string> or Matcher<const std::string&>. TEST(StringMatcherTest, CanBeImplicitlyConstructedFromCStringLiteral) { - Matcher<string> m1 = "hi"; + Matcher<std::string> m1 = "hi"; EXPECT_TRUE(m1.Matches("hi")); EXPECT_FALSE(m1.Matches("hello")); - Matcher<const string&> m2 = "hi"; + Matcher<const std::string&> m2 = "hi"; EXPECT_TRUE(m2.Matches("hi")); EXPECT_FALSE(m2.Matches("hello")); } // Tests that a string object can be implicitly converted to a -// Matcher<string> or Matcher<const string&>. +// Matcher<std::string> or Matcher<const std::string&>. TEST(StringMatcherTest, CanBeImplicitlyConstructedFromString) { - Matcher<string> m1 = string("hi"); + Matcher<std::string> m1 = std::string("hi"); + EXPECT_TRUE(m1.Matches("hi")); + EXPECT_FALSE(m1.Matches("hello")); + + Matcher<const std::string&> m2 = std::string("hi"); + EXPECT_TRUE(m2.Matches("hi")); + EXPECT_FALSE(m2.Matches("hello")); +} + +#if GTEST_HAS_GLOBAL_STRING +// Tests that a ::string object can be implicitly converted to a +// Matcher<std::string> or Matcher<const std::string&>. +TEST(StringMatcherTest, CanBeImplicitlyConstructedFromGlobalString) { + Matcher<std::string> m1 = ::string("hi"); + EXPECT_TRUE(m1.Matches("hi")); + EXPECT_FALSE(m1.Matches("hello")); + + Matcher<const std::string&> m2 = ::string("hi"); + EXPECT_TRUE(m2.Matches("hi")); + EXPECT_FALSE(m2.Matches("hello")); +} +#endif // GTEST_HAS_GLOBAL_STRING + +#if GTEST_HAS_GLOBAL_STRING +// Tests that a C-string literal can be implicitly converted to a +// Matcher<::string> or Matcher<const ::string&>. +TEST(GlobalStringMatcherTest, CanBeImplicitlyConstructedFromCStringLiteral) { + Matcher< ::string> m1 = "hi"; EXPECT_TRUE(m1.Matches("hi")); EXPECT_FALSE(m1.Matches("hello")); - Matcher<const string&> m2 = string("hi"); + Matcher<const ::string&> m2 = "hi"; EXPECT_TRUE(m2.Matches("hi")); EXPECT_FALSE(m2.Matches("hello")); } -#if GTEST_HAS_STRING_PIECE_ +// Tests that a std::string object can be implicitly converted to a +// Matcher<::string> or Matcher<const ::string&>. +TEST(GlobalStringMatcherTest, CanBeImplicitlyConstructedFromString) { + Matcher< ::string> m1 = std::string("hi"); + EXPECT_TRUE(m1.Matches("hi")); + EXPECT_FALSE(m1.Matches("hello")); + + Matcher<const ::string&> m2 = std::string("hi"); + EXPECT_TRUE(m2.Matches("hi")); + EXPECT_FALSE(m2.Matches("hello")); +} + +// Tests that a ::string object can be implicitly converted to a +// Matcher<::string> or Matcher<const ::string&>. +TEST(GlobalStringMatcherTest, CanBeImplicitlyConstructedFromGlobalString) { + Matcher< ::string> m1 = ::string("hi"); + EXPECT_TRUE(m1.Matches("hi")); + EXPECT_FALSE(m1.Matches("hello")); + + Matcher<const ::string&> m2 = ::string("hi"); + EXPECT_TRUE(m2.Matches("hi")); + EXPECT_FALSE(m2.Matches("hello")); +} +#endif // GTEST_HAS_GLOBAL_STRING + +#if GTEST_HAS_ABSL // Tests that a C-string literal can be implicitly converted to a -// Matcher<StringPiece> or Matcher<const StringPiece&>. -TEST(StringPieceMatcherTest, CanBeImplicitlyConstructedFromCStringLiteral) { - Matcher<StringPiece> m1 = "cats"; +// Matcher<absl::string_view> or Matcher<const absl::string_view&>. +TEST(StringViewMatcherTest, CanBeImplicitlyConstructedFromCStringLiteral) { + Matcher<absl::string_view> m1 = "cats"; EXPECT_TRUE(m1.Matches("cats")); EXPECT_FALSE(m1.Matches("dogs")); - Matcher<const StringPiece&> m2 = "cats"; + Matcher<const absl::string_view&> m2 = "cats"; EXPECT_TRUE(m2.Matches("cats")); EXPECT_FALSE(m2.Matches("dogs")); } -// Tests that a string object can be implicitly converted to a -// Matcher<StringPiece> or Matcher<const StringPiece&>. -TEST(StringPieceMatcherTest, CanBeImplicitlyConstructedFromString) { - Matcher<StringPiece> m1 = string("cats"); +// Tests that a std::string object can be implicitly converted to a +// Matcher<absl::string_view> or Matcher<const absl::string_view&>. +TEST(StringViewMatcherTest, CanBeImplicitlyConstructedFromString) { + Matcher<absl::string_view> m1 = std::string("cats"); + EXPECT_TRUE(m1.Matches("cats")); + EXPECT_FALSE(m1.Matches("dogs")); + + Matcher<const absl::string_view&> m2 = std::string("cats"); + EXPECT_TRUE(m2.Matches("cats")); + EXPECT_FALSE(m2.Matches("dogs")); +} + +#if GTEST_HAS_GLOBAL_STRING +// Tests that a ::string object can be implicitly converted to a +// Matcher<absl::string_view> or Matcher<const absl::string_view&>. +TEST(StringViewMatcherTest, CanBeImplicitlyConstructedFromGlobalString) { + Matcher<absl::string_view> m1 = ::string("cats"); EXPECT_TRUE(m1.Matches("cats")); EXPECT_FALSE(m1.Matches("dogs")); - Matcher<const StringPiece&> m2 = string("cats"); + Matcher<const absl::string_view&> m2 = ::string("cats"); EXPECT_TRUE(m2.Matches("cats")); EXPECT_FALSE(m2.Matches("dogs")); } +#endif // GTEST_HAS_GLOBAL_STRING -// Tests that a StringPiece object can be implicitly converted to a -// Matcher<StringPiece> or Matcher<const StringPiece&>. -TEST(StringPieceMatcherTest, CanBeImplicitlyConstructedFromStringPiece) { - Matcher<StringPiece> m1 = StringPiece("cats"); +// Tests that a absl::string_view object can be implicitly converted to a +// Matcher<absl::string_view> or Matcher<const absl::string_view&>. +TEST(StringViewMatcherTest, CanBeImplicitlyConstructedFromStringView) { + Matcher<absl::string_view> m1 = absl::string_view("cats"); EXPECT_TRUE(m1.Matches("cats")); EXPECT_FALSE(m1.Matches("dogs")); - Matcher<const StringPiece&> m2 = StringPiece("cats"); + Matcher<const absl::string_view&> m2 = absl::string_view("cats"); EXPECT_TRUE(m2.Matches("cats")); EXPECT_FALSE(m2.Matches("dogs")); } -#endif // GTEST_HAS_STRING_PIECE_ +#endif // GTEST_HAS_ABSL // Tests that MakeMatcher() constructs a Matcher<T> from a // MatcherInterface* without requiring the user to explicitly // write the type. TEST(MakeMatcherTest, ConstructsMatcherFromMatcherInterface) { - const MatcherInterface<int>* dummy_impl = NULL; + const MatcherInterface<int>* dummy_impl = nullptr; Matcher<int> m = MakeMatcher(dummy_impl); } @@ -489,7 +568,7 @@ class PolymorphicIsEvenImpl { bool MatchAndExplain(const T& x, MatchResultListener* listener) const { // Verifies that we can stream to the listener directly. *listener << "% " << 2; - if (listener->stream() != NULL) { + if (listener->stream() != nullptr) { // Verifies that we can stream to the listener's underlying stream // too. *listener->stream() << " == " << (x % 2); @@ -609,11 +688,76 @@ TEST(MatcherCastTest, FromSameType) { EXPECT_FALSE(m2.Matches(1)); } +// Tests that MatcherCast<T>(m) works when m is a value of the same type as the +// value type of the Matcher. +TEST(MatcherCastTest, FromAValue) { + Matcher<int> m = MatcherCast<int>(42); + EXPECT_TRUE(m.Matches(42)); + EXPECT_FALSE(m.Matches(239)); +} + +// Tests that MatcherCast<T>(m) works when m is a value of the type implicitly +// convertible to the value type of the Matcher. +TEST(MatcherCastTest, FromAnImplicitlyConvertibleValue) { + const int kExpected = 'c'; + Matcher<int> m = MatcherCast<int>('c'); + EXPECT_TRUE(m.Matches(kExpected)); + EXPECT_FALSE(m.Matches(kExpected + 1)); +} + +struct NonImplicitlyConstructibleTypeWithOperatorEq { + friend bool operator==( + const NonImplicitlyConstructibleTypeWithOperatorEq& /* ignored */, + int rhs) { + return 42 == rhs; + } + friend bool operator==( + int lhs, + const NonImplicitlyConstructibleTypeWithOperatorEq& /* ignored */) { + return lhs == 42; + } +}; + +// Tests that MatcherCast<T>(m) works when m is a neither a matcher nor +// implicitly convertible to the value type of the Matcher, but the value type +// of the matcher has operator==() overload accepting m. +TEST(MatcherCastTest, NonImplicitlyConstructibleTypeWithOperatorEq) { + Matcher<NonImplicitlyConstructibleTypeWithOperatorEq> m1 = + MatcherCast<NonImplicitlyConstructibleTypeWithOperatorEq>(42); + EXPECT_TRUE(m1.Matches(NonImplicitlyConstructibleTypeWithOperatorEq())); + + Matcher<NonImplicitlyConstructibleTypeWithOperatorEq> m2 = + MatcherCast<NonImplicitlyConstructibleTypeWithOperatorEq>(239); + EXPECT_FALSE(m2.Matches(NonImplicitlyConstructibleTypeWithOperatorEq())); + + // When updating the following lines please also change the comment to + // namespace convertible_from_any. + Matcher<int> m3 = + MatcherCast<int>(NonImplicitlyConstructibleTypeWithOperatorEq()); + EXPECT_TRUE(m3.Matches(42)); + EXPECT_FALSE(m3.Matches(239)); +} + +// ConvertibleFromAny does not work with MSVC. resulting in +// error C2440: 'initializing': cannot convert from 'Eq' to 'M' +// No constructor could take the source type, or constructor overload +// resolution was ambiguous + +#if !defined _MSC_VER + +// The below ConvertibleFromAny struct is implicitly constructible from anything +// and when in the same namespace can interact with other tests. In particular, +// if it is in the same namespace as other tests and one removes +// NonImplicitlyConstructibleTypeWithOperatorEq::operator==(int lhs, ...); +// then the corresponding test still compiles (and it should not!) by implicitly +// converting NonImplicitlyConstructibleTypeWithOperatorEq to ConvertibleFromAny +// in m3.Matcher(). +namespace convertible_from_any { // Implicitly convertible from any type. struct ConvertibleFromAny { ConvertibleFromAny(int a_value) : value(a_value) {} template <typename T> - explicit ConvertibleFromAny(const T& /*a_value*/) : value(-1) { + ConvertibleFromAny(const T& /*a_value*/) : value(-1) { ADD_FAILURE() << "Conversion constructor called"; } int value; @@ -639,6 +783,9 @@ TEST(MatcherCastTest, FromConvertibleFromAny) { EXPECT_TRUE(m.Matches(ConvertibleFromAny(1))); EXPECT_FALSE(m.Matches(ConvertibleFromAny(2))); } +} // namespace convertible_from_any + +#endif // !defined _MSC_VER struct IntReferenceWrapper { IntReferenceWrapper(const int& a_value) : value(&a_value) {} @@ -744,6 +891,9 @@ TEST(SafeMatcherCastTest, FromSameType) { EXPECT_FALSE(m2.Matches(1)); } +#if !defined _MSC_VER + +namespace convertible_from_any { TEST(SafeMatcherCastTest, ConversionConstructorIsUsed) { Matcher<ConvertibleFromAny> m = SafeMatcherCast<ConvertibleFromAny>(1); EXPECT_TRUE(m.Matches(ConvertibleFromAny(1))); @@ -756,6 +906,9 @@ TEST(SafeMatcherCastTest, FromConvertibleFromAny) { EXPECT_TRUE(m.Matches(ConvertibleFromAny(1))); EXPECT_FALSE(m.Matches(ConvertibleFromAny(2))); } +} // namespace convertible_from_any + +#endif // !defined _MSC_VER TEST(SafeMatcherCastTest, ValueIsNotCopied) { int n = 42; @@ -767,7 +920,7 @@ TEST(SafeMatcherCastTest, ValueIsNotCopied) { TEST(ExpectThat, TakesLiterals) { EXPECT_THAT(1, 1); EXPECT_THAT(1.0, 1.0); - EXPECT_THAT(string(), ""); + EXPECT_THAT(std::string(), ""); } TEST(ExpectThat, TakesFunctions) { @@ -867,15 +1020,11 @@ class Unprintable { public: Unprintable() : c_('a') {} + bool operator==(const Unprintable& /* rhs */) const { return true; } private: char c_; }; -inline bool operator==(const Unprintable& /* lhs */, - const Unprintable& /* rhs */) { - return true; -} - TEST(EqTest, CanDescribeSelf) { Matcher<Unprintable> m = Eq(Unprintable()); EXPECT_EQ("is equal to 1-byte object <61>", Describe(m)); @@ -914,7 +1063,7 @@ TEST(TypedEqTest, CanDescribeSelf) { // Type<T>::IsTypeOf(v) compiles iff the type of value v is T, where T // is a "bare" type (i.e. not in the form of const U or U&). If v's // type is not T, the compiler will generate a message about -// "undefined referece". +// "undefined reference". template <typename T> struct Type { static bool IsTypeOf(const T& /* v */) { return true; } @@ -973,7 +1122,7 @@ TEST(LeTest, CanDescribeSelf) { // Tests that Lt(v) matches anything < v. TEST(LtTest, ImplementsLessThan) { - Matcher<const string&> m1 = Lt("Hello"); + Matcher<const std::string&> m1 = Lt("Hello"); EXPECT_TRUE(m1.Matches("Abc")); EXPECT_FALSE(m1.Matches("Hello")); EXPECT_FALSE(m1.Matches("Hello, world!")); @@ -1002,13 +1151,13 @@ TEST(NeTest, CanDescribeSelf) { // Tests that IsNull() matches any NULL pointer of any type. TEST(IsNullTest, MatchesNullPointer) { Matcher<int*> m1 = IsNull(); - int* p1 = NULL; + int* p1 = nullptr; int n = 0; EXPECT_TRUE(m1.Matches(p1)); EXPECT_FALSE(m1.Matches(&n)); Matcher<const char*> m2 = IsNull(); - const char* p2 = NULL; + const char* p2 = nullptr; EXPECT_TRUE(m2.Matches(p2)); EXPECT_FALSE(m2.Matches("hi")); @@ -1022,7 +1171,7 @@ TEST(IsNullTest, MatchesNullPointer) { // gmock_matchers_test::IsNullTest_MatchesNullPointer_Test::TestBody()') // gmock-matchers.h: (instantiating: 'testing::PolymorphicMatc Matcher<void*> m3 = IsNull(); - void* p3 = NULL; + void* p3 = nullptr; EXPECT_TRUE(m3.Matches(p3)); EXPECT_FALSE(m3.Matches(reinterpret_cast<void*>(0xbeef))); #endif @@ -1046,14 +1195,14 @@ TEST(IsNullTest, ReferenceToConstLinkedPtr) { EXPECT_FALSE(m.Matches(non_null_p)); } -#if GTEST_HAS_STD_FUNCTION_ +#if GTEST_LANG_CXX11 TEST(IsNullTest, StdFunction) { const Matcher<std::function<void()>> m = IsNull(); EXPECT_TRUE(m.Matches(std::function<void()>())); EXPECT_FALSE(m.Matches([]{})); } -#endif // GTEST_HAS_STD_FUNCTION_ +#endif // GTEST_LANG_CXX11 // Tests that IsNull() describes itself properly. TEST(IsNullTest, CanDescribeSelf) { @@ -1065,13 +1214,13 @@ TEST(IsNullTest, CanDescribeSelf) { // Tests that NotNull() matches any non-NULL pointer of any type. TEST(NotNullTest, MatchesNonNullPointer) { Matcher<int*> m1 = NotNull(); - int* p1 = NULL; + int* p1 = nullptr; int n = 0; EXPECT_FALSE(m1.Matches(p1)); EXPECT_TRUE(m1.Matches(&n)); Matcher<const char*> m2 = NotNull(); - const char* p2 = NULL; + const char* p2 = nullptr; EXPECT_FALSE(m2.Matches(p2)); EXPECT_TRUE(m2.Matches("hi")); } @@ -1094,14 +1243,14 @@ TEST(NotNullTest, ReferenceToConstLinkedPtr) { EXPECT_TRUE(m.Matches(non_null_p)); } -#if GTEST_HAS_STD_FUNCTION_ +#if GTEST_LANG_CXX11 TEST(NotNullTest, StdFunction) { const Matcher<std::function<void()>> m = NotNull(); EXPECT_TRUE(m.Matches([]{})); EXPECT_FALSE(m.Matches(std::function<void()>())); } -#endif // GTEST_HAS_STD_FUNCTION_ +#endif // GTEST_LANG_CXX11 // Tests that NotNull() describes itself properly. TEST(NotNullTest, CanDescribeSelf) { @@ -1125,7 +1274,7 @@ TEST(RefTest, CanDescribeSelf) { Matcher<int&> m = Ref(n); stringstream ss; ss << "references the variable @" << &n << " 5"; - EXPECT_EQ(string(ss.str()), Describe(m)); + EXPECT_EQ(ss.str(), Describe(m)); } // Test that Ref(non_const_varialbe) can be used as a matcher for a @@ -1169,39 +1318,58 @@ TEST(RefTest, ExplainsResult) { // Tests string comparison matchers. TEST(StrEqTest, MatchesEqualString) { - Matcher<const char*> m = StrEq(string("Hello")); + Matcher<const char*> m = StrEq(std::string("Hello")); EXPECT_TRUE(m.Matches("Hello")); EXPECT_FALSE(m.Matches("hello")); - EXPECT_FALSE(m.Matches(NULL)); + EXPECT_FALSE(m.Matches(nullptr)); - Matcher<const string&> m2 = StrEq("Hello"); + Matcher<const std::string&> m2 = StrEq("Hello"); EXPECT_TRUE(m2.Matches("Hello")); EXPECT_FALSE(m2.Matches("Hi")); + +#if GTEST_HAS_ABSL + Matcher<const absl::string_view&> m3 = StrEq("Hello"); + EXPECT_TRUE(m3.Matches(absl::string_view("Hello"))); + EXPECT_FALSE(m3.Matches(absl::string_view("hello"))); + EXPECT_FALSE(m3.Matches(absl::string_view())); + + Matcher<const absl::string_view&> m_empty = StrEq(""); + EXPECT_TRUE(m_empty.Matches(absl::string_view(""))); + EXPECT_TRUE(m_empty.Matches(absl::string_view())); + EXPECT_FALSE(m_empty.Matches(absl::string_view("hello"))); +#endif // GTEST_HAS_ABSL } TEST(StrEqTest, CanDescribeSelf) { - Matcher<string> m = StrEq("Hi-\'\"?\\\a\b\f\n\r\t\v\xD3"); + Matcher<std::string> m = StrEq("Hi-\'\"?\\\a\b\f\n\r\t\v\xD3"); EXPECT_EQ("is equal to \"Hi-\'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\\xD3\"", Describe(m)); - string str("01204500800"); + std::string str("01204500800"); str[3] = '\0'; - Matcher<string> m2 = StrEq(str); + Matcher<std::string> m2 = StrEq(str); EXPECT_EQ("is equal to \"012\\04500800\"", Describe(m2)); str[0] = str[6] = str[7] = str[9] = str[10] = '\0'; - Matcher<string> m3 = StrEq(str); + Matcher<std::string> m3 = StrEq(str); EXPECT_EQ("is equal to \"\\012\\045\\0\\08\\0\\0\"", Describe(m3)); } TEST(StrNeTest, MatchesUnequalString) { Matcher<const char*> m = StrNe("Hello"); EXPECT_TRUE(m.Matches("")); - EXPECT_TRUE(m.Matches(NULL)); + EXPECT_TRUE(m.Matches(nullptr)); EXPECT_FALSE(m.Matches("Hello")); - Matcher<string> m2 = StrNe(string("Hello")); + Matcher<std::string> m2 = StrNe(std::string("Hello")); EXPECT_TRUE(m2.Matches("hello")); EXPECT_FALSE(m2.Matches("Hello")); + +#if GTEST_HAS_ABSL + Matcher<const absl::string_view> m3 = StrNe("Hello"); + EXPECT_TRUE(m3.Matches(absl::string_view(""))); + EXPECT_TRUE(m3.Matches(absl::string_view())); + EXPECT_FALSE(m3.Matches(absl::string_view("Hello"))); +#endif // GTEST_HAS_ABSL } TEST(StrNeTest, CanDescribeSelf) { @@ -1210,57 +1378,73 @@ TEST(StrNeTest, CanDescribeSelf) { } TEST(StrCaseEqTest, MatchesEqualStringIgnoringCase) { - Matcher<const char*> m = StrCaseEq(string("Hello")); + Matcher<const char*> m = StrCaseEq(std::string("Hello")); EXPECT_TRUE(m.Matches("Hello")); EXPECT_TRUE(m.Matches("hello")); EXPECT_FALSE(m.Matches("Hi")); - EXPECT_FALSE(m.Matches(NULL)); + EXPECT_FALSE(m.Matches(nullptr)); - Matcher<const string&> m2 = StrCaseEq("Hello"); + Matcher<const std::string&> m2 = StrCaseEq("Hello"); EXPECT_TRUE(m2.Matches("hello")); EXPECT_FALSE(m2.Matches("Hi")); + +#if GTEST_HAS_ABSL + Matcher<const absl::string_view&> m3 = StrCaseEq(std::string("Hello")); + EXPECT_TRUE(m3.Matches(absl::string_view("Hello"))); + EXPECT_TRUE(m3.Matches(absl::string_view("hello"))); + EXPECT_FALSE(m3.Matches(absl::string_view("Hi"))); + EXPECT_FALSE(m3.Matches(absl::string_view())); +#endif // GTEST_HAS_ABSL } TEST(StrCaseEqTest, MatchesEqualStringWith0IgnoringCase) { - string str1("oabocdooeoo"); - string str2("OABOCDOOEOO"); - Matcher<const string&> m0 = StrCaseEq(str1); - EXPECT_FALSE(m0.Matches(str2 + string(1, '\0'))); + std::string str1("oabocdooeoo"); + std::string str2("OABOCDOOEOO"); + Matcher<const std::string&> m0 = StrCaseEq(str1); + EXPECT_FALSE(m0.Matches(str2 + std::string(1, '\0'))); str1[3] = str2[3] = '\0'; - Matcher<const string&> m1 = StrCaseEq(str1); + Matcher<const std::string&> m1 = StrCaseEq(str1); EXPECT_TRUE(m1.Matches(str2)); str1[0] = str1[6] = str1[7] = str1[10] = '\0'; str2[0] = str2[6] = str2[7] = str2[10] = '\0'; - Matcher<const string&> m2 = StrCaseEq(str1); + Matcher<const std::string&> m2 = StrCaseEq(str1); str1[9] = str2[9] = '\0'; EXPECT_FALSE(m2.Matches(str2)); - Matcher<const string&> m3 = StrCaseEq(str1); + Matcher<const std::string&> m3 = StrCaseEq(str1); EXPECT_TRUE(m3.Matches(str2)); EXPECT_FALSE(m3.Matches(str2 + "x")); str2.append(1, '\0'); EXPECT_FALSE(m3.Matches(str2)); - EXPECT_FALSE(m3.Matches(string(str2, 0, 9))); + EXPECT_FALSE(m3.Matches(std::string(str2, 0, 9))); } TEST(StrCaseEqTest, CanDescribeSelf) { - Matcher<string> m = StrCaseEq("Hi"); + Matcher<std::string> m = StrCaseEq("Hi"); EXPECT_EQ("is equal to (ignoring case) \"Hi\"", Describe(m)); } TEST(StrCaseNeTest, MatchesUnequalStringIgnoringCase) { Matcher<const char*> m = StrCaseNe("Hello"); EXPECT_TRUE(m.Matches("Hi")); - EXPECT_TRUE(m.Matches(NULL)); + EXPECT_TRUE(m.Matches(nullptr)); EXPECT_FALSE(m.Matches("Hello")); EXPECT_FALSE(m.Matches("hello")); - Matcher<string> m2 = StrCaseNe(string("Hello")); + Matcher<std::string> m2 = StrCaseNe(std::string("Hello")); EXPECT_TRUE(m2.Matches("")); EXPECT_FALSE(m2.Matches("Hello")); + +#if GTEST_HAS_ABSL + Matcher<const absl::string_view> m3 = StrCaseNe("Hello"); + EXPECT_TRUE(m3.Matches(absl::string_view("Hi"))); + EXPECT_TRUE(m3.Matches(absl::string_view())); + EXPECT_FALSE(m3.Matches(absl::string_view("Hello"))); + EXPECT_FALSE(m3.Matches(absl::string_view("hello"))); +#endif // GTEST_HAS_ABSL } TEST(StrCaseNeTest, CanDescribeSelf) { @@ -1270,13 +1454,17 @@ TEST(StrCaseNeTest, CanDescribeSelf) { // Tests that HasSubstr() works for matching string-typed values. TEST(HasSubstrTest, WorksForStringClasses) { - const Matcher<string> m1 = HasSubstr("foo"); - EXPECT_TRUE(m1.Matches(string("I love food."))); - EXPECT_FALSE(m1.Matches(string("tofo"))); + const Matcher<std::string> m1 = HasSubstr("foo"); + EXPECT_TRUE(m1.Matches(std::string("I love food."))); + EXPECT_FALSE(m1.Matches(std::string("tofo"))); const Matcher<const std::string&> m2 = HasSubstr("foo"); EXPECT_TRUE(m2.Matches(std::string("I love food."))); EXPECT_FALSE(m2.Matches(std::string("tofo"))); + + const Matcher<std::string> m_empty = HasSubstr(""); + EXPECT_TRUE(m_empty.Matches(std::string())); + EXPECT_TRUE(m_empty.Matches(std::string("not empty"))); } // Tests that HasSubstr() works for matching C-string-typed values. @@ -1284,17 +1472,42 @@ TEST(HasSubstrTest, WorksForCStrings) { const Matcher<char*> m1 = HasSubstr("foo"); EXPECT_TRUE(m1.Matches(const_cast<char*>("I love food."))); EXPECT_FALSE(m1.Matches(const_cast<char*>("tofo"))); - EXPECT_FALSE(m1.Matches(NULL)); + EXPECT_FALSE(m1.Matches(nullptr)); const Matcher<const char*> m2 = HasSubstr("foo"); EXPECT_TRUE(m2.Matches("I love food.")); EXPECT_FALSE(m2.Matches("tofo")); - EXPECT_FALSE(m2.Matches(NULL)); + EXPECT_FALSE(m2.Matches(nullptr)); + + const Matcher<const char*> m_empty = HasSubstr(""); + EXPECT_TRUE(m_empty.Matches("not empty")); + EXPECT_TRUE(m_empty.Matches("")); + EXPECT_FALSE(m_empty.Matches(nullptr)); } +#if GTEST_HAS_ABSL +// Tests that HasSubstr() works for matching absl::string_view-typed values. +TEST(HasSubstrTest, WorksForStringViewClasses) { + const Matcher<absl::string_view> m1 = HasSubstr("foo"); + EXPECT_TRUE(m1.Matches(absl::string_view("I love food."))); + EXPECT_FALSE(m1.Matches(absl::string_view("tofo"))); + EXPECT_FALSE(m1.Matches(absl::string_view())); + + const Matcher<const absl::string_view&> m2 = HasSubstr("foo"); + EXPECT_TRUE(m2.Matches(absl::string_view("I love food."))); + EXPECT_FALSE(m2.Matches(absl::string_view("tofo"))); + EXPECT_FALSE(m2.Matches(absl::string_view())); + + const Matcher<const absl::string_view&> m3 = HasSubstr(""); + EXPECT_TRUE(m3.Matches(absl::string_view("foo"))); + EXPECT_TRUE(m3.Matches(absl::string_view(""))); + EXPECT_TRUE(m3.Matches(absl::string_view())); +} +#endif // GTEST_HAS_ABSL + // Tests that HasSubstr(s) describes itself properly. TEST(HasSubstrTest, CanDescribeSelf) { - Matcher<string> m = HasSubstr("foo\n\""); + Matcher<std::string> m = HasSubstr("foo\n\""); EXPECT_EQ("has substring \"foo\\n\\\"\"", Describe(m)); } @@ -1320,6 +1533,35 @@ TEST(KeyTest, MatchesCorrectly) { EXPECT_THAT(p, Not(Key(Lt(25)))); } +#if GTEST_LANG_CXX11 +template <size_t I> +struct Tag {}; + +struct PairWithGet { + int member_1; + string member_2; + using first_type = int; + using second_type = string; + + const int& GetImpl(Tag<0>) const { return member_1; } + const string& GetImpl(Tag<1>) const { return member_2; } +}; +template <size_t I> +auto get(const PairWithGet& value) -> decltype(value.GetImpl(Tag<I>())) { + return value.GetImpl(Tag<I>()); +} +TEST(PairTest, MatchesPairWithGetCorrectly) { + PairWithGet p{25, "foo"}; + EXPECT_THAT(p, Key(25)); + EXPECT_THAT(p, Not(Key(42))); + EXPECT_THAT(p, Key(Ge(20))); + EXPECT_THAT(p, Not(Key(Lt(25)))); + + std::vector<PairWithGet> v = {{11, "Foo"}, {29, "gMockIsBestMock"}}; + EXPECT_THAT(v, Contains(Key(29))); +} +#endif // GTEST_LANG_CXX11 + TEST(KeyTest, SafelyCastsInnerMatcher) { Matcher<int> is_positive = Gt(0); Matcher<int> is_negative = Lt(0); @@ -1457,20 +1699,39 @@ TEST(PairTest, InsideContainsUsingMap) { EXPECT_THAT(container, Not(Contains(Pair(3, _)))); } +#if GTEST_LANG_CXX11 +TEST(PairTest, UseGetInsteadOfMembers) { + PairWithGet pair{7, "ABC"}; + EXPECT_THAT(pair, Pair(7, "ABC")); + EXPECT_THAT(pair, Pair(Ge(7), HasSubstr("AB"))); + EXPECT_THAT(pair, Not(Pair(Lt(7), "ABC"))); + + std::vector<PairWithGet> v = {{11, "Foo"}, {29, "gMockIsBestMock"}}; + EXPECT_THAT(v, ElementsAre(Pair(11, string("Foo")), Pair(Ge(10), Not("")))); +} +#endif // GTEST_LANG_CXX11 + // Tests StartsWith(s). TEST(StartsWithTest, MatchesStringWithGivenPrefix) { - const Matcher<const char*> m1 = StartsWith(string("")); + const Matcher<const char*> m1 = StartsWith(std::string("")); EXPECT_TRUE(m1.Matches("Hi")); EXPECT_TRUE(m1.Matches("")); - EXPECT_FALSE(m1.Matches(NULL)); + EXPECT_FALSE(m1.Matches(nullptr)); - const Matcher<const string&> m2 = StartsWith("Hi"); + const Matcher<const std::string&> m2 = StartsWith("Hi"); EXPECT_TRUE(m2.Matches("Hi")); EXPECT_TRUE(m2.Matches("Hi Hi!")); EXPECT_TRUE(m2.Matches("High")); EXPECT_FALSE(m2.Matches("H")); EXPECT_FALSE(m2.Matches(" Hi")); + +#if GTEST_HAS_ABSL + const Matcher<absl::string_view> m_empty = StartsWith(""); + EXPECT_TRUE(m_empty.Matches(absl::string_view())); + EXPECT_TRUE(m_empty.Matches(absl::string_view(""))); + EXPECT_TRUE(m_empty.Matches(absl::string_view("not empty"))); +#endif // GTEST_HAS_ABSL } TEST(StartsWithTest, CanDescribeSelf) { @@ -1484,14 +1745,31 @@ TEST(EndsWithTest, MatchesStringWithGivenSuffix) { const Matcher<const char*> m1 = EndsWith(""); EXPECT_TRUE(m1.Matches("Hi")); EXPECT_TRUE(m1.Matches("")); - EXPECT_FALSE(m1.Matches(NULL)); + EXPECT_FALSE(m1.Matches(nullptr)); - const Matcher<const string&> m2 = EndsWith(string("Hi")); + const Matcher<const std::string&> m2 = EndsWith(std::string("Hi")); EXPECT_TRUE(m2.Matches("Hi")); EXPECT_TRUE(m2.Matches("Wow Hi Hi")); EXPECT_TRUE(m2.Matches("Super Hi")); EXPECT_FALSE(m2.Matches("i")); EXPECT_FALSE(m2.Matches("Hi ")); + +#if GTEST_HAS_GLOBAL_STRING + const Matcher<const ::string&> m3 = EndsWith(::string("Hi")); + EXPECT_TRUE(m3.Matches("Hi")); + EXPECT_TRUE(m3.Matches("Wow Hi Hi")); + EXPECT_TRUE(m3.Matches("Super Hi")); + EXPECT_FALSE(m3.Matches("i")); + EXPECT_FALSE(m3.Matches("Hi ")); +#endif // GTEST_HAS_GLOBAL_STRING + +#if GTEST_HAS_ABSL + const Matcher<const absl::string_view&> m4 = EndsWith(""); + EXPECT_TRUE(m4.Matches("Hi")); + EXPECT_TRUE(m4.Matches("")); + EXPECT_TRUE(m4.Matches(absl::string_view())); + EXPECT_TRUE(m4.Matches(absl::string_view(""))); +#endif // GTEST_HAS_ABSL } TEST(EndsWithTest, CanDescribeSelf) { @@ -1505,34 +1783,61 @@ TEST(MatchesRegexTest, MatchesStringMatchingGivenRegex) { const Matcher<const char*> m1 = MatchesRegex("a.*z"); EXPECT_TRUE(m1.Matches("az")); EXPECT_TRUE(m1.Matches("abcz")); - EXPECT_FALSE(m1.Matches(NULL)); + EXPECT_FALSE(m1.Matches(nullptr)); - const Matcher<const string&> m2 = MatchesRegex(new RE("a.*z")); + const Matcher<const std::string&> m2 = MatchesRegex(new RE("a.*z")); EXPECT_TRUE(m2.Matches("azbz")); EXPECT_FALSE(m2.Matches("az1")); EXPECT_FALSE(m2.Matches("1az")); + +#if GTEST_HAS_ABSL + const Matcher<const absl::string_view&> m3 = MatchesRegex("a.*z"); + EXPECT_TRUE(m3.Matches(absl::string_view("az"))); + EXPECT_TRUE(m3.Matches(absl::string_view("abcz"))); + EXPECT_FALSE(m3.Matches(absl::string_view("1az"))); + EXPECT_FALSE(m3.Matches(absl::string_view())); + const Matcher<const absl::string_view&> m4 = MatchesRegex(""); + EXPECT_TRUE(m4.Matches(absl::string_view(""))); + EXPECT_TRUE(m4.Matches(absl::string_view())); +#endif // GTEST_HAS_ABSL } TEST(MatchesRegexTest, CanDescribeSelf) { - Matcher<const std::string> m1 = MatchesRegex(string("Hi.*")); + Matcher<const std::string> m1 = MatchesRegex(std::string("Hi.*")); EXPECT_EQ("matches regular expression \"Hi.*\"", Describe(m1)); Matcher<const char*> m2 = MatchesRegex(new RE("a.*")); EXPECT_EQ("matches regular expression \"a.*\"", Describe(m2)); + +#if GTEST_HAS_ABSL + Matcher<const absl::string_view> m3 = MatchesRegex(new RE("0.*")); + EXPECT_EQ("matches regular expression \"0.*\"", Describe(m3)); +#endif // GTEST_HAS_ABSL } // Tests ContainsRegex(). TEST(ContainsRegexTest, MatchesStringContainingGivenRegex) { - const Matcher<const char*> m1 = ContainsRegex(string("a.*z")); + const Matcher<const char*> m1 = ContainsRegex(std::string("a.*z")); EXPECT_TRUE(m1.Matches("az")); EXPECT_TRUE(m1.Matches("0abcz1")); - EXPECT_FALSE(m1.Matches(NULL)); + EXPECT_FALSE(m1.Matches(nullptr)); - const Matcher<const string&> m2 = ContainsRegex(new RE("a.*z")); + const Matcher<const std::string&> m2 = ContainsRegex(new RE("a.*z")); EXPECT_TRUE(m2.Matches("azbz")); EXPECT_TRUE(m2.Matches("az1")); EXPECT_FALSE(m2.Matches("1a")); + +#if GTEST_HAS_ABSL + const Matcher<const absl::string_view&> m3 = ContainsRegex(new RE("a.*z")); + EXPECT_TRUE(m3.Matches(absl::string_view("azbz"))); + EXPECT_TRUE(m3.Matches(absl::string_view("az1"))); + EXPECT_FALSE(m3.Matches(absl::string_view("1a"))); + EXPECT_FALSE(m3.Matches(absl::string_view())); + const Matcher<const absl::string_view&> m4 = ContainsRegex(""); + EXPECT_TRUE(m4.Matches(absl::string_view(""))); + EXPECT_TRUE(m4.Matches(absl::string_view())); +#endif // GTEST_HAS_ABSL } TEST(ContainsRegexTest, CanDescribeSelf) { @@ -1541,6 +1846,11 @@ TEST(ContainsRegexTest, CanDescribeSelf) { Matcher<const char*> m2 = ContainsRegex(new RE("a.*")); EXPECT_EQ("contains regular expression \"a.*\"", Describe(m2)); + +#if GTEST_HAS_ABSL + Matcher<const absl::string_view> m3 = ContainsRegex(new RE("0.*")); + EXPECT_EQ("contains regular expression \"0.*\"", Describe(m3)); +#endif // GTEST_HAS_ABSL } // Tests for wide strings. @@ -1549,7 +1859,7 @@ TEST(StdWideStrEqTest, MatchesEqual) { Matcher<const wchar_t*> m = StrEq(::std::wstring(L"Hello")); EXPECT_TRUE(m.Matches(L"Hello")); EXPECT_FALSE(m.Matches(L"hello")); - EXPECT_FALSE(m.Matches(NULL)); + EXPECT_FALSE(m.Matches(nullptr)); Matcher<const ::std::wstring&> m2 = StrEq(L"Hello"); EXPECT_TRUE(m2.Matches(L"Hello")); @@ -1589,7 +1899,7 @@ TEST(StdWideStrEqTest, CanDescribeSelf) { TEST(StdWideStrNeTest, MatchesUnequalString) { Matcher<const wchar_t*> m = StrNe(L"Hello"); EXPECT_TRUE(m.Matches(L"")); - EXPECT_TRUE(m.Matches(NULL)); + EXPECT_TRUE(m.Matches(nullptr)); EXPECT_FALSE(m.Matches(L"Hello")); Matcher< ::std::wstring> m2 = StrNe(::std::wstring(L"Hello")); @@ -1607,7 +1917,7 @@ TEST(StdWideStrCaseEqTest, MatchesEqualStringIgnoringCase) { EXPECT_TRUE(m.Matches(L"Hello")); EXPECT_TRUE(m.Matches(L"hello")); EXPECT_FALSE(m.Matches(L"Hi")); - EXPECT_FALSE(m.Matches(NULL)); + EXPECT_FALSE(m.Matches(nullptr)); Matcher<const ::std::wstring&> m2 = StrCaseEq(L"Hello"); EXPECT_TRUE(m2.Matches(L"hello")); @@ -1647,7 +1957,7 @@ TEST(StdWideStrCaseEqTest, CanDescribeSelf) { TEST(StdWideStrCaseNeTest, MatchesUnequalStringIgnoringCase) { Matcher<const wchar_t*> m = StrCaseNe(L"Hello"); EXPECT_TRUE(m.Matches(L"Hi")); - EXPECT_TRUE(m.Matches(NULL)); + EXPECT_TRUE(m.Matches(nullptr)); EXPECT_FALSE(m.Matches(L"Hello")); EXPECT_FALSE(m.Matches(L"hello")); @@ -1677,12 +1987,12 @@ TEST(StdWideHasSubstrTest, WorksForCStrings) { const Matcher<wchar_t*> m1 = HasSubstr(L"foo"); EXPECT_TRUE(m1.Matches(const_cast<wchar_t*>(L"I love food."))); EXPECT_FALSE(m1.Matches(const_cast<wchar_t*>(L"tofo"))); - EXPECT_FALSE(m1.Matches(NULL)); + EXPECT_FALSE(m1.Matches(nullptr)); const Matcher<const wchar_t*> m2 = HasSubstr(L"foo"); EXPECT_TRUE(m2.Matches(L"I love food.")); EXPECT_FALSE(m2.Matches(L"tofo")); - EXPECT_FALSE(m2.Matches(NULL)); + EXPECT_FALSE(m2.Matches(nullptr)); } // Tests that HasSubstr(s) describes itself properly. @@ -1697,7 +2007,7 @@ TEST(StdWideStartsWithTest, MatchesStringWithGivenPrefix) { const Matcher<const wchar_t*> m1 = StartsWith(::std::wstring(L"")); EXPECT_TRUE(m1.Matches(L"Hi")); EXPECT_TRUE(m1.Matches(L"")); - EXPECT_FALSE(m1.Matches(NULL)); + EXPECT_FALSE(m1.Matches(nullptr)); const Matcher<const ::std::wstring&> m2 = StartsWith(L"Hi"); EXPECT_TRUE(m2.Matches(L"Hi")); @@ -1718,7 +2028,7 @@ TEST(StdWideEndsWithTest, MatchesStringWithGivenSuffix) { const Matcher<const wchar_t*> m1 = EndsWith(L""); EXPECT_TRUE(m1.Matches(L"Hi")); EXPECT_TRUE(m1.Matches(L"")); - EXPECT_FALSE(m1.Matches(NULL)); + EXPECT_FALSE(m1.Matches(nullptr)); const Matcher<const ::std::wstring&> m2 = EndsWith(::std::wstring(L"Hi")); EXPECT_TRUE(m2.Matches(L"Hi")); @@ -1740,7 +2050,7 @@ TEST(GlobalWideStrEqTest, MatchesEqual) { Matcher<const wchar_t*> m = StrEq(::wstring(L"Hello")); EXPECT_TRUE(m.Matches(L"Hello")); EXPECT_FALSE(m.Matches(L"hello")); - EXPECT_FALSE(m.Matches(NULL)); + EXPECT_FALSE(m.Matches(nullptr)); Matcher<const ::wstring&> m2 = StrEq(L"Hello"); EXPECT_TRUE(m2.Matches(L"Hello")); @@ -1780,7 +2090,7 @@ TEST(GlobalWideStrEqTest, CanDescribeSelf) { TEST(GlobalWideStrNeTest, MatchesUnequalString) { Matcher<const wchar_t*> m = StrNe(L"Hello"); EXPECT_TRUE(m.Matches(L"")); - EXPECT_TRUE(m.Matches(NULL)); + EXPECT_TRUE(m.Matches(nullptr)); EXPECT_FALSE(m.Matches(L"Hello")); Matcher< ::wstring> m2 = StrNe(::wstring(L"Hello")); @@ -1798,7 +2108,7 @@ TEST(GlobalWideStrCaseEqTest, MatchesEqualStringIgnoringCase) { EXPECT_TRUE(m.Matches(L"Hello")); EXPECT_TRUE(m.Matches(L"hello")); EXPECT_FALSE(m.Matches(L"Hi")); - EXPECT_FALSE(m.Matches(NULL)); + EXPECT_FALSE(m.Matches(nullptr)); Matcher<const ::wstring&> m2 = StrCaseEq(L"Hello"); EXPECT_TRUE(m2.Matches(L"hello")); @@ -1838,7 +2148,7 @@ TEST(GlobalWideStrCaseEqTest, CanDescribeSelf) { TEST(GlobalWideStrCaseNeTest, MatchesUnequalStringIgnoringCase) { Matcher<const wchar_t*> m = StrCaseNe(L"Hello"); EXPECT_TRUE(m.Matches(L"Hi")); - EXPECT_TRUE(m.Matches(NULL)); + EXPECT_TRUE(m.Matches(nullptr)); EXPECT_FALSE(m.Matches(L"Hello")); EXPECT_FALSE(m.Matches(L"hello")); @@ -1868,12 +2178,12 @@ TEST(GlobalWideHasSubstrTest, WorksForCStrings) { const Matcher<wchar_t*> m1 = HasSubstr(L"foo"); EXPECT_TRUE(m1.Matches(const_cast<wchar_t*>(L"I love food."))); EXPECT_FALSE(m1.Matches(const_cast<wchar_t*>(L"tofo"))); - EXPECT_FALSE(m1.Matches(NULL)); + EXPECT_FALSE(m1.Matches(nullptr)); const Matcher<const wchar_t*> m2 = HasSubstr(L"foo"); EXPECT_TRUE(m2.Matches(L"I love food.")); EXPECT_FALSE(m2.Matches(L"tofo")); - EXPECT_FALSE(m2.Matches(NULL)); + EXPECT_FALSE(m2.Matches(nullptr)); } // Tests that HasSubstr(s) describes itself properly. @@ -1888,7 +2198,7 @@ TEST(GlobalWideStartsWithTest, MatchesStringWithGivenPrefix) { const Matcher<const wchar_t*> m1 = StartsWith(::wstring(L"")); EXPECT_TRUE(m1.Matches(L"Hi")); EXPECT_TRUE(m1.Matches(L"")); - EXPECT_FALSE(m1.Matches(NULL)); + EXPECT_FALSE(m1.Matches(nullptr)); const Matcher<const ::wstring&> m2 = StartsWith(L"Hi"); EXPECT_TRUE(m2.Matches(L"Hi")); @@ -1909,7 +2219,7 @@ TEST(GlobalWideEndsWithTest, MatchesStringWithGivenSuffix) { const Matcher<const wchar_t*> m1 = EndsWith(L""); EXPECT_TRUE(m1.Matches(L"Hi")); EXPECT_TRUE(m1.Matches(L"")); - EXPECT_FALSE(m1.Matches(NULL)); + EXPECT_FALSE(m1.Matches(nullptr)); const Matcher<const ::wstring&> m2 = EndsWith(::wstring(L"Hi")); EXPECT_TRUE(m2.Matches(L"Hi")); @@ -1926,8 +2236,7 @@ TEST(GlobalWideEndsWithTest, CanDescribeSelf) { #endif // GTEST_HAS_GLOBAL_WSTRING - -typedef ::testing::tuple<long, int> Tuple2; // NOLINT +typedef ::std::tuple<long, int> Tuple2; // NOLINT // Tests that Eq() matches a 2-tuple where the first field == the // second field. @@ -2018,6 +2327,148 @@ TEST(Ne2Test, CanDescribeSelf) { EXPECT_EQ("are an unequal pair", Describe(m)); } +// Tests that FloatEq() matches a 2-tuple where +// FloatEq(first field) matches the second field. +TEST(FloatEq2Test, MatchesEqualArguments) { + typedef ::std::tuple<float, float> Tpl; + Matcher<const Tpl&> m = FloatEq(); + EXPECT_TRUE(m.Matches(Tpl(1.0f, 1.0f))); + EXPECT_TRUE(m.Matches(Tpl(0.3f, 0.1f + 0.1f + 0.1f))); + EXPECT_FALSE(m.Matches(Tpl(1.1f, 1.0f))); +} + +// Tests that FloatEq() describes itself properly. +TEST(FloatEq2Test, CanDescribeSelf) { + Matcher<const ::std::tuple<float, float>&> m = FloatEq(); + EXPECT_EQ("are an almost-equal pair", Describe(m)); +} + +// Tests that NanSensitiveFloatEq() matches a 2-tuple where +// NanSensitiveFloatEq(first field) matches the second field. +TEST(NanSensitiveFloatEqTest, MatchesEqualArgumentsWithNaN) { + typedef ::std::tuple<float, float> Tpl; + Matcher<const Tpl&> m = NanSensitiveFloatEq(); + EXPECT_TRUE(m.Matches(Tpl(1.0f, 1.0f))); + EXPECT_TRUE(m.Matches(Tpl(std::numeric_limits<float>::quiet_NaN(), + std::numeric_limits<float>::quiet_NaN()))); + EXPECT_FALSE(m.Matches(Tpl(1.1f, 1.0f))); + EXPECT_FALSE(m.Matches(Tpl(1.0f, std::numeric_limits<float>::quiet_NaN()))); + EXPECT_FALSE(m.Matches(Tpl(std::numeric_limits<float>::quiet_NaN(), 1.0f))); +} + +// Tests that NanSensitiveFloatEq() describes itself properly. +TEST(NanSensitiveFloatEqTest, CanDescribeSelfWithNaNs) { + Matcher<const ::std::tuple<float, float>&> m = NanSensitiveFloatEq(); + EXPECT_EQ("are an almost-equal pair", Describe(m)); +} + +// Tests that DoubleEq() matches a 2-tuple where +// DoubleEq(first field) matches the second field. +TEST(DoubleEq2Test, MatchesEqualArguments) { + typedef ::std::tuple<double, double> Tpl; + Matcher<const Tpl&> m = DoubleEq(); + EXPECT_TRUE(m.Matches(Tpl(1.0, 1.0))); + EXPECT_TRUE(m.Matches(Tpl(0.3, 0.1 + 0.1 + 0.1))); + EXPECT_FALSE(m.Matches(Tpl(1.1, 1.0))); +} + +// Tests that DoubleEq() describes itself properly. +TEST(DoubleEq2Test, CanDescribeSelf) { + Matcher<const ::std::tuple<double, double>&> m = DoubleEq(); + EXPECT_EQ("are an almost-equal pair", Describe(m)); +} + +// Tests that NanSensitiveDoubleEq() matches a 2-tuple where +// NanSensitiveDoubleEq(first field) matches the second field. +TEST(NanSensitiveDoubleEqTest, MatchesEqualArgumentsWithNaN) { + typedef ::std::tuple<double, double> Tpl; + Matcher<const Tpl&> m = NanSensitiveDoubleEq(); + EXPECT_TRUE(m.Matches(Tpl(1.0f, 1.0f))); + EXPECT_TRUE(m.Matches(Tpl(std::numeric_limits<double>::quiet_NaN(), + std::numeric_limits<double>::quiet_NaN()))); + EXPECT_FALSE(m.Matches(Tpl(1.1f, 1.0f))); + EXPECT_FALSE(m.Matches(Tpl(1.0f, std::numeric_limits<double>::quiet_NaN()))); + EXPECT_FALSE(m.Matches(Tpl(std::numeric_limits<double>::quiet_NaN(), 1.0f))); +} + +// Tests that DoubleEq() describes itself properly. +TEST(NanSensitiveDoubleEqTest, CanDescribeSelfWithNaNs) { + Matcher<const ::std::tuple<double, double>&> m = NanSensitiveDoubleEq(); + EXPECT_EQ("are an almost-equal pair", Describe(m)); +} + +// Tests that FloatEq() matches a 2-tuple where +// FloatNear(first field, max_abs_error) matches the second field. +TEST(FloatNear2Test, MatchesEqualArguments) { + typedef ::std::tuple<float, float> Tpl; + Matcher<const Tpl&> m = FloatNear(0.5f); + EXPECT_TRUE(m.Matches(Tpl(1.0f, 1.0f))); + EXPECT_TRUE(m.Matches(Tpl(1.3f, 1.0f))); + EXPECT_FALSE(m.Matches(Tpl(1.8f, 1.0f))); +} + +// Tests that FloatNear() describes itself properly. +TEST(FloatNear2Test, CanDescribeSelf) { + Matcher<const ::std::tuple<float, float>&> m = FloatNear(0.5f); + EXPECT_EQ("are an almost-equal pair", Describe(m)); +} + +// Tests that NanSensitiveFloatNear() matches a 2-tuple where +// NanSensitiveFloatNear(first field) matches the second field. +TEST(NanSensitiveFloatNearTest, MatchesNearbyArgumentsWithNaN) { + typedef ::std::tuple<float, float> Tpl; + Matcher<const Tpl&> m = NanSensitiveFloatNear(0.5f); + EXPECT_TRUE(m.Matches(Tpl(1.0f, 1.0f))); + EXPECT_TRUE(m.Matches(Tpl(1.1f, 1.0f))); + EXPECT_TRUE(m.Matches(Tpl(std::numeric_limits<float>::quiet_NaN(), + std::numeric_limits<float>::quiet_NaN()))); + EXPECT_FALSE(m.Matches(Tpl(1.6f, 1.0f))); + EXPECT_FALSE(m.Matches(Tpl(1.0f, std::numeric_limits<float>::quiet_NaN()))); + EXPECT_FALSE(m.Matches(Tpl(std::numeric_limits<float>::quiet_NaN(), 1.0f))); +} + +// Tests that NanSensitiveFloatNear() describes itself properly. +TEST(NanSensitiveFloatNearTest, CanDescribeSelfWithNaNs) { + Matcher<const ::std::tuple<float, float>&> m = NanSensitiveFloatNear(0.5f); + EXPECT_EQ("are an almost-equal pair", Describe(m)); +} + +// Tests that FloatEq() matches a 2-tuple where +// DoubleNear(first field, max_abs_error) matches the second field. +TEST(DoubleNear2Test, MatchesEqualArguments) { + typedef ::std::tuple<double, double> Tpl; + Matcher<const Tpl&> m = DoubleNear(0.5); + EXPECT_TRUE(m.Matches(Tpl(1.0, 1.0))); + EXPECT_TRUE(m.Matches(Tpl(1.3, 1.0))); + EXPECT_FALSE(m.Matches(Tpl(1.8, 1.0))); +} + +// Tests that DoubleNear() describes itself properly. +TEST(DoubleNear2Test, CanDescribeSelf) { + Matcher<const ::std::tuple<double, double>&> m = DoubleNear(0.5); + EXPECT_EQ("are an almost-equal pair", Describe(m)); +} + +// Tests that NanSensitiveDoubleNear() matches a 2-tuple where +// NanSensitiveDoubleNear(first field) matches the second field. +TEST(NanSensitiveDoubleNearTest, MatchesNearbyArgumentsWithNaN) { + typedef ::std::tuple<double, double> Tpl; + Matcher<const Tpl&> m = NanSensitiveDoubleNear(0.5f); + EXPECT_TRUE(m.Matches(Tpl(1.0f, 1.0f))); + EXPECT_TRUE(m.Matches(Tpl(1.1f, 1.0f))); + EXPECT_TRUE(m.Matches(Tpl(std::numeric_limits<double>::quiet_NaN(), + std::numeric_limits<double>::quiet_NaN()))); + EXPECT_FALSE(m.Matches(Tpl(1.6f, 1.0f))); + EXPECT_FALSE(m.Matches(Tpl(1.0f, std::numeric_limits<double>::quiet_NaN()))); + EXPECT_FALSE(m.Matches(Tpl(std::numeric_limits<double>::quiet_NaN(), 1.0f))); +} + +// Tests that NanSensitiveDoubleNear() describes itself properly. +TEST(NanSensitiveDoubleNearTest, CanDescribeSelfWithNaNs) { + Matcher<const ::std::tuple<double, double>&> m = NanSensitiveDoubleNear(0.5f); + EXPECT_EQ("are an almost-equal pair", Describe(m)); +} + // Tests that Not(m) matches any value that doesn't match m. TEST(NotTest, NegatesMatcher) { Matcher<int> m; @@ -2096,29 +2547,16 @@ TEST(AllOfTest, MatchesWhenAllMatch) { Ne(8), Ne(9))); AllOfMatches(10, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8), Ne(9), Ne(10))); + AllOfMatches( + 50, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8), Ne(9), + Ne(10), Ne(11), Ne(12), Ne(13), Ne(14), Ne(15), Ne(16), Ne(17), + Ne(18), Ne(19), Ne(20), Ne(21), Ne(22), Ne(23), Ne(24), Ne(25), + Ne(26), Ne(27), Ne(28), Ne(29), Ne(30), Ne(31), Ne(32), Ne(33), + Ne(34), Ne(35), Ne(36), Ne(37), Ne(38), Ne(39), Ne(40), Ne(41), + Ne(42), Ne(43), Ne(44), Ne(45), Ne(46), Ne(47), Ne(48), Ne(49), + Ne(50))); } -#if GTEST_LANG_CXX11 -// Tests the variadic version of the AllOfMatcher. -TEST(AllOfTest, VariadicMatchesWhenAllMatch) { - // Make sure AllOf is defined in the right namespace and does not depend on - // ADL. - ::testing::AllOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11); - Matcher<int> m = AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8), - Ne(9), Ne(10), Ne(11)); - EXPECT_THAT(Describe(m), EndsWith("and (isn't equal to 11))))))))))")); - AllOfMatches(11, m); - AllOfMatches(50, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8), - Ne(9), Ne(10), Ne(11), Ne(12), Ne(13), Ne(14), Ne(15), - Ne(16), Ne(17), Ne(18), Ne(19), Ne(20), Ne(21), Ne(22), - Ne(23), Ne(24), Ne(25), Ne(26), Ne(27), Ne(28), Ne(29), - Ne(30), Ne(31), Ne(32), Ne(33), Ne(34), Ne(35), Ne(36), - Ne(37), Ne(38), Ne(39), Ne(40), Ne(41), Ne(42), Ne(43), - Ne(44), Ne(45), Ne(46), Ne(47), Ne(48), Ne(49), - Ne(50))); -} - -#endif // GTEST_LANG_CXX11 // Tests that AllOf(m1, ..., mn) describes itself properly. TEST(AllOfTest, CanDescribeSelf) { @@ -2127,59 +2565,51 @@ TEST(AllOfTest, CanDescribeSelf) { EXPECT_EQ("(is <= 2) and (is >= 1)", Describe(m)); m = AllOf(Gt(0), Ne(1), Ne(2)); - EXPECT_EQ("(is > 0) and " - "((isn't equal to 1) and " - "(isn't equal to 2))", - Describe(m)); - + std::string expected_descr1 = + "(is > 0) and (isn't equal to 1) and (isn't equal to 2)"; + EXPECT_EQ(expected_descr1, Describe(m)); m = AllOf(Gt(0), Ne(1), Ne(2), Ne(3)); - EXPECT_EQ("((is > 0) and " - "(isn't equal to 1)) and " - "((isn't equal to 2) and " - "(isn't equal to 3))", - Describe(m)); - + std::string expected_descr2 = + "(is > 0) and (isn't equal to 1) and (isn't equal to 2) and (isn't equal " + "to 3)"; + EXPECT_EQ(expected_descr2, Describe(m)); m = AllOf(Ge(0), Lt(10), Ne(3), Ne(5), Ne(7)); - EXPECT_EQ("((is >= 0) and " - "(is < 10)) and " - "((isn't equal to 3) and " - "((isn't equal to 5) and " - "(isn't equal to 7)))", - Describe(m)); + std::string expected_descr3 = + "(is >= 0) and (is < 10) and (isn't equal to 3) and (isn't equal to 5) " + "and (isn't equal to 7)"; + EXPECT_EQ(expected_descr3, Describe(m)); } // Tests that AllOf(m1, ..., mn) describes its negation properly. TEST(AllOfTest, CanDescribeNegation) { Matcher<int> m; m = AllOf(Le(2), Ge(1)); - EXPECT_EQ("(isn't <= 2) or " - "(isn't >= 1)", - DescribeNegation(m)); + std::string expected_descr4 = "(isn't <= 2) or (isn't >= 1)"; + EXPECT_EQ(expected_descr4, DescribeNegation(m)); m = AllOf(Gt(0), Ne(1), Ne(2)); - EXPECT_EQ("(isn't > 0) or " - "((is equal to 1) or " - "(is equal to 2))", - DescribeNegation(m)); - + std::string expected_descr5 = + "(isn't > 0) or (is equal to 1) or (is equal to 2)"; + EXPECT_EQ(expected_descr5, DescribeNegation(m)); m = AllOf(Gt(0), Ne(1), Ne(2), Ne(3)); - EXPECT_EQ("((isn't > 0) or " - "(is equal to 1)) or " - "((is equal to 2) or " - "(is equal to 3))", - DescribeNegation(m)); - + std::string expected_descr6 = + "(isn't > 0) or (is equal to 1) or (is equal to 2) or (is equal to 3)"; + EXPECT_EQ(expected_descr6, DescribeNegation(m)); m = AllOf(Ge(0), Lt(10), Ne(3), Ne(5), Ne(7)); - EXPECT_EQ("((isn't >= 0) or " - "(isn't < 10)) or " - "((is equal to 3) or " - "((is equal to 5) or " - "(is equal to 7)))", - DescribeNegation(m)); + std::string expected_desr7 = + "(isn't >= 0) or (isn't < 10) or (is equal to 3) or (is equal to 5) or " + "(is equal to 7)"; + EXPECT_EQ(expected_desr7, DescribeNegation(m)); + + m = AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8), Ne(9), + Ne(10), Ne(11)); + AllOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11); + EXPECT_THAT(Describe(m), EndsWith("and (isn't equal to 11)")); + AllOfMatches(11, m); } // Tests that monomorphic matchers are safely cast by the AllOf matcher. @@ -2241,7 +2671,7 @@ TEST(AllOfTest, ExplainsResult) { } // Helper to allow easy testing of AnyOf matchers with num parameters. -void AnyOfMatches(int num, const Matcher<int>& m) { +static void AnyOfMatches(int num, const Matcher<int>& m) { SCOPED_TRACE(Describe(m)); EXPECT_FALSE(m.Matches(0)); for (int i = 1; i <= num; ++i) { @@ -2250,6 +2680,18 @@ void AnyOfMatches(int num, const Matcher<int>& m) { EXPECT_FALSE(m.Matches(num + 1)); } +#if GTEST_LANG_CXX11 +static void AnyOfStringMatches(int num, const Matcher<std::string>& m) { + SCOPED_TRACE(Describe(m)); + EXPECT_FALSE(m.Matches(std::to_string(0))); + + for (int i = 1; i <= num; ++i) { + EXPECT_TRUE(m.Matches(std::to_string(i))); + } + EXPECT_FALSE(m.Matches(std::to_string(num + 1))); +} +#endif + // Tests that AnyOf(m1, ..., mn) matches any value that matches at // least one of the given matchers. TEST(AnyOfTest, MatchesWhenAnyMatches) { @@ -2300,13 +2742,46 @@ TEST(AnyOfTest, VariadicMatchesWhenAnyMatches) { // on ADL. Matcher<int> m = ::testing::AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11); - EXPECT_THAT(Describe(m), EndsWith("or (is equal to 11))))))))))")); + EXPECT_THAT(Describe(m), EndsWith("or (is equal to 11)")); AnyOfMatches(11, m); AnyOfMatches(50, AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50)); + AnyOfStringMatches( + 50, AnyOf("1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", + "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", + "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", + "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", + "43", "44", "45", "46", "47", "48", "49", "50")); +} + +// Tests the variadic version of the ElementsAreMatcher +TEST(ElementsAreTest, HugeMatcher) { + vector<int> test_vector{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; + + EXPECT_THAT(test_vector, + ElementsAre(Eq(1), Eq(2), Lt(13), Eq(4), Eq(5), Eq(6), Eq(7), + Eq(8), Eq(9), Eq(10), Gt(1), Eq(12))); +} + +// Tests the variadic version of the UnorderedElementsAreMatcher +TEST(ElementsAreTest, HugeMatcherStr) { + vector<string> test_vector{ + "literal_string", "", "", "", "", "", "", "", "", "", "", ""}; + + EXPECT_THAT(test_vector, UnorderedElementsAre("literal_string", _, _, _, _, _, + _, _, _, _, _, _)); +} + +// Tests the variadic version of the UnorderedElementsAreMatcher +TEST(ElementsAreTest, HugeMatcherUnordered) { + vector<int> test_vector{2, 1, 8, 5, 4, 6, 7, 3, 9, 12, 11, 10}; + + EXPECT_THAT(test_vector, UnorderedElementsAre( + Eq(2), Eq(1), Gt(7), Eq(5), Eq(4), Eq(6), Eq(7), + Eq(3), Eq(9), Eq(12), Eq(11), Ne(122))); } #endif // GTEST_LANG_CXX11 @@ -2315,28 +2790,22 @@ TEST(AnyOfTest, VariadicMatchesWhenAnyMatches) { TEST(AnyOfTest, CanDescribeSelf) { Matcher<int> m; m = AnyOf(Le(1), Ge(3)); + EXPECT_EQ("(is <= 1) or (is >= 3)", Describe(m)); m = AnyOf(Lt(0), Eq(1), Eq(2)); - EXPECT_EQ("(is < 0) or " - "((is equal to 1) or (is equal to 2))", - Describe(m)); + EXPECT_EQ("(is < 0) or (is equal to 1) or (is equal to 2)", Describe(m)); m = AnyOf(Lt(0), Eq(1), Eq(2), Eq(3)); - EXPECT_EQ("((is < 0) or " - "(is equal to 1)) or " - "((is equal to 2) or " - "(is equal to 3))", + EXPECT_EQ("(is < 0) or (is equal to 1) or (is equal to 2) or (is equal to 3)", Describe(m)); m = AnyOf(Le(0), Gt(10), 3, 5, 7); - EXPECT_EQ("((is <= 0) or " - "(is > 10)) or " - "((is equal to 3) or " - "((is equal to 5) or " - "(is equal to 7)))", - Describe(m)); + EXPECT_EQ( + "(is <= 0) or (is > 10) or (is equal to 3) or (is equal to 5) or (is " + "equal to 7)", + Describe(m)); } // Tests that AnyOf(m1, ..., mn) describes its negation properly. @@ -2347,24 +2816,20 @@ TEST(AnyOfTest, CanDescribeNegation) { DescribeNegation(m)); m = AnyOf(Lt(0), Eq(1), Eq(2)); - EXPECT_EQ("(isn't < 0) and " - "((isn't equal to 1) and (isn't equal to 2))", + EXPECT_EQ("(isn't < 0) and (isn't equal to 1) and (isn't equal to 2)", DescribeNegation(m)); m = AnyOf(Lt(0), Eq(1), Eq(2), Eq(3)); - EXPECT_EQ("((isn't < 0) and " - "(isn't equal to 1)) and " - "((isn't equal to 2) and " - "(isn't equal to 3))", - DescribeNegation(m)); + EXPECT_EQ( + "(isn't < 0) and (isn't equal to 1) and (isn't equal to 2) and (isn't " + "equal to 3)", + DescribeNegation(m)); m = AnyOf(Le(0), Gt(10), 3, 5, 7); - EXPECT_EQ("((isn't <= 0) and " - "(isn't > 10)) and " - "((isn't equal to 3) and " - "((isn't equal to 5) and " - "(isn't equal to 7)))", - DescribeNegation(m)); + EXPECT_EQ( + "(isn't <= 0) and (isn't > 10) and (isn't equal to 3) and (isn't equal " + "to 5) and (isn't equal to 7)", + DescribeNegation(m)); } // Tests that monomorphic matchers are safely cast by the AnyOf matcher. @@ -2583,9 +3048,25 @@ TEST(ExplainMatchResultTest, WorksInsideMATCHER) { EXPECT_THAT(0, Really(Eq(0))); } +TEST(DescribeMatcherTest, WorksWithValue) { + EXPECT_EQ("is equal to 42", DescribeMatcher<int>(42)); + EXPECT_EQ("isn't equal to 42", DescribeMatcher<int>(42, true)); +} + +TEST(DescribeMatcherTest, WorksWithMonomorphicMatcher) { + const Matcher<int> monomorphic = Le(0); + EXPECT_EQ("is <= 0", DescribeMatcher<int>(monomorphic)); + EXPECT_EQ("isn't <= 0", DescribeMatcher<int>(monomorphic, true)); +} + +TEST(DescribeMatcherTest, WorksWithPolymorphicMatcher) { + EXPECT_EQ("is even", DescribeMatcher<int>(PolymorphicIsEven())); + EXPECT_EQ("is odd", DescribeMatcher<int>(PolymorphicIsEven(), true)); +} + TEST(AllArgsTest, WorksForTuple) { - EXPECT_THAT(make_tuple(1, 2L), AllArgs(Lt())); - EXPECT_THAT(make_tuple(2L, 1), Not(AllArgs(Lt()))); + EXPECT_THAT(std::make_tuple(1, 2L), AllArgs(Lt())); + EXPECT_THAT(std::make_tuple(2L, 1), Not(AllArgs(Lt()))); } TEST(AllArgsTest, WorksForNonTuple) { @@ -2617,6 +3098,44 @@ TEST(AllArgsTest, WorksInWithClause) { EXPECT_EQ(2, helper.Helper('a', 1)); } +class OptionalMatchersHelper { + public: + OptionalMatchersHelper() {} + + MOCK_METHOD0(NoArgs, int()); + + MOCK_METHOD1(OneArg, int(int y)); + + MOCK_METHOD2(TwoArgs, int(char x, int y)); + + MOCK_METHOD1(Overloaded, int(char x)); + MOCK_METHOD2(Overloaded, int(char x, int y)); + + private: + GTEST_DISALLOW_COPY_AND_ASSIGN_(OptionalMatchersHelper); +}; + +TEST(AllArgsTest, WorksWithoutMatchers) { + OptionalMatchersHelper helper; + + ON_CALL(helper, NoArgs).WillByDefault(Return(10)); + ON_CALL(helper, OneArg).WillByDefault(Return(20)); + ON_CALL(helper, TwoArgs).WillByDefault(Return(30)); + + EXPECT_EQ(10, helper.NoArgs()); + EXPECT_EQ(20, helper.OneArg(1)); + EXPECT_EQ(30, helper.TwoArgs('\1', 2)); + + EXPECT_CALL(helper, NoArgs).Times(1); + EXPECT_CALL(helper, OneArg).WillOnce(Return(100)); + EXPECT_CALL(helper, OneArg(17)).WillOnce(Return(200)); + EXPECT_CALL(helper, TwoArgs).Times(0); + + EXPECT_EQ(10, helper.NoArgs()); + EXPECT_EQ(100, helper.OneArg(1)); + EXPECT_EQ(200, helper.OneArg(17)); +} + // Tests that ASSERT_THAT() and EXPECT_THAT() work when the value // matches the matcher. TEST(MatcherAssertionTest, WorksWhenMatcherIsSatisfied) { @@ -2685,9 +3204,9 @@ TEST(MatcherAssertionTest, WorksForMonomorphicMatcher) { Matcher<const char*> starts_with_he = StartsWith("he"); ASSERT_THAT("hello", starts_with_he); - Matcher<const string&> ends_with_ok = EndsWith("ok"); + Matcher<const std::string&> ends_with_ok = EndsWith("ok"); ASSERT_THAT("book", ends_with_ok); - const string bad = "bad"; + const std::string bad = "bad"; EXPECT_NONFATAL_FAILURE(EXPECT_THAT(bad, ends_with_ok), "Value of: bad\n" "Expected: ends with \"ok\"\n" @@ -2712,18 +3231,22 @@ class FloatingPointTest : public testing::Test { zero_bits_(Floating(0).bits()), one_bits_(Floating(1).bits()), infinity_bits_(Floating(Floating::Infinity()).bits()), - close_to_positive_zero_(AsBits(zero_bits_ + max_ulps_/2)), - close_to_negative_zero_(AsBits(zero_bits_ + max_ulps_ - max_ulps_/2)), - further_from_negative_zero_(-AsBits( + close_to_positive_zero_( + Floating::ReinterpretBits(zero_bits_ + max_ulps_/2)), + close_to_negative_zero_( + -Floating::ReinterpretBits(zero_bits_ + max_ulps_ - max_ulps_/2)), + further_from_negative_zero_(-Floating::ReinterpretBits( zero_bits_ + max_ulps_ + 1 - max_ulps_/2)), - close_to_one_(AsBits(one_bits_ + max_ulps_)), - further_from_one_(AsBits(one_bits_ + max_ulps_ + 1)), + close_to_one_(Floating::ReinterpretBits(one_bits_ + max_ulps_)), + further_from_one_(Floating::ReinterpretBits(one_bits_ + max_ulps_ + 1)), infinity_(Floating::Infinity()), - close_to_infinity_(AsBits(infinity_bits_ - max_ulps_)), - further_from_infinity_(AsBits(infinity_bits_ - max_ulps_ - 1)), + close_to_infinity_( + Floating::ReinterpretBits(infinity_bits_ - max_ulps_)), + further_from_infinity_( + Floating::ReinterpretBits(infinity_bits_ - max_ulps_ - 1)), max_(Floating::Max()), - nan1_(AsBits(Floating::kExponentBitMask | 1)), - nan2_(AsBits(Floating::kExponentBitMask | 200)) { + nan1_(Floating::ReinterpretBits(Floating::kExponentBitMask | 1)), + nan2_(Floating::ReinterpretBits(Floating::kExponentBitMask | 200)) { } void TestSize() { @@ -2778,7 +3301,7 @@ class FloatingPointTest : public testing::Test { // Pre-calculated numbers to be used by the tests. - const size_t max_ulps_; + const Bits max_ulps_; const Bits zero_bits_; // The bits that represent 0.0. const Bits one_bits_; // The bits that represent 1.0. @@ -2804,12 +3327,6 @@ class FloatingPointTest : public testing::Test { // Some NaNs. const RawType nan1_; const RawType nan2_; - - private: - template <typename T> - static RawType AsBits(T value) { - return Floating::ReinterpretBits(static_cast<Bits>(value)); - } }; // Tests floating-point matchers with fixed epsilons. @@ -3099,7 +3616,8 @@ TEST_F(DoubleNearTest, ExplainsResultWhenMatchFails) { EXPECT_EQ("which is 0.2 from 2", Explain(DoubleNear(2.0, 0.1), 2.2)); EXPECT_EQ("which is -0.3 from 2", Explain(DoubleNear(2.0, 0.1), 1.7)); - const string explanation = Explain(DoubleNear(2.1, 1e-10), 2.1 + 1.2e-10); + const std::string explanation = + Explain(DoubleNear(2.1, 1e-10), 2.1 + 1.2e-10); // Different C++ implementations may print floating-point numbers // slightly differently. EXPECT_TRUE(explanation == "which is 1.2e-10 from 2.1" || // GCC @@ -3146,7 +3664,7 @@ TEST(PointeeTest, RawPointer) { EXPECT_TRUE(m.Matches(&n)); n = -1; EXPECT_FALSE(m.Matches(&n)); - EXPECT_FALSE(m.Matches(NULL)); + EXPECT_FALSE(m.Matches(nullptr)); } TEST(PointeeTest, RawPointerToConst) { @@ -3156,7 +3674,7 @@ TEST(PointeeTest, RawPointerToConst) { EXPECT_TRUE(m.Matches(&x)); x = -1; EXPECT_FALSE(m.Matches(&x)); - EXPECT_FALSE(m.Matches(NULL)); + EXPECT_FALSE(m.Matches(nullptr)); } TEST(PointeeTest, ReferenceToConstRawPointer) { @@ -3166,7 +3684,7 @@ TEST(PointeeTest, ReferenceToConstRawPointer) { EXPECT_TRUE(m.Matches(&n)); n = -1; EXPECT_FALSE(m.Matches(&n)); - EXPECT_FALSE(m.Matches(NULL)); + EXPECT_FALSE(m.Matches(nullptr)); } TEST(PointeeTest, ReferenceToNonConstRawPointer) { @@ -3177,7 +3695,7 @@ TEST(PointeeTest, ReferenceToNonConstRawPointer) { EXPECT_TRUE(m.Matches(p)); x = -1; EXPECT_FALSE(m.Matches(p)); - p = NULL; + p = nullptr; EXPECT_FALSE(m.Matches(p)); } @@ -3186,7 +3704,6 @@ MATCHER_P(FieldIIs, inner_matcher, "") { } #if GTEST_HAS_RTTI - TEST(WhenDynamicCastToTest, SameType) { Derived derived; derived.i = 4; @@ -3217,7 +3734,7 @@ TEST(WhenDynamicCastToTest, WrongTypes) { TEST(WhenDynamicCastToTest, AlreadyNull) { // Already NULL. - Base* as_base_ptr = NULL; + Base* as_base_ptr = nullptr; EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<Derived*>(IsNull())); } @@ -3244,7 +3761,7 @@ TEST(WhenDynamicCastToTest, AmbiguousCast) { TEST(WhenDynamicCastToTest, Describe) { Matcher<Base*> matcher = WhenDynamicCastTo<Derived*>(Pointee(_)); - const string prefix = + const std::string prefix = "when dynamic_cast to " + internal::GetTypeName<Derived*>() + ", "; EXPECT_EQ(prefix + "points to a value that is anything", Describe(matcher)); EXPECT_EQ(prefix + "does not point to a value that is anything", @@ -3253,7 +3770,7 @@ TEST(WhenDynamicCastToTest, Describe) { TEST(WhenDynamicCastToTest, Explain) { Matcher<Base*> matcher = WhenDynamicCastTo<Derived*>(Pointee(_)); - Base* null = NULL; + Base* null = nullptr; EXPECT_THAT(Explain(matcher, null), HasSubstr("NULL")); Derived derived; EXPECT_TRUE(matcher.Matches(&derived)); @@ -3278,7 +3795,6 @@ TEST(WhenDynamicCastToTest, BadReference) { Base& as_base_ref = derived; EXPECT_THAT(as_base_ref, Not(WhenDynamicCastTo<const OtherDerived&>(_))); } - #endif // GTEST_HAS_RTTI // Minimal const-propagating pointer. @@ -3315,7 +3831,7 @@ TEST(PointeeTest, WorksWithConstPropagatingPointers) { TEST(PointeeTest, NeverMatchesNull) { const Matcher<const char*> m = Pointee(_); - EXPECT_FALSE(m.Matches(NULL)); + EXPECT_FALSE(m.Matches(nullptr)); } // Tests that we can write Pointee(value) instead of Pointee(Eq(value)). @@ -3326,7 +3842,7 @@ TEST(PointeeTest, MatchesAgainstAValue) { EXPECT_TRUE(m.Matches(&n)); n = -1; EXPECT_FALSE(m.Matches(&n)); - EXPECT_FALSE(m.Matches(NULL)); + EXPECT_FALSE(m.Matches(nullptr)); } TEST(PointeeTest, CanDescribeSelf) { @@ -3337,9 +3853,9 @@ TEST(PointeeTest, CanDescribeSelf) { } TEST(PointeeTest, CanExplainMatchResult) { - const Matcher<const string*> m = Pointee(StartsWith("Hi")); + const Matcher<const std::string*> m = Pointee(StartsWith("Hi")); - EXPECT_EQ("", Explain(m, static_cast<const string*>(NULL))); + EXPECT_EQ("", Explain(m, static_cast<const std::string*>(nullptr))); const Matcher<long*> m2 = Pointee(GreaterThan(1)); // NOLINT long n = 3; // NOLINT @@ -3376,7 +3892,7 @@ MATCHER_P(UncopyableIs, inner_matcher, "") { // A user-defined struct for testing Field(). struct AStruct { - AStruct() : x(0), y(1.0), z(5), p(NULL) {} + AStruct() : x(0), y(1.0), z(5), p(nullptr) {} AStruct(const AStruct& rhs) : x(rhs.x), y(rhs.y), z(rhs.z.value()), p(rhs.p) {} @@ -3400,11 +3916,14 @@ struct DerivedStruct : public AStruct { // Tests that Field(&Foo::field, ...) works when field is non-const. TEST(FieldTest, WorksForNonConstField) { Matcher<AStruct> m = Field(&AStruct::x, Ge(0)); + Matcher<AStruct> m_with_name = Field("x", &AStruct::x, Ge(0)); AStruct a; EXPECT_TRUE(m.Matches(a)); + EXPECT_TRUE(m_with_name.Matches(a)); a.x = -1; EXPECT_FALSE(m.Matches(a)); + EXPECT_FALSE(m_with_name.Matches(a)); } // Tests that Field(&Foo::field, ...) works when field is const. @@ -3412,9 +3931,13 @@ TEST(FieldTest, WorksForConstField) { AStruct a; Matcher<AStruct> m = Field(&AStruct::y, Ge(0.0)); + Matcher<AStruct> m_with_name = Field("y", &AStruct::y, Ge(0.0)); EXPECT_TRUE(m.Matches(a)); + EXPECT_TRUE(m_with_name.Matches(a)); m = Field(&AStruct::y, Le(0.0)); + m_with_name = Field("y", &AStruct::y, Le(0.0)); EXPECT_FALSE(m.Matches(a)); + EXPECT_FALSE(m_with_name.Matches(a)); } // Tests that Field(&Foo::field, ...) works when field is not copyable. @@ -3430,7 +3953,7 @@ TEST(FieldTest, WorksForUncopyableField) { // Tests that Field(&Foo::field, ...) works when field is a pointer. TEST(FieldTest, WorksForPointerField) { // Matching against NULL. - Matcher<AStruct> m = Field(&AStruct::p, static_cast<const char*>(NULL)); + Matcher<AStruct> m = Field(&AStruct::p, static_cast<const char*>(nullptr)); AStruct a; EXPECT_TRUE(m.Matches(a)); a.p = "hi"; @@ -3488,6 +4011,14 @@ TEST(FieldTest, CanDescribeSelf) { EXPECT_EQ("is an object whose given field isn't >= 0", DescribeNegation(m)); } +TEST(FieldTest, CanDescribeSelfWithFieldName) { + Matcher<const AStruct&> m = Field("field_name", &AStruct::x, Ge(0)); + + EXPECT_EQ("is an object whose field `field_name` is >= 0", Describe(m)); + EXPECT_EQ("is an object whose field `field_name` isn't >= 0", + DescribeNegation(m)); +} + // Tests that Field() can explain the match result. TEST(FieldTest, CanExplainMatchResult) { Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0)); @@ -3502,6 +4033,19 @@ TEST(FieldTest, CanExplainMatchResult) { Explain(m, a)); } +TEST(FieldTest, CanExplainMatchResultWithFieldName) { + Matcher<const AStruct&> m = Field("field_name", &AStruct::x, Ge(0)); + + AStruct a; + a.x = 1; + EXPECT_EQ("whose field `field_name` is 1" + OfType("int"), Explain(m, a)); + + m = Field("field_name", &AStruct::x, GreaterThan(0)); + EXPECT_EQ("whose field `field_name` is 1" + OfType("int") + + ", which is 1 more than 0", + Explain(m, a)); +} + // Tests that Field() works when the argument is a pointer to const. TEST(FieldForPointerTest, WorksForPointerToConst) { Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0)); @@ -3535,7 +4079,7 @@ TEST(FieldForPointerTest, WorksForReferenceToConstPointer) { // Tests that Field() does not match the NULL pointer. TEST(FieldForPointerTest, DoesNotMatchNull) { Matcher<const AStruct*> m = Field(&AStruct::x, _); - EXPECT_FALSE(m.Matches(NULL)); + EXPECT_FALSE(m.Matches(nullptr)); } // Tests that Field(&Foo::field, ...) works when the argument's type @@ -3559,13 +4103,21 @@ TEST(FieldForPointerTest, CanDescribeSelf) { EXPECT_EQ("is an object whose given field isn't >= 0", DescribeNegation(m)); } +TEST(FieldForPointerTest, CanDescribeSelfWithFieldName) { + Matcher<const AStruct*> m = Field("field_name", &AStruct::x, Ge(0)); + + EXPECT_EQ("is an object whose field `field_name` is >= 0", Describe(m)); + EXPECT_EQ("is an object whose field `field_name` isn't >= 0", + DescribeNegation(m)); +} + // Tests that Field() can explain the result of matching a pointer. TEST(FieldForPointerTest, CanExplainMatchResult) { Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0)); AStruct a; a.x = 1; - EXPECT_EQ("", Explain(m, static_cast<const AStruct*>(NULL))); + EXPECT_EQ("", Explain(m, static_cast<const AStruct*>(nullptr))); EXPECT_EQ("which points to an object whose given field is 1" + OfType("int"), Explain(m, &a)); @@ -3574,6 +4126,22 @@ TEST(FieldForPointerTest, CanExplainMatchResult) { ", which is 1 more than 0", Explain(m, &a)); } +TEST(FieldForPointerTest, CanExplainMatchResultWithFieldName) { + Matcher<const AStruct*> m = Field("field_name", &AStruct::x, Ge(0)); + + AStruct a; + a.x = 1; + EXPECT_EQ("", Explain(m, static_cast<const AStruct*>(nullptr))); + EXPECT_EQ( + "which points to an object whose field `field_name` is 1" + OfType("int"), + Explain(m, &a)); + + m = Field("field_name", &AStruct::x, GreaterThan(0)); + EXPECT_EQ("which points to an object whose field `field_name` is 1" + + OfType("int") + ", which is 1 more than 0", + Explain(m, &a)); +} + // A user-defined class for testing Property(). class AClass { public: @@ -3585,15 +4153,20 @@ class AClass { void set_n(int new_n) { n_ = new_n; } // A getter that returns a reference to const. - const string& s() const { return s_; } + const std::string& s() const { return s_; } + +#if GTEST_LANG_CXX11 + const std::string& s_ref() const & { return s_; } +#endif - void set_s(const string& new_s) { s_ = new_s; } + void set_s(const std::string& new_s) { s_ = new_s; } // A getter that returns a reference to non-const. double& x() const { return x_; } + private: int n_; - string s_; + std::string s_; static double x_; }; @@ -3612,27 +4185,53 @@ class DerivedClass : public AClass { // returns a non-reference. TEST(PropertyTest, WorksForNonReferenceProperty) { Matcher<const AClass&> m = Property(&AClass::n, Ge(0)); + Matcher<const AClass&> m_with_name = Property("n", &AClass::n, Ge(0)); AClass a; a.set_n(1); EXPECT_TRUE(m.Matches(a)); + EXPECT_TRUE(m_with_name.Matches(a)); a.set_n(-1); EXPECT_FALSE(m.Matches(a)); + EXPECT_FALSE(m_with_name.Matches(a)); } // Tests that Property(&Foo::property, ...) works when property() // returns a reference to const. TEST(PropertyTest, WorksForReferenceToConstProperty) { Matcher<const AClass&> m = Property(&AClass::s, StartsWith("hi")); + Matcher<const AClass&> m_with_name = + Property("s", &AClass::s, StartsWith("hi")); + + AClass a; + a.set_s("hill"); + EXPECT_TRUE(m.Matches(a)); + EXPECT_TRUE(m_with_name.Matches(a)); + + a.set_s("hole"); + EXPECT_FALSE(m.Matches(a)); + EXPECT_FALSE(m_with_name.Matches(a)); +} + +#if GTEST_LANG_CXX11 +// Tests that Property(&Foo::property, ...) works when property() is +// ref-qualified. +TEST(PropertyTest, WorksForRefQualifiedProperty) { + Matcher<const AClass&> m = Property(&AClass::s_ref, StartsWith("hi")); + Matcher<const AClass&> m_with_name = + Property("s", &AClass::s_ref, StartsWith("hi")); AClass a; a.set_s("hill"); EXPECT_TRUE(m.Matches(a)); + EXPECT_TRUE(m_with_name.Matches(a)); a.set_s("hole"); EXPECT_FALSE(m.Matches(a)); + EXPECT_FALSE(m_with_name.Matches(a)); } +#endif // Tests that Property(&Foo::property, ...) works when property() // returns a reference to non-const. @@ -3682,10 +4281,15 @@ TEST(PropertyTest, WorksForCompatibleMatcherType) { Matcher<const AClass&> m = Property(&AClass::n, Matcher<signed char>(Ge(0))); + Matcher<const AClass&> m_with_name = + Property("n", &AClass::n, Matcher<signed char>(Ge(0))); + AClass a; EXPECT_TRUE(m.Matches(a)); + EXPECT_TRUE(m_with_name.Matches(a)); a.set_n(-1); EXPECT_FALSE(m.Matches(a)); + EXPECT_FALSE(m_with_name.Matches(a)); } // Tests that Property() can describe itself. @@ -3697,6 +4301,14 @@ TEST(PropertyTest, CanDescribeSelf) { DescribeNegation(m)); } +TEST(PropertyTest, CanDescribeSelfWithPropertyName) { + Matcher<const AClass&> m = Property("fancy_name", &AClass::n, Ge(0)); + + EXPECT_EQ("is an object whose property `fancy_name` is >= 0", Describe(m)); + EXPECT_EQ("is an object whose property `fancy_name` isn't >= 0", + DescribeNegation(m)); +} + // Tests that Property() can explain the match result. TEST(PropertyTest, CanExplainMatchResult) { Matcher<const AClass&> m = Property(&AClass::n, Ge(0)); @@ -3711,6 +4323,19 @@ TEST(PropertyTest, CanExplainMatchResult) { Explain(m, a)); } +TEST(PropertyTest, CanExplainMatchResultWithPropertyName) { + Matcher<const AClass&> m = Property("fancy_name", &AClass::n, Ge(0)); + + AClass a; + a.set_n(1); + EXPECT_EQ("whose property `fancy_name` is 1" + OfType("int"), Explain(m, a)); + + m = Property("fancy_name", &AClass::n, GreaterThan(0)); + EXPECT_EQ("whose property `fancy_name` is 1" + OfType("int") + + ", which is 1 more than 0", + Explain(m, a)); +} + // Tests that Property() works when the argument is a pointer to const. TEST(PropertyForPointerTest, WorksForPointerToConst) { Matcher<const AClass*> m = Property(&AClass::n, Ge(0)); @@ -3751,7 +4376,7 @@ TEST(PropertyForPointerTest, WorksForReferenceToConstPointer) { // Tests that Property() does not match the NULL pointer. TEST(PropertyForPointerTest, WorksForReferenceToNonConstProperty) { Matcher<const AClass*> m = Property(&AClass::x, _); - EXPECT_FALSE(m.Matches(NULL)); + EXPECT_FALSE(m.Matches(nullptr)); } // Tests that Property(&Foo::property, ...) works when the argument's @@ -3778,13 +4403,21 @@ TEST(PropertyForPointerTest, CanDescribeSelf) { DescribeNegation(m)); } +TEST(PropertyForPointerTest, CanDescribeSelfWithPropertyDescription) { + Matcher<const AClass*> m = Property("fancy_name", &AClass::n, Ge(0)); + + EXPECT_EQ("is an object whose property `fancy_name` is >= 0", Describe(m)); + EXPECT_EQ("is an object whose property `fancy_name` isn't >= 0", + DescribeNegation(m)); +} + // Tests that Property() can explain the result of matching a pointer. TEST(PropertyForPointerTest, CanExplainMatchResult) { Matcher<const AClass*> m = Property(&AClass::n, Ge(0)); AClass a; a.set_n(1); - EXPECT_EQ("", Explain(m, static_cast<const AClass*>(NULL))); + EXPECT_EQ("", Explain(m, static_cast<const AClass*>(nullptr))); EXPECT_EQ( "which points to an object whose given property is 1" + OfType("int"), Explain(m, &a)); @@ -3795,14 +4428,32 @@ TEST(PropertyForPointerTest, CanExplainMatchResult) { Explain(m, &a)); } +TEST(PropertyForPointerTest, CanExplainMatchResultWithPropertyName) { + Matcher<const AClass*> m = Property("fancy_name", &AClass::n, Ge(0)); + + AClass a; + a.set_n(1); + EXPECT_EQ("", Explain(m, static_cast<const AClass*>(nullptr))); + EXPECT_EQ("which points to an object whose property `fancy_name` is 1" + + OfType("int"), + Explain(m, &a)); + + m = Property("fancy_name", &AClass::n, GreaterThan(0)); + EXPECT_EQ("which points to an object whose property `fancy_name` is 1" + + OfType("int") + ", which is 1 more than 0", + Explain(m, &a)); +} + // Tests ResultOf. // Tests that ResultOf(f, ...) compiles and works as expected when f is a // function pointer. -string IntToStringFunction(int input) { return input == 1 ? "foo" : "bar"; } +std::string IntToStringFunction(int input) { + return input == 1 ? "foo" : "bar"; +} TEST(ResultOfTest, WorksForFunctionPointers) { - Matcher<int> matcher = ResultOf(&IntToStringFunction, Eq(string("foo"))); + Matcher<int> matcher = ResultOf(&IntToStringFunction, Eq(std::string("foo"))); EXPECT_TRUE(matcher.Matches(1)); EXPECT_FALSE(matcher.Matches(2)); @@ -3868,12 +4519,12 @@ TEST(ResultOfTest, WorksForReferenceToNonConstResults) { // Tests that ResultOf(f, ...) compiles and works as expected when f(x) // returns a reference to const. -const string& StringFunction(const string& input) { return input; } +const std::string& StringFunction(const std::string& input) { return input; } TEST(ResultOfTest, WorksForReferenceToConstResults) { - string s = "foo"; - string s2 = s; - Matcher<const string&> matcher = ResultOf(&StringFunction, Ref(s)); + std::string s = "foo"; + std::string s2 = s; + Matcher<const std::string&> matcher = ResultOf(&StringFunction, Ref(s)); EXPECT_TRUE(matcher.Matches(s)); EXPECT_FALSE(matcher.Matches(s2)); @@ -3893,8 +4544,9 @@ TEST(ResultOfTest, WorksForCompatibleMatcherTypes) { // a NULL function pointer. TEST(ResultOfDeathTest, DiesOnNullFunctionPointers) { EXPECT_DEATH_IF_SUPPORTED( - ResultOf(static_cast<string(*)(int dummy)>(NULL), Eq(string("foo"))), - "NULL function pointer is passed into ResultOf\\(\\)\\."); + ResultOf(static_cast<std::string (*)(int dummy)>(nullptr), + Eq(std::string("foo"))), + "NULL function pointer is passed into ResultOf\\(\\)\\."); } // Tests that ResultOf(f, ...) compiles and works as expected when f is a @@ -3907,26 +4559,27 @@ TEST(ResultOfTest, WorksForFunctionReferences) { // Tests that ResultOf(f, ...) compiles and works as expected when f is a // function object. -struct Functor : public ::std::unary_function<int, string> { +struct Functor : public ::std::unary_function<int, std::string> { result_type operator()(argument_type input) const { return IntToStringFunction(input); } }; TEST(ResultOfTest, WorksForFunctors) { - Matcher<int> matcher = ResultOf(Functor(), Eq(string("foo"))); + Matcher<int> matcher = ResultOf(Functor(), Eq(std::string("foo"))); EXPECT_TRUE(matcher.Matches(1)); EXPECT_FALSE(matcher.Matches(2)); } // Tests that ResultOf(f, ...) compiles and works as expected when f is a -// functor with more then one operator() defined. ResultOf() must work +// functor with more than one operator() defined. ResultOf() must work // for each defined operator(). struct PolymorphicFunctor { typedef int result_type; int operator()(int n) { return n; } int operator()(const char* s) { return static_cast<int>(strlen(s)); } + std::string operator()(int *p) { return p ? "good ptr" : "null"; } }; TEST(ResultOfTest, WorksForPolymorphicFunctors) { @@ -3941,6 +4594,23 @@ TEST(ResultOfTest, WorksForPolymorphicFunctors) { EXPECT_FALSE(matcher_string.Matches("shrt")); } +#if GTEST_LANG_CXX11 +TEST(ResultOfTest, WorksForPolymorphicFunctorsIgnoringResultType) { + Matcher<int*> matcher = ResultOf(PolymorphicFunctor(), "good ptr"); + + int n = 0; + EXPECT_TRUE(matcher.Matches(&n)); + EXPECT_FALSE(matcher.Matches(nullptr)); +} + +TEST(ResultOfTest, WorksForLambdas) { + Matcher<int> matcher = + ResultOf([](int str_len) { return std::string(str_len, 'x'); }, "xxx"); + EXPECT_TRUE(matcher.Matches(3)); + EXPECT_FALSE(matcher.Matches(1)); +} +#endif + const int* ReferencingFunction(const int& n) { return &n; } struct ReferencingFunctor { @@ -4080,11 +4750,11 @@ TEST(IsEmptyTest, ImplementsIsEmpty) { } TEST(IsEmptyTest, WorksWithString) { - string text; + std::string text; EXPECT_THAT(text, IsEmpty()); text = "foo"; EXPECT_THAT(text, Not(IsEmpty())); - text = string("\0", 1); + text = std::string("\0", 1); EXPECT_THAT(text, Not(IsEmpty())); } @@ -4102,6 +4772,44 @@ TEST(IsEmptyTest, ExplainsResult) { EXPECT_EQ("whose size is 1", Explain(m, container)); } +TEST(IsTrueTest, IsTrueIsFalse) { + EXPECT_THAT(true, IsTrue()); + EXPECT_THAT(false, IsFalse()); + EXPECT_THAT(true, Not(IsFalse())); + EXPECT_THAT(false, Not(IsTrue())); + EXPECT_THAT(0, Not(IsTrue())); + EXPECT_THAT(0, IsFalse()); + EXPECT_THAT(NULL, Not(IsTrue())); + EXPECT_THAT(NULL, IsFalse()); + EXPECT_THAT(-1, IsTrue()); + EXPECT_THAT(-1, Not(IsFalse())); + EXPECT_THAT(1, IsTrue()); + EXPECT_THAT(1, Not(IsFalse())); + EXPECT_THAT(2, IsTrue()); + EXPECT_THAT(2, Not(IsFalse())); + int a = 42; + EXPECT_THAT(a, IsTrue()); + EXPECT_THAT(a, Not(IsFalse())); + EXPECT_THAT(&a, IsTrue()); + EXPECT_THAT(&a, Not(IsFalse())); + EXPECT_THAT(false, Not(IsTrue())); + EXPECT_THAT(true, Not(IsFalse())); +#if GTEST_LANG_CXX11 + EXPECT_THAT(std::true_type(), IsTrue()); + EXPECT_THAT(std::true_type(), Not(IsFalse())); + EXPECT_THAT(std::false_type(), IsFalse()); + EXPECT_THAT(std::false_type(), Not(IsTrue())); + EXPECT_THAT(nullptr, Not(IsTrue())); + EXPECT_THAT(nullptr, IsFalse()); + std::unique_ptr<int> null_unique; + std::unique_ptr<int> nonnull_unique(new int(0)); + EXPECT_THAT(null_unique, Not(IsTrue())); + EXPECT_THAT(null_unique, IsFalse()); + EXPECT_THAT(nonnull_unique, IsTrue()); + EXPECT_THAT(nonnull_unique, Not(IsFalse())); +#endif // GTEST_LANG_CXX11 +} + TEST(SizeIsTest, ImplementsSizeIs) { vector<int> container; EXPECT_THAT(container, SizeIs(0)); @@ -4115,7 +4823,7 @@ TEST(SizeIsTest, ImplementsSizeIs) { } TEST(SizeIsTest, WorksWithMap) { - map<string, int> container; + map<std::string, int> container; EXPECT_THAT(container, SizeIs(0)); EXPECT_THAT(container, Not(SizeIs(1))); container.insert(make_pair("foo", 1)); @@ -4235,7 +4943,7 @@ TYPED_TEST(ContainerEqTest, DuplicateDifference) { #endif // GTEST_HAS_TYPED_TEST // Tests that mutliple missing values are reported. -// Using just vector here, so order is predicatble. +// Using just vector here, so order is predictable. TEST(ContainerEqExtraTest, MultipleValuesMissing) { static const int vals[] = {1, 1, 2, 3, 5, 8}; static const int test_vals[] = {2, 1, 5}; @@ -4248,7 +4956,7 @@ TEST(ContainerEqExtraTest, MultipleValuesMissing) { } // Tests that added values are reported. -// Using just vector here, so order is predicatble. +// Using just vector here, so order is predictable. TEST(ContainerEqExtraTest, MultipleValuesAdded) { static const int vals[] = {1, 1, 2, 3, 5, 8}; static const int test_vals[] = {1, 2, 92, 3, 5, 8, 46}; @@ -4336,11 +5044,11 @@ TEST(ContainerEqExtraTest, WorksForNativeArrayAsTuple) { const int b[] = {1, 2, 3, 4}; const int* const p1 = a1; - EXPECT_THAT(make_tuple(p1, 3), ContainerEq(a2)); - EXPECT_THAT(make_tuple(p1, 3), Not(ContainerEq(b))); + EXPECT_THAT(std::make_tuple(p1, 3), ContainerEq(a2)); + EXPECT_THAT(std::make_tuple(p1, 3), Not(ContainerEq(b))); const int c[] = {1, 3, 2}; - EXPECT_THAT(make_tuple(p1, 3), Not(ContainerEq(c))); + EXPECT_THAT(std::make_tuple(p1, 3), Not(ContainerEq(c))); } TEST(ContainerEqExtraTest, CopiesNativeArrayParameter) { @@ -4380,13 +5088,13 @@ TEST(WhenSortedByTest, WorksForNonEmptyContainer) { } TEST(WhenSortedByTest, WorksForNonVectorContainer) { - list<string> words; + list<std::string> words; words.push_back("say"); words.push_back("hello"); words.push_back("world"); - EXPECT_THAT(words, WhenSortedBy(less<string>(), + EXPECT_THAT(words, WhenSortedBy(less<std::string>(), ElementsAre("hello", "say", "world"))); - EXPECT_THAT(words, Not(WhenSortedBy(less<string>(), + EXPECT_THAT(words, Not(WhenSortedBy(less<std::string>(), ElementsAre("say", "hello", "world")))); } @@ -4429,7 +5137,7 @@ TEST(WhenSortedTest, WorksForEmptyContainer) { } TEST(WhenSortedTest, WorksForNonEmptyContainer) { - list<string> words; + list<std::string> words; words.push_back("3"); words.push_back("1"); words.push_back("2"); @@ -4439,14 +5147,16 @@ TEST(WhenSortedTest, WorksForNonEmptyContainer) { } TEST(WhenSortedTest, WorksForMapTypes) { - map<string, int> word_counts; - word_counts["and"] = 1; - word_counts["the"] = 1; - word_counts["buffalo"] = 2; - EXPECT_THAT(word_counts, WhenSorted(ElementsAre( - Pair("and", 1), Pair("buffalo", 2), Pair("the", 1)))); - EXPECT_THAT(word_counts, Not(WhenSorted(ElementsAre( - Pair("and", 1), Pair("the", 1), Pair("buffalo", 2))))); + map<std::string, int> word_counts; + word_counts["and"] = 1; + word_counts["the"] = 1; + word_counts["buffalo"] = 2; + EXPECT_THAT(word_counts, + WhenSorted(ElementsAre(Pair("and", 1), Pair("buffalo", 2), + Pair("the", 1)))); + EXPECT_THAT(word_counts, + Not(WhenSorted(ElementsAre(Pair("and", 1), Pair("the", 1), + Pair("buffalo", 2))))); } TEST(WhenSortedTest, WorksForMultiMapTypes) { @@ -4654,6 +5364,250 @@ TEST(WhenSortedTest, WorksForVectorConstRefMatcherOnStreamlike) { EXPECT_THAT(s, Not(WhenSorted(ElementsAre(2, 1, 4, 5, 3)))); } +TEST(IsSupersetOfTest, WorksForNativeArray) { + const int subset[] = {1, 4}; + const int superset[] = {1, 2, 4}; + const int disjoint[] = {1, 0, 3}; + EXPECT_THAT(subset, IsSupersetOf(subset)); + EXPECT_THAT(subset, Not(IsSupersetOf(superset))); + EXPECT_THAT(superset, IsSupersetOf(subset)); + EXPECT_THAT(subset, Not(IsSupersetOf(disjoint))); + EXPECT_THAT(disjoint, Not(IsSupersetOf(subset))); +} + +TEST(IsSupersetOfTest, WorksWithDuplicates) { + const int not_enough[] = {1, 2}; + const int enough[] = {1, 1, 2}; + const int expected[] = {1, 1}; + EXPECT_THAT(not_enough, Not(IsSupersetOf(expected))); + EXPECT_THAT(enough, IsSupersetOf(expected)); +} + +TEST(IsSupersetOfTest, WorksForEmpty) { + vector<int> numbers; + vector<int> expected; + EXPECT_THAT(numbers, IsSupersetOf(expected)); + expected.push_back(1); + EXPECT_THAT(numbers, Not(IsSupersetOf(expected))); + expected.clear(); + numbers.push_back(1); + numbers.push_back(2); + EXPECT_THAT(numbers, IsSupersetOf(expected)); + expected.push_back(1); + EXPECT_THAT(numbers, IsSupersetOf(expected)); + expected.push_back(2); + EXPECT_THAT(numbers, IsSupersetOf(expected)); + expected.push_back(3); + EXPECT_THAT(numbers, Not(IsSupersetOf(expected))); +} + +TEST(IsSupersetOfTest, WorksForStreamlike) { + const int a[5] = {1, 2, 3, 4, 5}; + Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a)); + + vector<int> expected; + expected.push_back(1); + expected.push_back(2); + expected.push_back(5); + EXPECT_THAT(s, IsSupersetOf(expected)); + + expected.push_back(0); + EXPECT_THAT(s, Not(IsSupersetOf(expected))); +} + +TEST(IsSupersetOfTest, TakesStlContainer) { + const int actual[] = {3, 1, 2}; + + ::std::list<int> expected; + expected.push_back(1); + expected.push_back(3); + EXPECT_THAT(actual, IsSupersetOf(expected)); + + expected.push_back(4); + EXPECT_THAT(actual, Not(IsSupersetOf(expected))); +} + +TEST(IsSupersetOfTest, Describe) { + typedef std::vector<int> IntVec; + IntVec expected; + expected.push_back(111); + expected.push_back(222); + expected.push_back(333); + EXPECT_THAT( + Describe<IntVec>(IsSupersetOf(expected)), + Eq("a surjection from elements to requirements exists such that:\n" + " - an element is equal to 111\n" + " - an element is equal to 222\n" + " - an element is equal to 333")); +} + +TEST(IsSupersetOfTest, DescribeNegation) { + typedef std::vector<int> IntVec; + IntVec expected; + expected.push_back(111); + expected.push_back(222); + expected.push_back(333); + EXPECT_THAT( + DescribeNegation<IntVec>(IsSupersetOf(expected)), + Eq("no surjection from elements to requirements exists such that:\n" + " - an element is equal to 111\n" + " - an element is equal to 222\n" + " - an element is equal to 333")); +} + +TEST(IsSupersetOfTest, MatchAndExplain) { + std::vector<int> v; + v.push_back(2); + v.push_back(3); + std::vector<int> expected; + expected.push_back(1); + expected.push_back(2); + StringMatchResultListener listener; + ASSERT_FALSE(ExplainMatchResult(IsSupersetOf(expected), v, &listener)) + << listener.str(); + EXPECT_THAT(listener.str(), + Eq("where the following matchers don't match any elements:\n" + "matcher #0: is equal to 1")); + + v.push_back(1); + listener.Clear(); + ASSERT_TRUE(ExplainMatchResult(IsSupersetOf(expected), v, &listener)) + << listener.str(); + EXPECT_THAT(listener.str(), Eq("where:\n" + " - element #0 is matched by matcher #1,\n" + " - element #2 is matched by matcher #0")); +} + +#if GTEST_HAS_STD_INITIALIZER_LIST_ +TEST(IsSupersetOfTest, WorksForRhsInitializerList) { + const int numbers[] = {1, 3, 6, 2, 4, 5}; + EXPECT_THAT(numbers, IsSupersetOf({1, 2})); + EXPECT_THAT(numbers, Not(IsSupersetOf({3, 0}))); +} +#endif + +TEST(IsSubsetOfTest, WorksForNativeArray) { + const int subset[] = {1, 4}; + const int superset[] = {1, 2, 4}; + const int disjoint[] = {1, 0, 3}; + EXPECT_THAT(subset, IsSubsetOf(subset)); + EXPECT_THAT(subset, IsSubsetOf(superset)); + EXPECT_THAT(superset, Not(IsSubsetOf(subset))); + EXPECT_THAT(subset, Not(IsSubsetOf(disjoint))); + EXPECT_THAT(disjoint, Not(IsSubsetOf(subset))); +} + +TEST(IsSubsetOfTest, WorksWithDuplicates) { + const int not_enough[] = {1, 2}; + const int enough[] = {1, 1, 2}; + const int actual[] = {1, 1}; + EXPECT_THAT(actual, Not(IsSubsetOf(not_enough))); + EXPECT_THAT(actual, IsSubsetOf(enough)); +} + +TEST(IsSubsetOfTest, WorksForEmpty) { + vector<int> numbers; + vector<int> expected; + EXPECT_THAT(numbers, IsSubsetOf(expected)); + expected.push_back(1); + EXPECT_THAT(numbers, IsSubsetOf(expected)); + expected.clear(); + numbers.push_back(1); + numbers.push_back(2); + EXPECT_THAT(numbers, Not(IsSubsetOf(expected))); + expected.push_back(1); + EXPECT_THAT(numbers, Not(IsSubsetOf(expected))); + expected.push_back(2); + EXPECT_THAT(numbers, IsSubsetOf(expected)); + expected.push_back(3); + EXPECT_THAT(numbers, IsSubsetOf(expected)); +} + +TEST(IsSubsetOfTest, WorksForStreamlike) { + const int a[5] = {1, 2}; + Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a)); + + vector<int> expected; + expected.push_back(1); + EXPECT_THAT(s, Not(IsSubsetOf(expected))); + expected.push_back(2); + expected.push_back(5); + EXPECT_THAT(s, IsSubsetOf(expected)); +} + +TEST(IsSubsetOfTest, TakesStlContainer) { + const int actual[] = {3, 1, 2}; + + ::std::list<int> expected; + expected.push_back(1); + expected.push_back(3); + EXPECT_THAT(actual, Not(IsSubsetOf(expected))); + + expected.push_back(2); + expected.push_back(4); + EXPECT_THAT(actual, IsSubsetOf(expected)); +} + +TEST(IsSubsetOfTest, Describe) { + typedef std::vector<int> IntVec; + IntVec expected; + expected.push_back(111); + expected.push_back(222); + expected.push_back(333); + + EXPECT_THAT( + Describe<IntVec>(IsSubsetOf(expected)), + Eq("an injection from elements to requirements exists such that:\n" + " - an element is equal to 111\n" + " - an element is equal to 222\n" + " - an element is equal to 333")); +} + +TEST(IsSubsetOfTest, DescribeNegation) { + typedef std::vector<int> IntVec; + IntVec expected; + expected.push_back(111); + expected.push_back(222); + expected.push_back(333); + EXPECT_THAT( + DescribeNegation<IntVec>(IsSubsetOf(expected)), + Eq("no injection from elements to requirements exists such that:\n" + " - an element is equal to 111\n" + " - an element is equal to 222\n" + " - an element is equal to 333")); +} + +TEST(IsSubsetOfTest, MatchAndExplain) { + std::vector<int> v; + v.push_back(2); + v.push_back(3); + std::vector<int> expected; + expected.push_back(1); + expected.push_back(2); + StringMatchResultListener listener; + ASSERT_FALSE(ExplainMatchResult(IsSubsetOf(expected), v, &listener)) + << listener.str(); + EXPECT_THAT(listener.str(), + Eq("where the following elements don't match any matchers:\n" + "element #1: 3")); + + expected.push_back(3); + listener.Clear(); + ASSERT_TRUE(ExplainMatchResult(IsSubsetOf(expected), v, &listener)) + << listener.str(); + EXPECT_THAT(listener.str(), Eq("where:\n" + " - element #0 is matched by matcher #1,\n" + " - element #1 is matched by matcher #2")); +} + +#if GTEST_HAS_STD_INITIALIZER_LIST_ +TEST(IsSubsetOfTest, WorksForRhsInitializerList) { + const int numbers[] = {1, 2, 3}; + EXPECT_THAT(numbers, IsSubsetOf({1, 2, 3, 4})); + EXPECT_THAT(numbers, Not(IsSubsetOf({1, 2}))); +} +#endif + // Tests using ElementsAre() and ElementsAreArray() with stream-like // "containers". @@ -4763,7 +5717,7 @@ TEST(UnorderedElementsAreArrayTest, TakesInitializerList) { } TEST(UnorderedElementsAreArrayTest, TakesInitializerListOfCStrings) { - const string a[5] = {"a", "b", "c", "d", "e"}; + const std::string a[5] = {"a", "b", "c", "d", "e"}; EXPECT_THAT(a, UnorderedElementsAreArray({"a", "b", "c", "d", "e"})); EXPECT_THAT(a, Not(UnorderedElementsAreArray({"a", "b", "c", "d", "ef"}))); } @@ -4937,7 +5891,7 @@ TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedMatcherAndElement) { } // Test helper for formatting element, matcher index pairs in expectations. -static string EMString(int element, int matcher) { +static std::string EMString(int element, int matcher) { stringstream ss; ss << "(element #" << element << ", matcher #" << matcher << ")"; return ss.str(); @@ -4946,7 +5900,7 @@ static string EMString(int element, int matcher) { TEST_F(UnorderedElementsAreTest, FailMessageImperfectMatchOnly) { // A situation where all elements and matchers have a match // associated with them, but the max matching is not perfect. - std::vector<string> v; + std::vector<std::string> v; v.push_back("a"); v.push_back("b"); v.push_back("c"); @@ -4955,7 +5909,7 @@ TEST_F(UnorderedElementsAreTest, FailMessageImperfectMatchOnly) { UnorderedElementsAre("a", "a", AnyOf("b", "c")), v, &listener)) << listener.str(); - string prefix = + std::string prefix = "where no permutation of the elements can satisfy all matchers, " "and the closest match is 2 of 3 matchers with the " "pairings:\n"; @@ -5190,7 +6144,7 @@ TEST_P(BipartiteRandomTest, LargerNets) { testing::internal::Int32 seed = GTEST_FLAG(random_seed); if (seed == 0) { - seed = static_cast<testing::internal::Int32>(time(NULL)); + seed = static_cast<testing::internal::Int32>(time(nullptr)); } for (; iters > 0; --iters, ++seed) { @@ -5238,28 +6192,6 @@ TEST(IsReadableTypeNameTest, ReturnsFalseForLongFunctionTypeNames) { EXPECT_FALSE(IsReadableTypeName("void (&)(int, bool, char, float)")); } -// Tests JoinAsTuple(). - -TEST(JoinAsTupleTest, JoinsEmptyTuple) { - EXPECT_EQ("", JoinAsTuple(Strings())); -} - -TEST(JoinAsTupleTest, JoinsOneTuple) { - const char* fields[] = {"1"}; - EXPECT_EQ("1", JoinAsTuple(Strings(fields, fields + 1))); -} - -TEST(JoinAsTupleTest, JoinsTwoTuple) { - const char* fields[] = {"1", "a"}; - EXPECT_EQ("(1, a)", JoinAsTuple(Strings(fields, fields + 2))); -} - -TEST(JoinAsTupleTest, JoinsTenTuple) { - const char* fields[] = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10"}; - EXPECT_EQ("(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)", - JoinAsTuple(Strings(fields, fields + 10))); -} - // Tests FormatMatcherDescription(). TEST(FormatMatcherDescriptionTest, WorksForEmptyDescription) { @@ -5298,13 +6230,15 @@ TEST(PolymorphicMatcherTest, CanAccessImpl) { TEST(MatcherTupleTest, ExplainsMatchFailure) { stringstream ss1; - ExplainMatchFailureTupleTo(make_tuple(Matcher<char>(Eq('a')), GreaterThan(5)), - make_tuple('a', 10), &ss1); + ExplainMatchFailureTupleTo( + std::make_tuple(Matcher<char>(Eq('a')), GreaterThan(5)), + std::make_tuple('a', 10), &ss1); EXPECT_EQ("", ss1.str()); // Successful match. stringstream ss2; - ExplainMatchFailureTupleTo(make_tuple(GreaterThan(5), Matcher<char>(Eq('a'))), - make_tuple(2, 'b'), &ss2); + ExplainMatchFailureTupleTo( + std::make_tuple(GreaterThan(5), Matcher<char>(Eq('a'))), + std::make_tuple(2, 'b'), &ss2); EXPECT_EQ(" Expected arg #0: is > 5\n" " Actual: 2, which is 3 less than 5\n" " Expected arg #1: is equal to 'a' (97, 0x61)\n" @@ -5312,8 +6246,9 @@ TEST(MatcherTupleTest, ExplainsMatchFailure) { ss2.str()); // Failed match where both arguments need explanation. stringstream ss3; - ExplainMatchFailureTupleTo(make_tuple(GreaterThan(5), Matcher<char>(Eq('a'))), - make_tuple(2, 'a'), &ss3); + ExplainMatchFailureTupleTo( + std::make_tuple(GreaterThan(5), Matcher<char>(Eq('a'))), + std::make_tuple(2, 'a'), &ss3); EXPECT_EQ(" Expected arg #0: is > 5\n" " Actual: 2, which is 3 less than 5\n", ss3.str()); // Failed match where only one argument needs @@ -5366,13 +6301,13 @@ TEST(EachTest, MatchesVectorWhenAllElementsMatch) { EXPECT_THAT(some_vector, Not(Each(3))); EXPECT_THAT(some_vector, Each(Lt(3.5))); - vector<string> another_vector; + vector<std::string> another_vector; another_vector.push_back("fee"); - EXPECT_THAT(another_vector, Each(string("fee"))); + EXPECT_THAT(another_vector, Each(std::string("fee"))); another_vector.push_back("fie"); another_vector.push_back("foe"); another_vector.push_back("fum"); - EXPECT_THAT(another_vector, Not(Each(string("fee")))); + EXPECT_THAT(another_vector, Not(Each(std::string("fee")))); } TEST(EachTest, MatchesMapWhenAllElementsMatch) { @@ -5381,15 +6316,15 @@ TEST(EachTest, MatchesMapWhenAllElementsMatch) { my_map[bar] = 2; EXPECT_THAT(my_map, Each(make_pair(bar, 2))); - map<string, int> another_map; - EXPECT_THAT(another_map, Each(make_pair(string("fee"), 1))); + map<std::string, int> another_map; + EXPECT_THAT(another_map, Each(make_pair(std::string("fee"), 1))); another_map["fee"] = 1; - EXPECT_THAT(another_map, Each(make_pair(string("fee"), 1))); + EXPECT_THAT(another_map, Each(make_pair(std::string("fee"), 1))); another_map["fie"] = 2; another_map["foe"] = 3; another_map["fum"] = 4; - EXPECT_THAT(another_map, Not(Each(make_pair(string("fee"), 1)))); - EXPECT_THAT(another_map, Not(Each(make_pair(string("fum"), 1)))); + EXPECT_THAT(another_map, Not(Each(make_pair(std::string("fee"), 1)))); + EXPECT_THAT(another_map, Not(Each(make_pair(std::string("fum"), 1)))); EXPECT_THAT(another_map, Each(Pair(_, Gt(0)))); } @@ -5402,21 +6337,21 @@ TEST(EachTest, AcceptsMatcher) { TEST(EachTest, WorksForNativeArrayAsTuple) { const int a[] = {1, 2}; const int* const pointer = a; - EXPECT_THAT(make_tuple(pointer, 2), Each(Gt(0))); - EXPECT_THAT(make_tuple(pointer, 2), Not(Each(Gt(1)))); + EXPECT_THAT(std::make_tuple(pointer, 2), Each(Gt(0))); + EXPECT_THAT(std::make_tuple(pointer, 2), Not(Each(Gt(1)))); } // For testing Pointwise(). class IsHalfOfMatcher { public: template <typename T1, typename T2> - bool MatchAndExplain(const tuple<T1, T2>& a_pair, + bool MatchAndExplain(const std::tuple<T1, T2>& a_pair, MatchResultListener* listener) const { - if (get<0>(a_pair) == get<1>(a_pair)/2) { - *listener << "where the second is " << get<1>(a_pair); + if (std::get<0>(a_pair) == std::get<1>(a_pair) / 2) { + *listener << "where the second is " << std::get<1>(a_pair); return true; } else { - *listener << "where the second/2 is " << get<1>(a_pair)/2; + *listener << "where the second/2 is " << std::get<1>(a_pair) / 2; return false; } } @@ -5483,6 +6418,16 @@ TEST(PointwiseTest, WorksForRhsNativeArray) { EXPECT_THAT(lhs, Not(Pointwise(Lt(), rhs))); } +// Test is effective only with sanitizers. +TEST(PointwiseTest, WorksForVectorOfBool) { + vector<bool> rhs(3, false); + rhs[1] = true; + vector<bool> lhs = rhs; + EXPECT_THAT(lhs, Pointwise(Eq(), rhs)); + rhs[0] = true; + EXPECT_THAT(lhs, Not(Pointwise(Eq(), rhs))); +} + #if GTEST_HAS_STD_INITIALIZER_LIST_ TEST(PointwiseTest, WorksForRhsInitializerList) { @@ -5523,13 +6468,13 @@ TEST(PointwiseTest, AcceptsCorrectContent) { TEST(PointwiseTest, AllowsMonomorphicInnerMatcher) { const double lhs[3] = {1, 2, 3}; const int rhs[3] = {2, 4, 6}; - const Matcher<tuple<const double&, const int&> > m1 = IsHalfOf(); + const Matcher<std::tuple<const double&, const int&>> m1 = IsHalfOf(); EXPECT_THAT(lhs, Pointwise(m1, rhs)); EXPECT_EQ("", Explain(Pointwise(m1, rhs), lhs)); - // This type works as a tuple<const double&, const int&> can be - // implicitly cast to tuple<double, int>. - const Matcher<tuple<double, int> > m2 = IsHalfOf(); + // This type works as a std::tuple<const double&, const int&> can be + // implicitly cast to std::tuple<double, int>. + const Matcher<std::tuple<double, int>> m2 = IsHalfOf(); EXPECT_THAT(lhs, Pointwise(m2, rhs)); EXPECT_EQ("", Explain(Pointwise(m2, rhs), lhs)); } @@ -5639,14 +6584,207 @@ TEST(UnorderedPointwiseTest, AcceptsCorrectContentInDifferentOrder) { TEST(UnorderedPointwiseTest, AllowsMonomorphicInnerMatcher) { const double lhs[3] = {1, 2, 3}; const int rhs[3] = {4, 6, 2}; - const Matcher<tuple<const double&, const int&> > m1 = IsHalfOf(); + const Matcher<std::tuple<const double&, const int&>> m1 = IsHalfOf(); EXPECT_THAT(lhs, UnorderedPointwise(m1, rhs)); - // This type works as a tuple<const double&, const int&> can be - // implicitly cast to tuple<double, int>. - const Matcher<tuple<double, int> > m2 = IsHalfOf(); + // This type works as a std::tuple<const double&, const int&> can be + // implicitly cast to std::tuple<double, int>. + const Matcher<std::tuple<double, int>> m2 = IsHalfOf(); EXPECT_THAT(lhs, UnorderedPointwise(m2, rhs)); } +// Sample optional type implementation with minimal requirements for use with +// Optional matcher. +class SampleOptionalInt { + public: + typedef int value_type; + explicit SampleOptionalInt(int value) : value_(value), has_value_(true) {} + SampleOptionalInt() : value_(0), has_value_(false) {} + operator bool() const { + return has_value_; + } + const int& operator*() const { + return value_; + } + private: + int value_; + bool has_value_; +}; + +TEST(OptionalTest, DescribesSelf) { + const Matcher<SampleOptionalInt> m = Optional(Eq(1)); + EXPECT_EQ("value is equal to 1", Describe(m)); +} + +TEST(OptionalTest, ExplainsSelf) { + const Matcher<SampleOptionalInt> m = Optional(Eq(1)); + EXPECT_EQ("whose value 1 matches", Explain(m, SampleOptionalInt(1))); + EXPECT_EQ("whose value 2 doesn't match", Explain(m, SampleOptionalInt(2))); +} + +TEST(OptionalTest, MatchesNonEmptyOptional) { + const Matcher<SampleOptionalInt> m1 = Optional(1); + const Matcher<SampleOptionalInt> m2 = Optional(Eq(2)); + const Matcher<SampleOptionalInt> m3 = Optional(Lt(3)); + SampleOptionalInt opt(1); + EXPECT_TRUE(m1.Matches(opt)); + EXPECT_FALSE(m2.Matches(opt)); + EXPECT_TRUE(m3.Matches(opt)); +} + +TEST(OptionalTest, DoesNotMatchNullopt) { + const Matcher<SampleOptionalInt> m = Optional(1); + SampleOptionalInt empty; + EXPECT_FALSE(m.Matches(empty)); +} + +class SampleVariantIntString { + public: + SampleVariantIntString(int i) : i_(i), has_int_(true) {} + SampleVariantIntString(const std::string& s) : s_(s), has_int_(false) {} + + template <typename T> + friend bool holds_alternative(const SampleVariantIntString& value) { + return value.has_int_ == internal::IsSame<T, int>::value; + } + + template <typename T> + friend const T& get(const SampleVariantIntString& value) { + return value.get_impl(static_cast<T*>(nullptr)); + } + + private: + const int& get_impl(int*) const { return i_; } + const std::string& get_impl(std::string*) const { return s_; } + + int i_; + std::string s_; + bool has_int_; +}; + +TEST(VariantTest, DescribesSelf) { + const Matcher<SampleVariantIntString> m = VariantWith<int>(Eq(1)); + EXPECT_THAT(Describe(m), ContainsRegex("is a variant<> with value of type " + "'.*' and the value is equal to 1")); +} + +TEST(VariantTest, ExplainsSelf) { + const Matcher<SampleVariantIntString> m = VariantWith<int>(Eq(1)); + EXPECT_THAT(Explain(m, SampleVariantIntString(1)), + ContainsRegex("whose value 1")); + EXPECT_THAT(Explain(m, SampleVariantIntString("A")), + HasSubstr("whose value is not of type '")); + EXPECT_THAT(Explain(m, SampleVariantIntString(2)), + "whose value 2 doesn't match"); +} + +TEST(VariantTest, FullMatch) { + Matcher<SampleVariantIntString> m = VariantWith<int>(Eq(1)); + EXPECT_TRUE(m.Matches(SampleVariantIntString(1))); + + m = VariantWith<std::string>(Eq("1")); + EXPECT_TRUE(m.Matches(SampleVariantIntString("1"))); +} + +TEST(VariantTest, TypeDoesNotMatch) { + Matcher<SampleVariantIntString> m = VariantWith<int>(Eq(1)); + EXPECT_FALSE(m.Matches(SampleVariantIntString("1"))); + + m = VariantWith<std::string>(Eq("1")); + EXPECT_FALSE(m.Matches(SampleVariantIntString(1))); +} + +TEST(VariantTest, InnerDoesNotMatch) { + Matcher<SampleVariantIntString> m = VariantWith<int>(Eq(1)); + EXPECT_FALSE(m.Matches(SampleVariantIntString(2))); + + m = VariantWith<std::string>(Eq("1")); + EXPECT_FALSE(m.Matches(SampleVariantIntString("2"))); +} + +class SampleAnyType { + public: + explicit SampleAnyType(int i) : index_(0), i_(i) {} + explicit SampleAnyType(const std::string& s) : index_(1), s_(s) {} + + template <typename T> + friend const T* any_cast(const SampleAnyType* any) { + return any->get_impl(static_cast<T*>(nullptr)); + } + + private: + int index_; + int i_; + std::string s_; + + const int* get_impl(int*) const { return index_ == 0 ? &i_ : nullptr; } + const std::string* get_impl(std::string*) const { + return index_ == 1 ? &s_ : nullptr; + } +}; + +TEST(AnyWithTest, FullMatch) { + Matcher<SampleAnyType> m = AnyWith<int>(Eq(1)); + EXPECT_TRUE(m.Matches(SampleAnyType(1))); +} + +TEST(AnyWithTest, TestBadCastType) { + Matcher<SampleAnyType> m = AnyWith<std::string>(Eq("fail")); + EXPECT_FALSE(m.Matches(SampleAnyType(1))); +} + +#if GTEST_LANG_CXX11 +TEST(AnyWithTest, TestUseInContainers) { + std::vector<SampleAnyType> a; + a.emplace_back(1); + a.emplace_back(2); + a.emplace_back(3); + EXPECT_THAT( + a, ElementsAreArray({AnyWith<int>(1), AnyWith<int>(2), AnyWith<int>(3)})); + + std::vector<SampleAnyType> b; + b.emplace_back("hello"); + b.emplace_back("merhaba"); + b.emplace_back("salut"); + EXPECT_THAT(b, ElementsAreArray({AnyWith<std::string>("hello"), + AnyWith<std::string>("merhaba"), + AnyWith<std::string>("salut")})); +} +#endif // GTEST_LANG_CXX11 +TEST(AnyWithTest, TestCompare) { + EXPECT_THAT(SampleAnyType(1), AnyWith<int>(Gt(0))); +} + +TEST(AnyWithTest, DescribesSelf) { + const Matcher<const SampleAnyType&> m = AnyWith<int>(Eq(1)); + EXPECT_THAT(Describe(m), ContainsRegex("is an 'any' type with value of type " + "'.*' and the value is equal to 1")); +} + +TEST(AnyWithTest, ExplainsSelf) { + const Matcher<const SampleAnyType&> m = AnyWith<int>(Eq(1)); + + EXPECT_THAT(Explain(m, SampleAnyType(1)), ContainsRegex("whose value 1")); + EXPECT_THAT(Explain(m, SampleAnyType("A")), + HasSubstr("whose value is not of type '")); + EXPECT_THAT(Explain(m, SampleAnyType(2)), "whose value 2 doesn't match"); +} + +#if GTEST_LANG_CXX11 + +TEST(PointeeTest, WorksOnMoveOnlyType) { + std::unique_ptr<int> p(new int(3)); + EXPECT_THAT(p, Pointee(Eq(3))); + EXPECT_THAT(p, Not(Pointee(Eq(2)))); +} + +TEST(NotTest, WorksOnMoveOnlyType) { + std::unique_ptr<int> p(new int(3)); + EXPECT_THAT(p, Pointee(Eq(3))); + EXPECT_THAT(p, Not(Pointee(Eq(2)))); +} + +#endif // GTEST_LANG_CXX11 + } // namespace gmock_matchers_test } // namespace testing diff --git a/googlemock/test/gmock-more-actions_test.cc b/googlemock/test/gmock-more-actions_test.cc index 77e15bd..521f305 100644 --- a/googlemock/test/gmock-more-actions_test.cc +++ b/googlemock/test/gmock-more-actions_test.cc @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // Google Mock - a framework for writing C++ mock classes. // @@ -47,10 +46,6 @@ namespace gmock_more_actions_test { using ::std::plus; using ::std::string; -using testing::get; -using testing::make_tuple; -using testing::tuple; -using testing::tuple_element; using testing::_; using testing::Action; using testing::ActionInterface; @@ -94,12 +89,12 @@ const char* Plus1(const char* s) { return s + 1; } void VoidUnary(int /* n */) { g_done = true; } -bool ByConstRef(const string& s) { return s == "Hi"; } +bool ByConstRef(const std::string& s) { return s == "Hi"; } const double g_double = 0; bool ReferencesGlobalDouble(const double& x) { return &x == &g_double; } -string ByNonConstRef(string& s) { return s += "+"; } // NOLINT +std::string ByNonConstRef(std::string& s) { return s += "+"; } // NOLINT struct UnaryFunctor { int operator()(bool x) { return x ? 1 : -1; } @@ -119,9 +114,9 @@ int SumOfFirst2(int a, int b, Unused, Unused) { return a + b; } void VoidFunctionWithFourArguments(char, int, float, double) { g_done = true; } -string Concat4(const char* s1, const char* s2, const char* s3, - const char* s4) { - return string(s1) + s2 + s3 + s4; +std::string Concat4(const char* s1, const char* s2, const char* s3, + const char* s4) { + return std::string(s1) + s2 + s3 + s4; } int SumOf5(int a, int b, int c, int d, int e) { return a + b + c + d + e; } @@ -132,9 +127,9 @@ struct SumOf5Functor { } }; -string Concat5(const char* s1, const char* s2, const char* s3, - const char* s4, const char* s5) { - return string(s1) + s2 + s3 + s4 + s5; +std::string Concat5(const char* s1, const char* s2, const char* s3, + const char* s4, const char* s5) { + return std::string(s1) + s2 + s3 + s4 + s5; } int SumOf6(int a, int b, int c, int d, int e, int f) { @@ -147,34 +142,34 @@ struct SumOf6Functor { } }; -string Concat6(const char* s1, const char* s2, const char* s3, - const char* s4, const char* s5, const char* s6) { - return string(s1) + s2 + s3 + s4 + s5 + s6; +std::string Concat6(const char* s1, const char* s2, const char* s3, + const char* s4, const char* s5, const char* s6) { + return std::string(s1) + s2 + s3 + s4 + s5 + s6; } -string Concat7(const char* s1, const char* s2, const char* s3, - const char* s4, const char* s5, const char* s6, - const char* s7) { - return string(s1) + s2 + s3 + s4 + s5 + s6 + s7; +std::string Concat7(const char* s1, const char* s2, const char* s3, + const char* s4, const char* s5, const char* s6, + const char* s7) { + return std::string(s1) + s2 + s3 + s4 + s5 + s6 + s7; } -string Concat8(const char* s1, const char* s2, const char* s3, - const char* s4, const char* s5, const char* s6, - const char* s7, const char* s8) { - return string(s1) + s2 + s3 + s4 + s5 + s6 + s7 + s8; +std::string Concat8(const char* s1, const char* s2, const char* s3, + const char* s4, const char* s5, const char* s6, + const char* s7, const char* s8) { + return std::string(s1) + s2 + s3 + s4 + s5 + s6 + s7 + s8; } -string Concat9(const char* s1, const char* s2, const char* s3, - const char* s4, const char* s5, const char* s6, - const char* s7, const char* s8, const char* s9) { - return string(s1) + s2 + s3 + s4 + s5 + s6 + s7 + s8 + s9; +std::string Concat9(const char* s1, const char* s2, const char* s3, + const char* s4, const char* s5, const char* s6, + const char* s7, const char* s8, const char* s9) { + return std::string(s1) + s2 + s3 + s4 + s5 + s6 + s7 + s8 + s9; } -string Concat10(const char* s1, const char* s2, const char* s3, - const char* s4, const char* s5, const char* s6, - const char* s7, const char* s8, const char* s9, - const char* s10) { - return string(s1) + s2 + s3 + s4 + s5 + s6 + s7 + s8 + s9 + s10; +std::string Concat10(const char* s1, const char* s2, const char* s3, + const char* s4, const char* s5, const char* s6, + const char* s7, const char* s8, const char* s9, + const char* s10) { + return std::string(s1) + s2 + s3 + s4 + s5 + s6 + s7 + s8 + s9 + s10; } class Foo { @@ -185,7 +180,7 @@ class Foo { short Unary(long x) { return static_cast<short>(value_ + x); } // NOLINT - string Binary(const string& str, char c) const { return str + c; } + std::string Binary(const std::string& str, char c) const { return str + c; } int Ternary(int x, bool y, char z) { return value_ + x + y*z; } @@ -201,29 +196,29 @@ class Foo { return a + b + c + d + e + f; } - string Concat7(const char* s1, const char* s2, const char* s3, - const char* s4, const char* s5, const char* s6, - const char* s7) { - return string(s1) + s2 + s3 + s4 + s5 + s6 + s7; + std::string Concat7(const char* s1, const char* s2, const char* s3, + const char* s4, const char* s5, const char* s6, + const char* s7) { + return std::string(s1) + s2 + s3 + s4 + s5 + s6 + s7; } - string Concat8(const char* s1, const char* s2, const char* s3, - const char* s4, const char* s5, const char* s6, - const char* s7, const char* s8) { - return string(s1) + s2 + s3 + s4 + s5 + s6 + s7 + s8; + std::string Concat8(const char* s1, const char* s2, const char* s3, + const char* s4, const char* s5, const char* s6, + const char* s7, const char* s8) { + return std::string(s1) + s2 + s3 + s4 + s5 + s6 + s7 + s8; } - string Concat9(const char* s1, const char* s2, const char* s3, - const char* s4, const char* s5, const char* s6, - const char* s7, const char* s8, const char* s9) { - return string(s1) + s2 + s3 + s4 + s5 + s6 + s7 + s8 + s9; + std::string Concat9(const char* s1, const char* s2, const char* s3, + const char* s4, const char* s5, const char* s6, + const char* s7, const char* s8, const char* s9) { + return std::string(s1) + s2 + s3 + s4 + s5 + s6 + s7 + s8 + s9; } - string Concat10(const char* s1, const char* s2, const char* s3, - const char* s4, const char* s5, const char* s6, - const char* s7, const char* s8, const char* s9, - const char* s10) { - return string(s1) + s2 + s3 + s4 + s5 + s6 + s7 + s8 + s9 + s10; + std::string Concat10(const char* s1, const char* s2, const char* s3, + const char* s4, const char* s5, const char* s6, + const char* s7, const char* s8, const char* s9, + const char* s10) { + return std::string(s1) + s2 + s3 + s4 + s5 + s6 + s7 + s8 + s9 + s10; } private: @@ -233,45 +228,46 @@ class Foo { // Tests using Invoke() with a nullary function. TEST(InvokeTest, Nullary) { Action<int()> a = Invoke(Nullary); // NOLINT - EXPECT_EQ(1, a.Perform(make_tuple())); + EXPECT_EQ(1, a.Perform(std::make_tuple())); } // Tests using Invoke() with a unary function. TEST(InvokeTest, Unary) { Action<bool(int)> a = Invoke(Unary); // NOLINT - EXPECT_FALSE(a.Perform(make_tuple(1))); - EXPECT_TRUE(a.Perform(make_tuple(-1))); + EXPECT_FALSE(a.Perform(std::make_tuple(1))); + EXPECT_TRUE(a.Perform(std::make_tuple(-1))); } // Tests using Invoke() with a binary function. TEST(InvokeTest, Binary) { Action<const char*(const char*, short)> a = Invoke(Binary); // NOLINT const char* p = "Hello"; - EXPECT_EQ(p + 2, a.Perform(make_tuple(p, Short(2)))); + EXPECT_EQ(p + 2, a.Perform(std::make_tuple(p, Short(2)))); } // Tests using Invoke() with a ternary function. TEST(InvokeTest, Ternary) { Action<int(int, char, short)> a = Invoke(Ternary); // NOLINT - EXPECT_EQ(6, a.Perform(make_tuple(1, '\2', Short(3)))); + EXPECT_EQ(6, a.Perform(std::make_tuple(1, '\2', Short(3)))); } // Tests using Invoke() with a 4-argument function. TEST(InvokeTest, FunctionThatTakes4Arguments) { Action<int(int, int, int, int)> a = Invoke(SumOf4); // NOLINT - EXPECT_EQ(1234, a.Perform(make_tuple(1000, 200, 30, 4))); + EXPECT_EQ(1234, a.Perform(std::make_tuple(1000, 200, 30, 4))); } // Tests using Invoke() with a 5-argument function. TEST(InvokeTest, FunctionThatTakes5Arguments) { Action<int(int, int, int, int, int)> a = Invoke(SumOf5); // NOLINT - EXPECT_EQ(12345, a.Perform(make_tuple(10000, 2000, 300, 40, 5))); + EXPECT_EQ(12345, a.Perform(std::make_tuple(10000, 2000, 300, 40, 5))); } // Tests using Invoke() with a 6-argument function. TEST(InvokeTest, FunctionThatTakes6Arguments) { Action<int(int, int, int, int, int, int)> a = Invoke(SumOf6); // NOLINT - EXPECT_EQ(123456, a.Perform(make_tuple(100000, 20000, 3000, 400, 50, 6))); + EXPECT_EQ(123456, + a.Perform(std::make_tuple(100000, 20000, 3000, 400, 50, 6))); } // A helper that turns the type of a C-string literal from const @@ -280,84 +276,85 @@ inline const char* CharPtr(const char* s) { return s; } // Tests using Invoke() with a 7-argument function. TEST(InvokeTest, FunctionThatTakes7Arguments) { - Action<string(const char*, const char*, const char*, const char*, - const char*, const char*, const char*)> a = - Invoke(Concat7); + Action<std::string(const char*, const char*, const char*, const char*, + const char*, const char*, const char*)> + a = Invoke(Concat7); EXPECT_EQ("1234567", - a.Perform(make_tuple(CharPtr("1"), CharPtr("2"), CharPtr("3"), - CharPtr("4"), CharPtr("5"), CharPtr("6"), - CharPtr("7")))); + a.Perform(std::make_tuple(CharPtr("1"), CharPtr("2"), CharPtr("3"), + CharPtr("4"), CharPtr("5"), CharPtr("6"), + CharPtr("7")))); } // Tests using Invoke() with a 8-argument function. TEST(InvokeTest, FunctionThatTakes8Arguments) { - Action<string(const char*, const char*, const char*, const char*, - const char*, const char*, const char*, const char*)> a = - Invoke(Concat8); + Action<std::string(const char*, const char*, const char*, const char*, + const char*, const char*, const char*, const char*)> + a = Invoke(Concat8); EXPECT_EQ("12345678", - a.Perform(make_tuple(CharPtr("1"), CharPtr("2"), CharPtr("3"), - CharPtr("4"), CharPtr("5"), CharPtr("6"), - CharPtr("7"), CharPtr("8")))); + a.Perform(std::make_tuple(CharPtr("1"), CharPtr("2"), CharPtr("3"), + CharPtr("4"), CharPtr("5"), CharPtr("6"), + CharPtr("7"), CharPtr("8")))); } // Tests using Invoke() with a 9-argument function. TEST(InvokeTest, FunctionThatTakes9Arguments) { - Action<string(const char*, const char*, const char*, const char*, - const char*, const char*, const char*, const char*, - const char*)> a = Invoke(Concat9); - EXPECT_EQ("123456789", - a.Perform(make_tuple(CharPtr("1"), CharPtr("2"), CharPtr("3"), - CharPtr("4"), CharPtr("5"), CharPtr("6"), - CharPtr("7"), CharPtr("8"), CharPtr("9")))); + Action<std::string(const char*, const char*, const char*, const char*, + const char*, const char*, const char*, const char*, + const char*)> + a = Invoke(Concat9); + EXPECT_EQ("123456789", a.Perform(std::make_tuple( + CharPtr("1"), CharPtr("2"), CharPtr("3"), + CharPtr("4"), CharPtr("5"), CharPtr("6"), + CharPtr("7"), CharPtr("8"), CharPtr("9")))); } // Tests using Invoke() with a 10-argument function. TEST(InvokeTest, FunctionThatTakes10Arguments) { - Action<string(const char*, const char*, const char*, const char*, - const char*, const char*, const char*, const char*, - const char*, const char*)> a = Invoke(Concat10); + Action<std::string(const char*, const char*, const char*, const char*, + const char*, const char*, const char*, const char*, + const char*, const char*)> + a = Invoke(Concat10); EXPECT_EQ("1234567890", - a.Perform(make_tuple(CharPtr("1"), CharPtr("2"), CharPtr("3"), - CharPtr("4"), CharPtr("5"), CharPtr("6"), - CharPtr("7"), CharPtr("8"), CharPtr("9"), - CharPtr("0")))); + a.Perform(std::make_tuple(CharPtr("1"), CharPtr("2"), CharPtr("3"), + CharPtr("4"), CharPtr("5"), CharPtr("6"), + CharPtr("7"), CharPtr("8"), CharPtr("9"), + CharPtr("0")))); } // Tests using Invoke() with functions with parameters declared as Unused. TEST(InvokeTest, FunctionWithUnusedParameters) { - Action<int(int, int, double, const string&)> a1 = - Invoke(SumOfFirst2); - string s("hi"); - EXPECT_EQ(12, a1.Perform( - tuple<int, int, double, const string&>(10, 2, 5.6, s))); + Action<int(int, int, double, const std::string&)> a1 = Invoke(SumOfFirst2); + std::tuple<int, int, double, std::string> dummy = + std::make_tuple(10, 2, 5.6, std::string("hi")); + EXPECT_EQ(12, a1.Perform(dummy)); Action<int(int, int, bool, int*)> a2 = Invoke(SumOfFirst2); - EXPECT_EQ(23, a2.Perform(make_tuple(20, 3, true, static_cast<int*>(NULL)))); + EXPECT_EQ( + 23, a2.Perform(std::make_tuple(20, 3, true, static_cast<int*>(nullptr)))); } // Tests using Invoke() with methods with parameters declared as Unused. TEST(InvokeTest, MethodWithUnusedParameters) { Foo foo; - Action<int(string, bool, int, int)> a1 = - Invoke(&foo, &Foo::SumOfLast2); - EXPECT_EQ(12, a1.Perform(make_tuple(CharPtr("hi"), true, 10, 2))); + Action<int(std::string, bool, int, int)> a1 = Invoke(&foo, &Foo::SumOfLast2); + EXPECT_EQ(12, a1.Perform(std::make_tuple(CharPtr("hi"), true, 10, 2))); Action<int(char, double, int, int)> a2 = Invoke(&foo, &Foo::SumOfLast2); - EXPECT_EQ(23, a2.Perform(make_tuple('a', 2.5, 20, 3))); + EXPECT_EQ(23, a2.Perform(std::make_tuple('a', 2.5, 20, 3))); } // Tests using Invoke() with a functor. TEST(InvokeTest, Functor) { Action<long(long, int)> a = Invoke(plus<long>()); // NOLINT - EXPECT_EQ(3L, a.Perform(make_tuple(1, 2))); + EXPECT_EQ(3L, a.Perform(std::make_tuple(1, 2))); } // Tests using Invoke(f) as an action of a compatible type. TEST(InvokeTest, FunctionWithCompatibleType) { Action<long(int, short, char, bool)> a = Invoke(SumOf4); // NOLINT - EXPECT_EQ(4321, a.Perform(make_tuple(4000, Short(300), Char(20), true))); + EXPECT_EQ(4321, a.Perform(std::make_tuple(4000, Short(300), Char(20), true))); } // Tests using Invoke() with an object pointer and a method pointer. @@ -366,44 +363,44 @@ TEST(InvokeTest, FunctionWithCompatibleType) { TEST(InvokeMethodTest, Nullary) { Foo foo; Action<int()> a = Invoke(&foo, &Foo::Nullary); // NOLINT - EXPECT_EQ(123, a.Perform(make_tuple())); + EXPECT_EQ(123, a.Perform(std::make_tuple())); } // Tests using Invoke() with a unary method. TEST(InvokeMethodTest, Unary) { Foo foo; Action<short(long)> a = Invoke(&foo, &Foo::Unary); // NOLINT - EXPECT_EQ(4123, a.Perform(make_tuple(4000))); + EXPECT_EQ(4123, a.Perform(std::make_tuple(4000))); } // Tests using Invoke() with a binary method. TEST(InvokeMethodTest, Binary) { Foo foo; - Action<string(const string&, char)> a = Invoke(&foo, &Foo::Binary); - string s("Hell"); - EXPECT_EQ("Hello", a.Perform( - tuple<const string&, char>(s, 'o'))); + Action<std::string(const std::string&, char)> a = Invoke(&foo, &Foo::Binary); + std::string s("Hell"); + std::tuple<std::string, char> dummy = std::make_tuple(s, 'o'); + EXPECT_EQ("Hello", a.Perform(dummy)); } // Tests using Invoke() with a ternary method. TEST(InvokeMethodTest, Ternary) { Foo foo; Action<int(int, bool, char)> a = Invoke(&foo, &Foo::Ternary); // NOLINT - EXPECT_EQ(1124, a.Perform(make_tuple(1000, true, Char(1)))); + EXPECT_EQ(1124, a.Perform(std::make_tuple(1000, true, Char(1)))); } // Tests using Invoke() with a 4-argument method. TEST(InvokeMethodTest, MethodThatTakes4Arguments) { Foo foo; Action<int(int, int, int, int)> a = Invoke(&foo, &Foo::SumOf4); // NOLINT - EXPECT_EQ(1357, a.Perform(make_tuple(1000, 200, 30, 4))); + EXPECT_EQ(1357, a.Perform(std::make_tuple(1000, 200, 30, 4))); } // Tests using Invoke() with a 5-argument method. TEST(InvokeMethodTest, MethodThatTakes5Arguments) { Foo foo; Action<int(int, int, int, int, int)> a = Invoke(&foo, &Foo::SumOf5); // NOLINT - EXPECT_EQ(12345, a.Perform(make_tuple(10000, 2000, 300, 40, 5))); + EXPECT_EQ(12345, a.Perform(std::make_tuple(10000, 2000, 300, 40, 5))); } // Tests using Invoke() with a 6-argument method. @@ -411,56 +408,59 @@ TEST(InvokeMethodTest, MethodThatTakes6Arguments) { Foo foo; Action<int(int, int, int, int, int, int)> a = // NOLINT Invoke(&foo, &Foo::SumOf6); - EXPECT_EQ(123456, a.Perform(make_tuple(100000, 20000, 3000, 400, 50, 6))); + EXPECT_EQ(123456, + a.Perform(std::make_tuple(100000, 20000, 3000, 400, 50, 6))); } // Tests using Invoke() with a 7-argument method. TEST(InvokeMethodTest, MethodThatTakes7Arguments) { Foo foo; - Action<string(const char*, const char*, const char*, const char*, - const char*, const char*, const char*)> a = - Invoke(&foo, &Foo::Concat7); + Action<std::string(const char*, const char*, const char*, const char*, + const char*, const char*, const char*)> + a = Invoke(&foo, &Foo::Concat7); EXPECT_EQ("1234567", - a.Perform(make_tuple(CharPtr("1"), CharPtr("2"), CharPtr("3"), - CharPtr("4"), CharPtr("5"), CharPtr("6"), - CharPtr("7")))); + a.Perform(std::make_tuple(CharPtr("1"), CharPtr("2"), CharPtr("3"), + CharPtr("4"), CharPtr("5"), CharPtr("6"), + CharPtr("7")))); } // Tests using Invoke() with a 8-argument method. TEST(InvokeMethodTest, MethodThatTakes8Arguments) { Foo foo; - Action<string(const char*, const char*, const char*, const char*, - const char*, const char*, const char*, const char*)> a = - Invoke(&foo, &Foo::Concat8); + Action<std::string(const char*, const char*, const char*, const char*, + const char*, const char*, const char*, const char*)> + a = Invoke(&foo, &Foo::Concat8); EXPECT_EQ("12345678", - a.Perform(make_tuple(CharPtr("1"), CharPtr("2"), CharPtr("3"), - CharPtr("4"), CharPtr("5"), CharPtr("6"), - CharPtr("7"), CharPtr("8")))); + a.Perform(std::make_tuple(CharPtr("1"), CharPtr("2"), CharPtr("3"), + CharPtr("4"), CharPtr("5"), CharPtr("6"), + CharPtr("7"), CharPtr("8")))); } // Tests using Invoke() with a 9-argument method. TEST(InvokeMethodTest, MethodThatTakes9Arguments) { Foo foo; - Action<string(const char*, const char*, const char*, const char*, - const char*, const char*, const char*, const char*, - const char*)> a = Invoke(&foo, &Foo::Concat9); - EXPECT_EQ("123456789", - a.Perform(make_tuple(CharPtr("1"), CharPtr("2"), CharPtr("3"), - CharPtr("4"), CharPtr("5"), CharPtr("6"), - CharPtr("7"), CharPtr("8"), CharPtr("9")))); + Action<std::string(const char*, const char*, const char*, const char*, + const char*, const char*, const char*, const char*, + const char*)> + a = Invoke(&foo, &Foo::Concat9); + EXPECT_EQ("123456789", a.Perform(std::make_tuple( + CharPtr("1"), CharPtr("2"), CharPtr("3"), + CharPtr("4"), CharPtr("5"), CharPtr("6"), + CharPtr("7"), CharPtr("8"), CharPtr("9")))); } // Tests using Invoke() with a 10-argument method. TEST(InvokeMethodTest, MethodThatTakes10Arguments) { Foo foo; - Action<string(const char*, const char*, const char*, const char*, - const char*, const char*, const char*, const char*, - const char*, const char*)> a = Invoke(&foo, &Foo::Concat10); + Action<std::string(const char*, const char*, const char*, const char*, + const char*, const char*, const char*, const char*, + const char*, const char*)> + a = Invoke(&foo, &Foo::Concat10); EXPECT_EQ("1234567890", - a.Perform(make_tuple(CharPtr("1"), CharPtr("2"), CharPtr("3"), - CharPtr("4"), CharPtr("5"), CharPtr("6"), - CharPtr("7"), CharPtr("8"), CharPtr("9"), - CharPtr("0")))); + a.Perform(std::make_tuple(CharPtr("1"), CharPtr("2"), CharPtr("3"), + CharPtr("4"), CharPtr("5"), CharPtr("6"), + CharPtr("7"), CharPtr("8"), CharPtr("9"), + CharPtr("0")))); } // Tests using Invoke(f) as an action of a compatible type. @@ -468,48 +468,48 @@ TEST(InvokeMethodTest, MethodWithCompatibleType) { Foo foo; Action<long(int, short, char, bool)> a = // NOLINT Invoke(&foo, &Foo::SumOf4); - EXPECT_EQ(4444, a.Perform(make_tuple(4000, Short(300), Char(20), true))); + EXPECT_EQ(4444, a.Perform(std::make_tuple(4000, Short(300), Char(20), true))); } // Tests using WithoutArgs with an action that takes no argument. TEST(WithoutArgsTest, NoArg) { Action<int(int n)> a = WithoutArgs(Invoke(Nullary)); // NOLINT - EXPECT_EQ(1, a.Perform(make_tuple(2))); + EXPECT_EQ(1, a.Perform(std::make_tuple(2))); } // Tests using WithArg with an action that takes 1 argument. TEST(WithArgTest, OneArg) { Action<bool(double x, int n)> b = WithArg<1>(Invoke(Unary)); // NOLINT - EXPECT_TRUE(b.Perform(make_tuple(1.5, -1))); - EXPECT_FALSE(b.Perform(make_tuple(1.5, 1))); + EXPECT_TRUE(b.Perform(std::make_tuple(1.5, -1))); + EXPECT_FALSE(b.Perform(std::make_tuple(1.5, 1))); } TEST(ReturnArgActionTest, WorksForOneArgIntArg0) { const Action<int(int)> a = ReturnArg<0>(); - EXPECT_EQ(5, a.Perform(make_tuple(5))); + EXPECT_EQ(5, a.Perform(std::make_tuple(5))); } TEST(ReturnArgActionTest, WorksForMultiArgBoolArg0) { const Action<bool(bool, bool, bool)> a = ReturnArg<0>(); - EXPECT_TRUE(a.Perform(make_tuple(true, false, false))); + EXPECT_TRUE(a.Perform(std::make_tuple(true, false, false))); } TEST(ReturnArgActionTest, WorksForMultiArgStringArg2) { - const Action<string(int, int, string, int)> a = ReturnArg<2>(); - EXPECT_EQ("seven", a.Perform(make_tuple(5, 6, string("seven"), 8))); + const Action<std::string(int, int, std::string, int)> a = ReturnArg<2>(); + EXPECT_EQ("seven", a.Perform(std::make_tuple(5, 6, std::string("seven"), 8))); } TEST(SaveArgActionTest, WorksForSameType) { int result = 0; const Action<void(int n)> a1 = SaveArg<0>(&result); - a1.Perform(make_tuple(5)); + a1.Perform(std::make_tuple(5)); EXPECT_EQ(5, result); } TEST(SaveArgActionTest, WorksForCompatibleType) { int result = 0; const Action<void(bool, char)> a1 = SaveArg<1>(&result); - a1.Perform(make_tuple(true, 'a')); + a1.Perform(std::make_tuple(true, 'a')); EXPECT_EQ('a', result); } @@ -517,7 +517,7 @@ TEST(SaveArgPointeeActionTest, WorksForSameType) { int result = 0; const int value = 5; const Action<void(const int*)> a1 = SaveArgPointee<0>(&result); - a1.Perform(make_tuple(&value)); + a1.Perform(std::make_tuple(&value)); EXPECT_EQ(5, result); } @@ -525,7 +525,7 @@ TEST(SaveArgPointeeActionTest, WorksForCompatibleType) { int result = 0; char value = 'a'; const Action<void(bool, char*)> a1 = SaveArgPointee<1>(&result); - a1.Perform(make_tuple(true, &value)); + a1.Perform(std::make_tuple(true, &value)); EXPECT_EQ('a', result); } @@ -533,28 +533,28 @@ TEST(SaveArgPointeeActionTest, WorksForLinkedPtr) { int result = 0; linked_ptr<int> value(new int(5)); const Action<void(linked_ptr<int>)> a1 = SaveArgPointee<0>(&result); - a1.Perform(make_tuple(value)); + a1.Perform(std::make_tuple(value)); EXPECT_EQ(5, result); } TEST(SetArgRefereeActionTest, WorksForSameType) { int value = 0; const Action<void(int&)> a1 = SetArgReferee<0>(1); - a1.Perform(tuple<int&>(value)); + a1.Perform(std::tuple<int&>(value)); EXPECT_EQ(1, value); } TEST(SetArgRefereeActionTest, WorksForCompatibleType) { int value = 0; const Action<void(int, int&)> a1 = SetArgReferee<1>('a'); - a1.Perform(tuple<int, int&>(0, value)); + a1.Perform(std::tuple<int, int&>(0, value)); EXPECT_EQ('a', value); } TEST(SetArgRefereeActionTest, WorksWithExtraArguments) { int value = 0; const Action<void(bool, int, int&, const char*)> a1 = SetArgReferee<2>('a'); - a1.Perform(tuple<bool, int, int&, const char*>(true, 0, value, "hi")); + a1.Perform(std::tuple<bool, int, int&, const char*>(true, 0, value, "hi")); EXPECT_EQ('a', value); } @@ -581,7 +581,7 @@ TEST(DeleteArgActionTest, OneArg) { DeletionTester* t = new DeletionTester(&is_deleted); const Action<void(DeletionTester*)> a1 = DeleteArg<0>(); // NOLINT EXPECT_FALSE(is_deleted); - a1.Perform(make_tuple(t)); + a1.Perform(std::make_tuple(t)); EXPECT_TRUE(is_deleted); } @@ -591,7 +591,7 @@ TEST(DeleteArgActionTest, TenArgs) { const Action<void(bool, int, int, const char*, bool, int, int, int, int, DeletionTester*)> a1 = DeleteArg<9>(); EXPECT_FALSE(is_deleted); - a1.Perform(make_tuple(true, 5, 6, CharPtr("hi"), false, 7, 8, 9, 10, t)); + a1.Perform(std::make_tuple(true, 5, 6, CharPtr("hi"), false, 7, 8, 9, 10, t)); EXPECT_TRUE(is_deleted); } @@ -599,19 +599,19 @@ TEST(DeleteArgActionTest, TenArgs) { TEST(ThrowActionTest, ThrowsGivenExceptionInVoidFunction) { const Action<void(int n)> a = Throw('a'); - EXPECT_THROW(a.Perform(make_tuple(0)), char); + EXPECT_THROW(a.Perform(std::make_tuple(0)), char); } class MyException {}; TEST(ThrowActionTest, ThrowsGivenExceptionInNonVoidFunction) { const Action<double(char ch)> a = Throw(MyException()); - EXPECT_THROW(a.Perform(make_tuple('0')), MyException); + EXPECT_THROW(a.Perform(std::make_tuple('0')), MyException); } TEST(ThrowActionTest, ThrowsGivenExceptionInNullaryFunction) { const Action<double()> a = Throw(MyException()); - EXPECT_THROW(a.Perform(make_tuple()), MyException); + EXPECT_THROW(a.Perform(std::make_tuple()), MyException); } #endif // GTEST_HAS_EXCEPTIONS @@ -627,7 +627,7 @@ TEST(SetArrayArgumentTest, SetsTheNthArray) { int* pn = n; char ch[4] = {}; char* pch = ch; - a.Perform(make_tuple(true, pn, pch)); + a.Perform(std::make_tuple(true, pn, pch)); EXPECT_EQ(1, n[0]); EXPECT_EQ(2, n[1]); EXPECT_EQ(3, n[2]); @@ -642,7 +642,7 @@ TEST(SetArrayArgumentTest, SetsTheNthArray) { a = SetArrayArgument<2>(letters.begin(), letters.end()); std::fill_n(n, 4, 0); std::fill_n(ch, 4, '\0'); - a.Perform(make_tuple(true, pn, pch)); + a.Perform(std::make_tuple(true, pn, pch)); EXPECT_EQ(0, n[0]); EXPECT_EQ(0, n[1]); EXPECT_EQ(0, n[2]); @@ -661,7 +661,7 @@ TEST(SetArrayArgumentTest, SetsTheNthArrayWithEmptyRange) { int n[4] = {}; int* pn = n; - a.Perform(make_tuple(true, pn)); + a.Perform(std::make_tuple(true, pn)); EXPECT_EQ(0, n[0]); EXPECT_EQ(0, n[1]); EXPECT_EQ(0, n[2]); @@ -677,7 +677,7 @@ TEST(SetArrayArgumentTest, SetsTheNthArrayWithConvertibleType) { int codes[4] = { 111, 222, 333, 444 }; int* pcodes = codes; - a.Perform(make_tuple(true, pcodes)); + a.Perform(std::make_tuple(true, pcodes)); EXPECT_EQ(97, codes[0]); EXPECT_EQ(98, codes[1]); EXPECT_EQ(99, codes[2]); @@ -691,17 +691,17 @@ TEST(SetArrayArgumentTest, SetsTheNthArrayWithIteratorArgument) { Action<MyFunction> a = SetArrayArgument<1>(letters.begin(), letters.end()); std::string s; - a.Perform(make_tuple(true, back_inserter(s))); + a.Perform(std::make_tuple(true, back_inserter(s))); EXPECT_EQ(letters, s); } TEST(ReturnPointeeTest, Works) { int n = 42; const Action<int()> a = ReturnPointee(&n); - EXPECT_EQ(42, a.Perform(make_tuple())); + EXPECT_EQ(42, a.Perform(std::make_tuple())); n = 43; - EXPECT_EQ(43, a.Perform(make_tuple())); + EXPECT_EQ(43, a.Perform(std::make_tuple())); } } // namespace gmock_generated_actions_test diff --git a/googlemock/test/gmock-nice-strict_test.cc b/googlemock/test/gmock-nice-strict_test.cc index 38daee0..9cae987 100644 --- a/googlemock/test/gmock-nice-strict_test.cc +++ b/googlemock/test/gmock-nice-strict_test.cc @@ -26,15 +26,15 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + #include "gmock/gmock-generated-nice-strict.h" #include <string> +#include <utility> #include "gmock/gmock.h" -#include "gtest/gtest.h" #include "gtest/gtest-spi.h" +#include "gtest/gtest.h" // This must not be defined inside the ::testing namespace, or it will // clash with ::testing::Mock. @@ -51,7 +51,6 @@ class Mock { namespace testing { namespace gmock_nice_strict_test { -using testing::internal::string; using testing::GMOCK_FLAG(verbose); using testing::HasSubstr; using testing::NaggyMock; @@ -63,6 +62,12 @@ using testing::internal::CaptureStdout; using testing::internal::GetCapturedStdout; #endif +// Class without default constructor. +class NotDefaultConstructible { + public: + explicit NotDefaultConstructible(int) {} +}; + // Defines some mock classes needed by the tests. class Foo { @@ -80,6 +85,7 @@ class MockFoo : public Foo { MOCK_METHOD0(DoThis, void()); MOCK_METHOD1(DoThat, int(bool flag)); + MOCK_METHOD0(ReturnNonDefaultConstructible, NotDefaultConstructible()); private: GTEST_DISALLOW_COPY_AND_ASSIGN_(MockFoo); @@ -87,32 +93,50 @@ class MockFoo : public Foo { class MockBar { public: - explicit MockBar(const string& s) : str_(s) {} + explicit MockBar(const std::string& s) : str_(s) {} - MockBar(char a1, char a2, string a3, string a4, int a5, int a6, - const string& a7, const string& a8, bool a9, bool a10) { - str_ = string() + a1 + a2 + a3 + a4 + static_cast<char>(a5) + + MockBar(char a1, char a2, std::string a3, std::string a4, int a5, int a6, + const std::string& a7, const std::string& a8, bool a9, bool a10) { + str_ = std::string() + a1 + a2 + a3 + a4 + static_cast<char>(a5) + static_cast<char>(a6) + a7 + a8 + (a9 ? 'T' : 'F') + (a10 ? 'T' : 'F'); } virtual ~MockBar() {} - const string& str() const { return str_; } + const std::string& str() const { return str_; } MOCK_METHOD0(This, int()); - MOCK_METHOD2(That, string(int, bool)); + MOCK_METHOD2(That, std::string(int, bool)); private: - string str_; + std::string str_; GTEST_DISALLOW_COPY_AND_ASSIGN_(MockBar); }; +#if GTEST_GTEST_LANG_CXX11 + +class MockBaz { + public: + class MoveOnly { + MoveOnly() = default; + + MoveOnly(const MoveOnly&) = delete; + operator=(const MoveOnly&) = delete; + + MoveOnly(MoveOnly&&) = default; + operator=(MoveOnly&&) = default; + }; + + MockBaz(MoveOnly) {} +} +#endif // GTEST_GTEST_LANG_CXX11 && GTEST_HAS_STD_MOVE_ + #if GTEST_HAS_STREAM_REDIRECTION // Tests that a raw mock generates warnings for uninteresting calls. TEST(RawMockTest, WarningForUninterestingCall) { - const string saved_flag = GMOCK_FLAG(verbose); + const std::string saved_flag = GMOCK_FLAG(verbose); GMOCK_FLAG(verbose) = "warning"; MockFoo raw_foo; @@ -129,7 +153,7 @@ TEST(RawMockTest, WarningForUninterestingCall) { // Tests that a raw mock generates warnings for uninteresting calls // that delete the mock object. TEST(RawMockTest, WarningForUninterestingCallAfterDeath) { - const string saved_flag = GMOCK_FLAG(verbose); + const std::string saved_flag = GMOCK_FLAG(verbose); GMOCK_FLAG(verbose) = "warning"; MockFoo* const raw_foo = new MockFoo; @@ -150,7 +174,7 @@ TEST(RawMockTest, WarningForUninterestingCallAfterDeath) { TEST(RawMockTest, InfoForUninterestingCall) { MockFoo raw_foo; - const string saved_flag = GMOCK_FLAG(verbose); + const std::string saved_flag = GMOCK_FLAG(verbose); GMOCK_FLAG(verbose) = "info"; CaptureStdout(); raw_foo.DoThis(); @@ -196,7 +220,7 @@ TEST(NiceMockTest, NoWarningForUninterestingCallAfterDeath) { TEST(NiceMockTest, InfoForUninterestingCall) { NiceMock<MockFoo> nice_foo; - const string saved_flag = GMOCK_FLAG(verbose); + const std::string saved_flag = GMOCK_FLAG(verbose); GMOCK_FLAG(verbose) = "info"; CaptureStdout(); nice_foo.DoThis(); @@ -216,6 +240,23 @@ TEST(NiceMockTest, AllowsExpectedCall) { nice_foo.DoThis(); } +// Tests that an unexpected call on a nice mock which returns a +// not-default-constructible type throws an exception and the exception contains +// the method's name. +TEST(NiceMockTest, ThrowsExceptionForUnknownReturnTypes) { + NiceMock<MockFoo> nice_foo; +#if GTEST_HAS_EXCEPTIONS + try { + nice_foo.ReturnNonDefaultConstructible(); + FAIL(); + } catch (const std::runtime_error& ex) { + EXPECT_THAT(ex.what(), HasSubstr("ReturnNonDefaultConstructible")); + } +#else + EXPECT_DEATH_IF_SUPPORTED({ nice_foo.ReturnNonDefaultConstructible(); }, ""); +#endif +} + // Tests that an unexpected call on a nice mock fails. TEST(NiceMockTest, UnexpectedCallFails) { NiceMock<MockFoo> nice_foo; @@ -245,6 +286,21 @@ TEST(NiceMockTest, NonDefaultConstructor10) { nice_bar.That(5, true); } +TEST(NiceMockTest, AllowLeak) { + NiceMock<MockFoo>* leaked = new NiceMock<MockFoo>; + Mock::AllowLeak(leaked); + EXPECT_CALL(*leaked, DoThis()); + leaked->DoThis(); +} + +#if GTEST_GTEST_LANG_CXX11 && GTEST_HAS_STD_MOVE_ + +TEST(NiceMockTest, MoveOnlyConstructor) { + NiceMock<MockBaz> nice_baz(MockBaz::MoveOnly()); +} + +#endif // GTEST_LANG_CXX11 && GTEST_HAS_STD_MOVE_ + #if !GTEST_OS_SYMBIAN && !GTEST_OS_WINDOWS_MOBILE // Tests that NiceMock<Mock> compiles where Mock is a user-defined // class (as opposed to ::testing::Mock). We had to work around an @@ -272,7 +328,7 @@ TEST(NiceMockTest, IsNaggy_IsNice_IsStrict) { // Tests that a naggy mock generates warnings for uninteresting calls. TEST(NaggyMockTest, WarningForUninterestingCall) { - const string saved_flag = GMOCK_FLAG(verbose); + const std::string saved_flag = GMOCK_FLAG(verbose); GMOCK_FLAG(verbose) = "warning"; NaggyMock<MockFoo> naggy_foo; @@ -289,7 +345,7 @@ TEST(NaggyMockTest, WarningForUninterestingCall) { // Tests that a naggy mock generates a warning for an uninteresting call // that deletes the mock object. TEST(NaggyMockTest, WarningForUninterestingCallAfterDeath) { - const string saved_flag = GMOCK_FLAG(verbose); + const std::string saved_flag = GMOCK_FLAG(verbose); GMOCK_FLAG(verbose) = "warning"; NaggyMock<MockFoo>* const naggy_foo = new NaggyMock<MockFoo>; @@ -345,6 +401,21 @@ TEST(NaggyMockTest, NonDefaultConstructor10) { naggy_bar.That(5, true); } +TEST(NaggyMockTest, AllowLeak) { + NaggyMock<MockFoo>* leaked = new NaggyMock<MockFoo>; + Mock::AllowLeak(leaked); + EXPECT_CALL(*leaked, DoThis()); + leaked->DoThis(); +} + +#if GTEST_GTEST_LANG_CXX11 && GTEST_HAS_STD_MOVE_ + +TEST(NaggyMockTest, MoveOnlyConstructor) { + NaggyMock<MockBaz> naggy_baz(MockBaz::MoveOnly()); +} + +#endif // GTEST_LANG_CXX11 && GTEST_HAS_STD_MOVE_ + #if !GTEST_OS_SYMBIAN && !GTEST_OS_WINDOWS_MOBILE // Tests that NaggyMock<Mock> compiles where Mock is a user-defined // class (as opposed to ::testing::Mock). We had to work around an @@ -426,6 +497,21 @@ TEST(StrictMockTest, NonDefaultConstructor10) { "Uninteresting mock function call"); } +TEST(StrictMockTest, AllowLeak) { + StrictMock<MockFoo>* leaked = new StrictMock<MockFoo>; + Mock::AllowLeak(leaked); + EXPECT_CALL(*leaked, DoThis()); + leaked->DoThis(); +} + +#if GTEST_GTEST_LANG_CXX11 && GTEST_HAS_STD_MOVE_ + +TEST(StrictMockTest, MoveOnlyConstructor) { + StrictMock<MockBaz> strict_baz(MockBaz::MoveOnly()); +} + +#endif // GTEST_LANG_CXX11 && GTEST_HAS_STD_MOVE_ + #if !GTEST_OS_SYMBIAN && !GTEST_OS_WINDOWS_MOBILE // Tests that StrictMock<Mock> compiles where Mock is a user-defined // class (as opposed to ::testing::Mock). We had to work around an diff --git a/googlemock/test/gmock-port_test.cc b/googlemock/test/gmock-port_test.cc index d6a8d44..a2c2be2 100644 --- a/googlemock/test/gmock-port_test.cc +++ b/googlemock/test/gmock-port_test.cc @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: vladl@google.com (Vlad Losev) + // Google Mock - a framework for writing C++ mock classes. // diff --git a/googlemock/test/gmock-spec-builders_test.cc b/googlemock/test/gmock-spec-builders_test.cc index 59ea87c..65c9fcc 100644 --- a/googlemock/test/gmock-spec-builders_test.cc +++ b/googlemock/test/gmock-spec-builders_test.cc @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // Google Mock - a framework for writing C++ mock classes. // @@ -89,15 +88,18 @@ using testing::Mock; using testing::NaggyMock; using testing::Ne; using testing::Return; +using testing::SaveArg; using testing::Sequence; using testing::SetArgPointee; using testing::internal::ExpectationTester; using testing::internal::FormatFileLocation; +using testing::internal::kAllow; using testing::internal::kErrorVerbosity; +using testing::internal::kFail; using testing::internal::kInfoVerbosity; +using testing::internal::kWarn; using testing::internal::kWarningVerbosity; using testing::internal::linked_ptr; -using testing::internal::string; #if GTEST_HAS_STREAM_REDIRECTION using testing::HasSubstr; @@ -692,6 +694,60 @@ TEST(ExpectCallSyntaxTest, WarnsOnTooFewActions) { b.DoB(); } +TEST(ExpectCallSyntaxTest, WarningIsErrorWithFlag) { + int original_behavior = testing::GMOCK_FLAG(default_mock_behavior); + + testing::GMOCK_FLAG(default_mock_behavior) = kAllow; + CaptureStdout(); + { + MockA a; + a.DoA(0); + } + std::string output = GetCapturedStdout(); + EXPECT_TRUE(output.empty()) << output; + + testing::GMOCK_FLAG(default_mock_behavior) = kWarn; + CaptureStdout(); + { + MockA a; + a.DoA(0); + } + std::string warning_output = GetCapturedStdout(); + EXPECT_PRED_FORMAT2(IsSubstring, "GMOCK WARNING", warning_output); + EXPECT_PRED_FORMAT2(IsSubstring, "Uninteresting mock function call", + warning_output); + + testing::GMOCK_FLAG(default_mock_behavior) = kFail; + EXPECT_NONFATAL_FAILURE({ + MockA a; + a.DoA(0); + }, "Uninteresting mock function call"); + + // Out of bounds values are converted to kWarn + testing::GMOCK_FLAG(default_mock_behavior) = -1; + CaptureStdout(); + { + MockA a; + a.DoA(0); + } + warning_output = GetCapturedStdout(); + EXPECT_PRED_FORMAT2(IsSubstring, "GMOCK WARNING", warning_output); + EXPECT_PRED_FORMAT2(IsSubstring, "Uninteresting mock function call", + warning_output); + testing::GMOCK_FLAG(default_mock_behavior) = 3; + CaptureStdout(); + { + MockA a; + a.DoA(0); + } + warning_output = GetCapturedStdout(); + EXPECT_PRED_FORMAT2(IsSubstring, "GMOCK WARNING", warning_output); + EXPECT_PRED_FORMAT2(IsSubstring, "Uninteresting mock function call", + warning_output); + + testing::GMOCK_FLAG(default_mock_behavior) = original_behavior; +} + #endif // GTEST_HAS_STREAM_REDIRECTION // Tests the semantics of ON_CALL(). @@ -1119,7 +1175,7 @@ TEST(UnexpectedCallTest, UnsatisifiedPrerequisites) { TEST(UndefinedReturnValueTest, ReturnValueIsMandatoryWhenNotDefaultConstructible) { MockA a; - // TODO(wan@google.com): We should really verify the output message, + // FIXME: We should really verify the output message, // but we cannot yet due to that EXPECT_DEATH only captures stderr // while Google Mock logs to stdout. #if GTEST_HAS_EXCEPTIONS @@ -1954,7 +2010,7 @@ class MockC { public: MockC() {} - MOCK_METHOD6(VoidMethod, void(bool cond, int n, string s, void* p, + MOCK_METHOD6(VoidMethod, void(bool cond, int n, std::string s, void* p, const Printable& x, Unprintable y)); MOCK_METHOD0(NonVoidMethod, int()); // NOLINT @@ -1970,7 +2026,7 @@ class VerboseFlagPreservingFixture : public testing::Test { ~VerboseFlagPreservingFixture() { GMOCK_FLAG(verbose) = saved_verbose_flag_; } private: - const string saved_verbose_flag_; + const std::string saved_verbose_flag_; GTEST_DISALLOW_COPY_AND_ASSIGN_(VerboseFlagPreservingFixture); }; @@ -1985,7 +2041,7 @@ TEST(FunctionCallMessageTest, GMOCK_FLAG(verbose) = kWarningVerbosity; NaggyMock<MockC> c; CaptureStdout(); - c.VoidMethod(false, 5, "Hi", NULL, Printable(), Unprintable()); + c.VoidMethod(false, 5, "Hi", nullptr, Printable(), Unprintable()); const std::string output = GetCapturedStdout(); EXPECT_PRED_FORMAT2(IsSubstring, "GMOCK WARNING", output); EXPECT_PRED_FORMAT2(IsNotSubstring, "Stack trace:", output); @@ -1999,7 +2055,7 @@ TEST(FunctionCallMessageTest, GMOCK_FLAG(verbose) = kInfoVerbosity; NaggyMock<MockC> c; CaptureStdout(); - c.VoidMethod(false, 5, "Hi", NULL, Printable(), Unprintable()); + c.VoidMethod(false, 5, "Hi", nullptr, Printable(), Unprintable()); const std::string output = GetCapturedStdout(); EXPECT_PRED_FORMAT2(IsSubstring, "GMOCK WARNING", output); EXPECT_PRED_FORMAT2(IsSubstring, "Stack trace:", output); @@ -2042,7 +2098,7 @@ TEST(FunctionCallMessageTest, // A void mock function. NaggyMock<MockC> c; CaptureStdout(); - c.VoidMethod(false, 5, "Hi", NULL, Printable(), Unprintable()); + c.VoidMethod(false, 5, "Hi", nullptr, Printable(), Unprintable()); const std::string output2 = GetCapturedStdout(); EXPECT_THAT(output2.c_str(), ContainsRegex( @@ -2062,8 +2118,8 @@ class GMockVerboseFlagTest : public VerboseFlagPreservingFixture { // contain the given function name in the stack trace. When it's // false, the output should be empty.) void VerifyOutput(const std::string& output, bool should_print, - const string& expected_substring, - const string& function_name) { + const std::string& expected_substring, + const std::string& function_name) { if (should_print) { EXPECT_THAT(output.c_str(), HasSubstr(expected_substring)); # ifndef NDEBUG @@ -2113,11 +2169,13 @@ class GMockVerboseFlagTest : public VerboseFlagPreservingFixture { // Tests how the flag affects uninteresting calls on a naggy mock. void TestUninterestingCallOnNaggyMock(bool should_print) { NaggyMock<MockA> a; - const string note = + const std::string note = "NOTE: You can safely ignore the above warning unless this " "call should not happen. Do not suppress it by blindly adding " "an EXPECT_CALL() if you don't mean to enforce the call. " - "See https://github.com/google/googletest/blob/master/googlemock/docs/CookBook.md#" + "See " + "https://github.com/google/googletest/blob/master/googlemock/docs/" + "CookBook.md#" "knowing-when-to-expect for details."; // A void-returning function. @@ -2623,9 +2681,78 @@ TEST(SynchronizationTest, CanCallMockMethodInAction) { // EXPECT_CALL() did not specify an action. } +TEST(ParameterlessExpectationsTest, CanSetExpectationsWithoutMatchers) { + MockA a; + int do_a_arg0 = 0; + ON_CALL(a, DoA).WillByDefault(SaveArg<0>(&do_a_arg0)); + int do_a_47_arg0 = 0; + ON_CALL(a, DoA(47)).WillByDefault(SaveArg<0>(&do_a_47_arg0)); + + a.DoA(17); + EXPECT_THAT(do_a_arg0, 17); + EXPECT_THAT(do_a_47_arg0, 0); + a.DoA(47); + EXPECT_THAT(do_a_arg0, 17); + EXPECT_THAT(do_a_47_arg0, 47); + + ON_CALL(a, Binary).WillByDefault(Return(true)); + ON_CALL(a, Binary(_, 14)).WillByDefault(Return(false)); + EXPECT_THAT(a.Binary(14, 17), true); + EXPECT_THAT(a.Binary(17, 14), false); +} + +TEST(ParameterlessExpectationsTest, CanSetExpectationsForOverloadedMethods) { + MockB b; + ON_CALL(b, DoB()).WillByDefault(Return(9)); + ON_CALL(b, DoB(5)).WillByDefault(Return(11)); + + EXPECT_THAT(b.DoB(), 9); + EXPECT_THAT(b.DoB(1), 0); // default value + EXPECT_THAT(b.DoB(5), 11); +} + +struct MockWithConstMethods { + public: + MOCK_CONST_METHOD1(Foo, int(int)); + MOCK_CONST_METHOD2(Bar, int(int, const char*)); +}; + +TEST(ParameterlessExpectationsTest, CanSetExpectationsForConstMethods) { + MockWithConstMethods mock; + ON_CALL(mock, Foo).WillByDefault(Return(7)); + ON_CALL(mock, Bar).WillByDefault(Return(33)); + + EXPECT_THAT(mock.Foo(17), 7); + EXPECT_THAT(mock.Bar(27, "purple"), 33); +} + +class MockConstOverload { + public: + MOCK_METHOD1(Overloaded, int(int)); + MOCK_CONST_METHOD1(Overloaded, int(int)); +}; + +TEST(ParameterlessExpectationsTest, + CanSetExpectationsForConstOverloadedMethods) { + MockConstOverload mock; + ON_CALL(mock, Overloaded(_)).WillByDefault(Return(7)); + ON_CALL(mock, Overloaded(5)).WillByDefault(Return(9)); + ON_CALL(Const(mock), Overloaded(5)).WillByDefault(Return(11)); + ON_CALL(Const(mock), Overloaded(7)).WillByDefault(Return(13)); + + EXPECT_THAT(mock.Overloaded(1), 7); + EXPECT_THAT(mock.Overloaded(5), 9); + EXPECT_THAT(mock.Overloaded(7), 7); + + const MockConstOverload& const_mock = mock; + EXPECT_THAT(const_mock.Overloaded(1), 0); + EXPECT_THAT(const_mock.Overloaded(5), 11); + EXPECT_THAT(const_mock.Overloaded(7), 13); +} + } // namespace -// Allows the user to define his own main and then invoke gmock_main +// Allows the user to define their own main and then invoke gmock_main // from it. This might be necessary on some platforms which require // specific setup and teardown. #if GMOCK_RENAME_MAIN @@ -2634,7 +2761,6 @@ int gmock_main(int argc, char **argv) { int main(int argc, char **argv) { #endif // GMOCK_RENAME_MAIN testing::InitGoogleMock(&argc, argv); - // Ensures that the tests pass no matter what value of // --gmock_catch_leaked_mocks and --gmock_verbose the user specifies. testing::GMOCK_FLAG(catch_leaked_mocks) = true; diff --git a/googlemock/test/gmock_all_test.cc b/googlemock/test/gmock_all_test.cc index 56d6c49..e1774fb 100644 --- a/googlemock/test/gmock_all_test.cc +++ b/googlemock/test/gmock_all_test.cc @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // // Tests for Google C++ Mocking Framework (Google Mock) // diff --git a/googlemock/test/gmock_ex_test.cc b/googlemock/test/gmock_ex_test.cc index 3afed86..72eb43f 100644 --- a/googlemock/test/gmock_ex_test.cc +++ b/googlemock/test/gmock_ex_test.cc @@ -26,17 +26,18 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // Tests Google Mock's functionality that depends on exceptions. #include "gmock/gmock.h" #include "gtest/gtest.h" +#if GTEST_HAS_EXCEPTIONS namespace { using testing::HasSubstr; + using testing::internal::GoogleTestFailureException; // A type that cannot be default constructed. @@ -52,8 +53,6 @@ class MockFoo { MOCK_METHOD0(GetNonDefaultConstructible, NonDefaultConstructible()); }; -#if GTEST_HAS_EXCEPTIONS - TEST(DefaultValueTest, ThrowsRuntimeErrorWhenNoDefaultValue) { MockFoo mock; try { @@ -76,6 +75,6 @@ TEST(DefaultValueTest, ThrowsRuntimeErrorWhenNoDefaultValue) { } } -#endif } // unnamed namespace +#endif diff --git a/googlemock/test/gmock_leak_test.py b/googlemock/test/gmock_leak_test.py index 997680c..7e4b1ee 100755 --- a/googlemock/test/gmock_leak_test.py +++ b/googlemock/test/gmock_leak_test.py @@ -31,12 +31,8 @@ """Tests that leaked mock objects can be caught be Google Mock.""" -__author__ = 'wan@google.com (Zhanyong Wan)' - - import gmock_test_utils - PROGRAM_PATH = gmock_test_utils.GetTestExecutablePath('gmock_leak_test_') TEST_WITH_EXPECT_CALL = [PROGRAM_PATH, '--gtest_filter=*ExpectCall*'] TEST_WITH_ON_CALL = [PROGRAM_PATH, '--gtest_filter=*OnCall*'] diff --git a/googlemock/test/gmock_leak_test_.cc b/googlemock/test/gmock_leak_test_.cc index 1d27d22..2e095ab 100644 --- a/googlemock/test/gmock_leak_test_.cc +++ b/googlemock/test/gmock_leak_test_.cc @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // Google Mock - a framework for writing C++ mock classes. // diff --git a/googlemock/test/gmock_link2_test.cc b/googlemock/test/gmock_link2_test.cc index 4c310c3..d27ce17 100644 --- a/googlemock/test/gmock_link2_test.cc +++ b/googlemock/test/gmock_link2_test.cc @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan), vladl@google.com (Vlad Losev) + // Google Mock - a framework for writing C++ mock classes. // @@ -37,4 +36,4 @@ #define LinkTest LinkTest2 -#include "test/gmock_link_test.h" +#include "test/gmock_link_test.h" diff --git a/googlemock/test/gmock_link_test.cc b/googlemock/test/gmock_link_test.cc index 61e97d1..e7c54cc 100644 --- a/googlemock/test/gmock_link_test.cc +++ b/googlemock/test/gmock_link_test.cc @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan), vladl@google.com (Vlad Losev) + // Google Mock - a framework for writing C++ mock classes. // @@ -37,4 +36,4 @@ #define LinkTest LinkTest1 -#include "test/gmock_link_test.h" +#include "test/gmock_link_test.h" diff --git a/googlemock/test/gmock_link_test.h b/googlemock/test/gmock_link_test.h index 1f55f5b..e85f750 100644 --- a/googlemock/test/gmock_link_test.h +++ b/googlemock/test/gmock_link_test.h @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: vladl@google.com (Vlad Losev) + // Google Mock - a framework for writing C++ mock classes. // @@ -90,8 +89,10 @@ // Field // Property // ResultOf(function) +// ResultOf(callback) // Pointee // Truly(predicate) +// AddressSatisfies // AllOf // AnyOf // Not @@ -120,13 +121,15 @@ # include <errno.h> #endif -#include "gmock/internal/gmock-port.h" -#include "gtest/gtest.h" #include <iostream> #include <vector> +#include "gtest/gtest.h" +#include "gtest/internal/gtest-port.h" + using testing::_; using testing::A; +using testing::Action; using testing::AllOf; using testing::AnyOf; using testing::Assign; @@ -148,6 +151,8 @@ using testing::Invoke; using testing::InvokeArgument; using testing::InvokeWithoutArgs; using testing::IsNull; +using testing::IsSubsetOf; +using testing::IsSupersetOf; using testing::Le; using testing::Lt; using testing::Matcher; @@ -243,7 +248,7 @@ TEST(LinkTest, TestReturnVoid) { Mock mock; EXPECT_CALL(mock, VoidFromString(_)).WillOnce(Return()); - mock.VoidFromString(NULL); + mock.VoidFromString(nullptr); } // Tests the linkage of the Return action. @@ -252,7 +257,7 @@ TEST(LinkTest, TestReturn) { char ch = 'x'; EXPECT_CALL(mock, StringFromString(_)).WillOnce(Return(&ch)); - mock.StringFromString(NULL); + mock.StringFromString(nullptr); } // Tests the linkage of the ReturnNull action. @@ -260,7 +265,7 @@ TEST(LinkTest, TestReturnNull) { Mock mock; EXPECT_CALL(mock, VoidFromString(_)).WillOnce(Return()); - mock.VoidFromString(NULL); + mock.VoidFromString(nullptr); } // Tests the linkage of the ReturnRef action. @@ -269,7 +274,7 @@ TEST(LinkTest, TestReturnRef) { int n = 42; EXPECT_CALL(mock, IntRefFromString(_)).WillOnce(ReturnRef(n)); - mock.IntRefFromString(NULL); + mock.IntRefFromString(nullptr); } // Tests the linkage of the Assign action. @@ -278,7 +283,7 @@ TEST(LinkTest, TestAssign) { char ch = 'x'; EXPECT_CALL(mock, VoidFromString(_)).WillOnce(Assign(&ch, 'y')); - mock.VoidFromString(NULL); + mock.VoidFromString(nullptr); } // Tests the linkage of the SetArgPointee action. @@ -309,7 +314,7 @@ TEST(LinkTest, TestSetErrnoAndReturn) { int saved_errno = errno; EXPECT_CALL(mock, IntFromString(_)).WillOnce(SetErrnoAndReturn(1, -1)); - mock.IntFromString(NULL); + mock.IntFromString(nullptr); errno = saved_errno; } @@ -323,8 +328,8 @@ TEST(LinkTest, TestInvoke) { EXPECT_CALL(mock, VoidFromString(_)) .WillOnce(Invoke(&InvokeHelper::StaticVoidFromString)) .WillOnce(Invoke(&test_invoke_helper, &InvokeHelper::VoidFromString)); - mock.VoidFromString(NULL); - mock.VoidFromString(NULL); + mock.VoidFromString(nullptr); + mock.VoidFromString(nullptr); } // Tests the linkage of the InvokeWithoutArgs action. @@ -336,8 +341,8 @@ TEST(LinkTest, TestInvokeWithoutArgs) { .WillOnce(InvokeWithoutArgs(&InvokeHelper::StaticVoidFromVoid)) .WillOnce(InvokeWithoutArgs(&test_invoke_helper, &InvokeHelper::VoidFromVoid)); - mock.VoidFromString(NULL); - mock.VoidFromString(NULL); + mock.VoidFromString(nullptr); + mock.VoidFromString(nullptr); } // Tests the linkage of the InvokeArgument action. @@ -355,7 +360,7 @@ TEST(LinkTest, TestWithArg) { EXPECT_CALL(mock, VoidFromString(_)) .WillOnce(WithArg<0>(Invoke(&InvokeHelper::StaticVoidFromString))); - mock.VoidFromString(NULL); + mock.VoidFromString(nullptr); } // Tests the linkage of the WithArgs action. @@ -364,7 +369,7 @@ TEST(LinkTest, TestWithArgs) { EXPECT_CALL(mock, VoidFromString(_)) .WillOnce(WithArgs<0>(Invoke(&InvokeHelper::StaticVoidFromString))); - mock.VoidFromString(NULL); + mock.VoidFromString(nullptr); } // Tests the linkage of the WithoutArgs action. @@ -372,7 +377,7 @@ TEST(LinkTest, TestWithoutArgs) { Mock mock; EXPECT_CALL(mock, VoidFromString(_)).WillOnce(WithoutArgs(Return())); - mock.VoidFromString(NULL); + mock.VoidFromString(nullptr); } // Tests the linkage of the DoAll action. @@ -400,7 +405,7 @@ TEST(LinkTest, TestIgnoreResult) { Mock mock; EXPECT_CALL(mock, VoidFromString(_)).WillOnce(IgnoreResult(Return(42))); - mock.VoidFromString(NULL); + mock.VoidFromString(nullptr); } #if GTEST_HAS_EXCEPTIONS @@ -432,7 +437,7 @@ TEST(LinkTest, TestActionMacro) { Mock mock; EXPECT_CALL(mock, IntFromString(_)).WillOnce(Return1()); - mock.IntFromString(NULL); + mock.IntFromString(nullptr); } // Tests the linkage of actions created using ACTION_P macro. @@ -444,7 +449,7 @@ TEST(LinkTest, TestActionPMacro) { Mock mock; EXPECT_CALL(mock, IntFromString(_)).WillOnce(ReturnArgument(42)); - mock.IntFromString(NULL); + mock.IntFromString(nullptr); } // Tests the linkage of actions created using ACTION_P2 macro. @@ -592,6 +597,22 @@ TEST(LinkTest, TestMatcherElementsAreArray) { ON_CALL(mock, VoidFromVector(ElementsAreArray(arr))).WillByDefault(Return()); } +// Tests the linkage of the IsSubsetOf matcher. +TEST(LinkTest, TestMatcherIsSubsetOf) { + Mock mock; + char arr[] = {'a', 'b'}; + + ON_CALL(mock, VoidFromVector(IsSubsetOf(arr))).WillByDefault(Return()); +} + +// Tests the linkage of the IsSupersetOf matcher. +TEST(LinkTest, TestMatcherIsSupersetOf) { + Mock mock; + char arr[] = {'a', 'b'}; + + ON_CALL(mock, VoidFromVector(IsSupersetOf(arr))).WillByDefault(Return()); +} + // Tests the linkage of the ContainerEq matcher. TEST(LinkTest, TestMatcherContainerEq) { Mock mock; @@ -625,7 +646,7 @@ TEST(LinkTest, TestMatcherProperty) { // Tests the linkage of the ResultOf matcher. TEST(LinkTest, TestMatcherResultOf) { Matcher<char*> m = ResultOf(&InvokeHelper::StaticIntFromString, Eq(1)); - EXPECT_TRUE(m.Matches(NULL)); + EXPECT_TRUE(m.Matches(nullptr)); } // Tests the linkage of the ResultOf matcher. @@ -639,7 +660,7 @@ TEST(LinkTest, TestMatcherPointee) { // Tests the linkage of the Truly matcher. TEST(LinkTest, TestMatcherTruly) { Matcher<const char*> m = Truly(&InvokeHelper::StaticBoolFromString); - EXPECT_TRUE(m.Matches(NULL)); + EXPECT_TRUE(m.Matches(nullptr)); } // Tests the linkage of the AllOf matcher. @@ -663,7 +684,7 @@ TEST(LinkTest, TestMatcherNot) { // Tests the linkage of the MatcherCast<T>() function. TEST(LinkTest, TestMatcherCast) { Matcher<const char*> m = MatcherCast<const char*>(_); - EXPECT_TRUE(m.Matches(NULL)); + EXPECT_TRUE(m.Matches(nullptr)); } #endif // GMOCK_TEST_GMOCK_LINK_TEST_H_ diff --git a/googlemock/test/gmock_output_test.py b/googlemock/test/gmock_output_test.py index eced8a8..0527bd9 100755 --- a/googlemock/test/gmock_output_test.py +++ b/googlemock/test/gmock_output_test.py @@ -29,21 +29,19 @@ # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -"""Tests the text output of Google C++ Mocking Framework. +r"""Tests the text output of Google C++ Mocking Framework. -SYNOPSIS - gmock_output_test.py --build_dir=BUILD/DIR --gengolden - # where BUILD/DIR contains the built gmock_output_test_ file. - gmock_output_test.py --gengolden - gmock_output_test.py -""" +To update the golden file: +gmock_output_test.py --build_dir=BUILD/DIR --gengolden +where BUILD/DIR contains the built gmock_output_test_ file. +gmock_output_test.py --gengolden +gmock_output_test.py -__author__ = 'wan@google.com (Zhanyong Wan)' +""" import os import re import sys - import gmock_test_utils @@ -176,5 +174,8 @@ if __name__ == '__main__': golden_file = open(GOLDEN_PATH, 'wb') golden_file.write(output) golden_file.close() + # Suppress the error "googletest was imported but a call to its main() + # was never detected." + os._exit(0) else: gmock_test_utils.Main() diff --git a/googlemock/test/gmock_output_test_.cc b/googlemock/test/gmock_output_test_.cc index 44cba34..3955c73 100644 --- a/googlemock/test/gmock_output_test_.cc +++ b/googlemock/test/gmock_output_test_.cc @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // Tests Google Mock's output in various scenarios. This ensures that // Google Mock's messages are readable and useful. @@ -39,6 +38,12 @@ #include "gtest/gtest.h" +// Silence C4100 (unreferenced formal parameter) +#ifdef _MSC_VER +# pragma warning(push) +# pragma warning(disable:4100) +#endif + using testing::_; using testing::AnyNumber; using testing::Ge; @@ -47,6 +52,7 @@ using testing::NaggyMock; using testing::Ref; using testing::Return; using testing::Sequence; +using testing::Value; class MockFoo { public: @@ -268,6 +274,15 @@ TEST_F(GMockOutputTest, CatchesLeakedMocks) { // Both foo1 and foo2 are deliberately leaked. } +MATCHER_P2(IsPair, first, second, "") { + return Value(arg.first, first) && Value(arg.second, second); +} + +TEST_F(GMockOutputTest, PrintsMatcher) { + const testing::Matcher<int> m1 = Ge(48); + EXPECT_THAT((std::pair<int, bool>(42, true)), IsPair(m1, true)); +} + void TestCatchesLeakedMocksInAdHocTests() { MockFoo* foo = new MockFoo; @@ -280,7 +295,6 @@ void TestCatchesLeakedMocksInAdHocTests() { int main(int argc, char **argv) { testing::InitGoogleMock(&argc, argv); - // Ensures that the tests pass no matter what value of // --gmock_catch_leaked_mocks and --gmock_verbose the user specifies. testing::GMOCK_FLAG(catch_leaked_mocks) = true; @@ -289,3 +303,7 @@ int main(int argc, char **argv) { TestCatchesLeakedMocksInAdHocTests(); return RUN_ALL_TESTS(); } + +#ifdef _MSC_VER +# pragma warning(pop) +#endif diff --git a/googlemock/test/gmock_output_test_golden.txt b/googlemock/test/gmock_output_test_golden.txt index 689d5ee..dbcb211 100644 --- a/googlemock/test/gmock_output_test_golden.txt +++ b/googlemock/test/gmock_output_test_golden.txt @@ -288,6 +288,12 @@ Stack trace: [ OK ] GMockOutputTest.ExplicitActionsRunOutWithDefaultAction [ RUN ] GMockOutputTest.CatchesLeakedMocks [ OK ] GMockOutputTest.CatchesLeakedMocks +[ RUN ] GMockOutputTest.PrintsMatcher +FILE:#: Failure +Value of: (std::pair<int, bool>(42, true)) +Expected: is pair (is >= 48, true) + Actual: (42, true) (of type std::pair<int, bool>) +[ FAILED ] GMockOutputTest.PrintsMatcher [ FAILED ] GMockOutputTest.UnexpectedCall [ FAILED ] GMockOutputTest.UnexpectedCallToVoidFunction [ FAILED ] GMockOutputTest.ExcessiveCall @@ -302,9 +308,10 @@ Stack trace: [ FAILED ] GMockOutputTest.MismatchArgumentsAndWith [ FAILED ] GMockOutputTest.UnexpectedCallWithDefaultAction [ FAILED ] GMockOutputTest.ExcessiveCallWithDefaultAction +[ FAILED ] GMockOutputTest.PrintsMatcher FILE:#: ERROR: this mock object should be deleted but never is. Its address is @0x#. FILE:#: ERROR: this mock object should be deleted but never is. Its address is @0x#. FILE:#: ERROR: this mock object should be deleted but never is. Its address is @0x#. -ERROR: 3 leaked mock objects found at program exit. +ERROR: 3 leaked mock objects found at program exit. Expectations on a mock object is verified when the object is destructed. Leaking a mock means that its expectations aren't verified, which is usually a test bug. If you really intend to leak a mock, you can suppress this error using testing::Mock::AllowLeak(mock_object), or you may use a fake or stub instead of a mock. diff --git a/googlemock/test/gmock_stress_test.cc b/googlemock/test/gmock_stress_test.cc index 0e97aee..9ae0b1e 100644 --- a/googlemock/test/gmock_stress_test.cc +++ b/googlemock/test/gmock_stress_test.cc @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // Tests that Google Mock constructs can be used in a large number of // threads concurrently. @@ -38,7 +37,7 @@ namespace testing { namespace { -// From <gtest/internal/gtest-port.h>. +// From gtest-port.h. using ::testing::internal::ThreadWithParam; // The maximum number of test threads (not including helper threads) @@ -51,7 +50,7 @@ const int kRepeat = 50; class MockFoo { public: MOCK_METHOD1(Bar, int(int n)); // NOLINT - MOCK_METHOD2(Baz, char(const char* s1, const internal::string& s2)); // NOLINT + MOCK_METHOD2(Baz, char(const char* s1, const std::string& s2)); // NOLINT }; // Helper for waiting for the given thread to finish and then deleting it. @@ -211,7 +210,7 @@ void TestConcurrentCallsOnSameObject(Dummy /* dummy */) { int count1 = 0; const Helper1Param param = { &foo, &count1 }; ThreadWithParam<Helper1Param>* const t = - new ThreadWithParam<Helper1Param>(Helper1, param, NULL); + new ThreadWithParam<Helper1Param>(Helper1, param, nullptr); int count2 = 0; const Helper1Param param2 = { &foo, &count2 }; @@ -265,7 +264,7 @@ void TestPartiallyOrderedExpectationsWithThreads(Dummy /* dummy */) { foo.Bar(1); ThreadWithParam<MockFoo*>* const t = - new ThreadWithParam<MockFoo*>(Helper2, &foo, NULL); + new ThreadWithParam<MockFoo*>(Helper2, &foo, nullptr); Helper2(&foo); JoinAndDelete(t); @@ -289,8 +288,8 @@ TEST(StressTest, CanUseGMockWithThreads) { ThreadWithParam<Dummy>* threads[kTestThreads] = {}; for (int i = 0; i < kTestThreads; i++) { // Creates a thread to run the test function. - threads[i] = - new ThreadWithParam<Dummy>(test_routines[i % kRoutines], Dummy(), NULL); + threads[i] = new ThreadWithParam<Dummy>(test_routines[i % kRoutines], + Dummy(), nullptr); GTEST_LOG_(INFO) << "Thread #" << i << " running . . ."; } diff --git a/googlemock/test/gmock_test.cc b/googlemock/test/gmock_test.cc index d8d0c57..e9840a3 100644 --- a/googlemock/test/gmock_test.cc +++ b/googlemock/test/gmock_test.cc @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // Google Mock - a framework for writing C++ mock classes. // @@ -37,9 +36,11 @@ #include <string> #include "gtest/gtest.h" +#include "gtest/internal/custom/gtest.h" #if !defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_) +using testing::GMOCK_FLAG(default_mock_behavior); using testing::GMOCK_FLAG(verbose); using testing::InitGoogleMock; @@ -50,9 +51,9 @@ void TestInitGoogleMock(const Char* (&argv)[M], const Char* (&new_argv)[N], const ::std::string& expected_gmock_verbose) { const ::std::string old_verbose = GMOCK_FLAG(verbose); - int argc = M; + int argc = M - 1; InitGoogleMock(&argc, const_cast<Char**>(argv)); - ASSERT_EQ(N, argc) << "The new argv has wrong number of elements."; + ASSERT_EQ(N - 1, argc) << "The new argv has wrong number of elements."; for (int i = 0; i < N; i++) { EXPECT_STREQ(new_argv[i], argv[i]); @@ -63,149 +64,109 @@ void TestInitGoogleMock(const Char* (&argv)[M], const Char* (&new_argv)[N], } TEST(InitGoogleMockTest, ParsesInvalidCommandLine) { - const char* argv[] = { - NULL - }; + const char* argv[] = {nullptr}; - const char* new_argv[] = { - NULL - }; + const char* new_argv[] = {nullptr}; TestInitGoogleMock(argv, new_argv, GMOCK_FLAG(verbose)); } TEST(InitGoogleMockTest, ParsesEmptyCommandLine) { - const char* argv[] = { - "foo.exe", - NULL - }; + const char* argv[] = {"foo.exe", nullptr}; - const char* new_argv[] = { - "foo.exe", - NULL - }; + const char* new_argv[] = {"foo.exe", nullptr}; TestInitGoogleMock(argv, new_argv, GMOCK_FLAG(verbose)); } TEST(InitGoogleMockTest, ParsesSingleFlag) { - const char* argv[] = { - "foo.exe", - "--gmock_verbose=info", - NULL - }; + const char* argv[] = {"foo.exe", "--gmock_verbose=info", nullptr}; + + const char* new_argv[] = {"foo.exe", nullptr}; + + TestInitGoogleMock(argv, new_argv, "info"); +} - const char* new_argv[] = { - "foo.exe", - NULL - }; +TEST(InitGoogleMockTest, ParsesMultipleFlags) { + int old_default_behavior = GMOCK_FLAG(default_mock_behavior); + const wchar_t* argv[] = {L"foo.exe", L"--gmock_verbose=info", + L"--gmock_default_mock_behavior=2", nullptr}; + + const wchar_t* new_argv[] = {L"foo.exe", nullptr}; TestInitGoogleMock(argv, new_argv, "info"); + EXPECT_EQ(2, GMOCK_FLAG(default_mock_behavior)); + EXPECT_NE(2, old_default_behavior); + GMOCK_FLAG(default_mock_behavior) = old_default_behavior; } TEST(InitGoogleMockTest, ParsesUnrecognizedFlag) { - const char* argv[] = { - "foo.exe", - "--non_gmock_flag=blah", - NULL - }; - - const char* new_argv[] = { - "foo.exe", - "--non_gmock_flag=blah", - NULL - }; + const char* argv[] = {"foo.exe", "--non_gmock_flag=blah", nullptr}; + + const char* new_argv[] = {"foo.exe", "--non_gmock_flag=blah", nullptr}; TestInitGoogleMock(argv, new_argv, GMOCK_FLAG(verbose)); } TEST(InitGoogleMockTest, ParsesGoogleMockFlagAndUnrecognizedFlag) { - const char* argv[] = { - "foo.exe", - "--non_gmock_flag=blah", - "--gmock_verbose=error", - NULL - }; - - const char* new_argv[] = { - "foo.exe", - "--non_gmock_flag=blah", - NULL - }; + const char* argv[] = {"foo.exe", "--non_gmock_flag=blah", + "--gmock_verbose=error", nullptr}; + + const char* new_argv[] = {"foo.exe", "--non_gmock_flag=blah", nullptr}; TestInitGoogleMock(argv, new_argv, "error"); } TEST(WideInitGoogleMockTest, ParsesInvalidCommandLine) { - const wchar_t* argv[] = { - NULL - }; + const wchar_t* argv[] = {nullptr}; - const wchar_t* new_argv[] = { - NULL - }; + const wchar_t* new_argv[] = {nullptr}; TestInitGoogleMock(argv, new_argv, GMOCK_FLAG(verbose)); } TEST(WideInitGoogleMockTest, ParsesEmptyCommandLine) { - const wchar_t* argv[] = { - L"foo.exe", - NULL - }; + const wchar_t* argv[] = {L"foo.exe", nullptr}; - const wchar_t* new_argv[] = { - L"foo.exe", - NULL - }; + const wchar_t* new_argv[] = {L"foo.exe", nullptr}; TestInitGoogleMock(argv, new_argv, GMOCK_FLAG(verbose)); } TEST(WideInitGoogleMockTest, ParsesSingleFlag) { - const wchar_t* argv[] = { - L"foo.exe", - L"--gmock_verbose=info", - NULL - }; + const wchar_t* argv[] = {L"foo.exe", L"--gmock_verbose=info", nullptr}; + + const wchar_t* new_argv[] = {L"foo.exe", nullptr}; + + TestInitGoogleMock(argv, new_argv, "info"); +} + +TEST(WideInitGoogleMockTest, ParsesMultipleFlags) { + int old_default_behavior = GMOCK_FLAG(default_mock_behavior); + const wchar_t* argv[] = {L"foo.exe", L"--gmock_verbose=info", + L"--gmock_default_mock_behavior=2", nullptr}; - const wchar_t* new_argv[] = { - L"foo.exe", - NULL - }; + const wchar_t* new_argv[] = {L"foo.exe", nullptr}; TestInitGoogleMock(argv, new_argv, "info"); + EXPECT_EQ(2, GMOCK_FLAG(default_mock_behavior)); + EXPECT_NE(2, old_default_behavior); + GMOCK_FLAG(default_mock_behavior) = old_default_behavior; } TEST(WideInitGoogleMockTest, ParsesUnrecognizedFlag) { - const wchar_t* argv[] = { - L"foo.exe", - L"--non_gmock_flag=blah", - NULL - }; - - const wchar_t* new_argv[] = { - L"foo.exe", - L"--non_gmock_flag=blah", - NULL - }; + const wchar_t* argv[] = {L"foo.exe", L"--non_gmock_flag=blah", nullptr}; + + const wchar_t* new_argv[] = {L"foo.exe", L"--non_gmock_flag=blah", nullptr}; TestInitGoogleMock(argv, new_argv, GMOCK_FLAG(verbose)); } TEST(WideInitGoogleMockTest, ParsesGoogleMockFlagAndUnrecognizedFlag) { - const wchar_t* argv[] = { - L"foo.exe", - L"--non_gmock_flag=blah", - L"--gmock_verbose=error", - NULL - }; - - const wchar_t* new_argv[] = { - L"foo.exe", - L"--non_gmock_flag=blah", - NULL - }; + const wchar_t* argv[] = {L"foo.exe", L"--non_gmock_flag=blah", + L"--gmock_verbose=error", nullptr}; + + const wchar_t* new_argv[] = {L"foo.exe", L"--non_gmock_flag=blah", nullptr}; TestInitGoogleMock(argv, new_argv, "error"); } diff --git a/googlemock/test/gmock_test_utils.py b/googlemock/test/gmock_test_utils.py index 20e3d3d..7dc4e11 100755 --- a/googlemock/test/gmock_test_utils.py +++ b/googlemock/test/gmock_test_utils.py @@ -1,5 +1,3 @@ -#!/usr/bin/env python -# # Copyright 2006, Google Inc. # All rights reserved. # @@ -31,24 +29,22 @@ """Unit test utilities for Google C++ Mocking Framework.""" -__author__ = 'wan@google.com (Zhanyong Wan)' - import os import sys - # Determines path to gtest_test_utils and imports it. SCRIPT_DIR = os.path.dirname(__file__) or '.' # isdir resolves symbolic links. -gtest_tests_util_dir = os.path.join(SCRIPT_DIR, '../gtest/test') +gtest_tests_util_dir = os.path.join(SCRIPT_DIR, '../../googletest/test') if os.path.isdir(gtest_tests_util_dir): GTEST_TESTS_UTIL_DIR = gtest_tests_util_dir else: - GTEST_TESTS_UTIL_DIR = os.path.join(SCRIPT_DIR, '../../gtest/test') - + GTEST_TESTS_UTIL_DIR = os.path.join(SCRIPT_DIR, '../../googletest/test') sys.path.append(GTEST_TESTS_UTIL_DIR) -import gtest_test_utils # pylint: disable-msg=C6204 + +# pylint: disable=C6204 +import gtest_test_utils def GetSourceDir(): |