Update to googletest 1.10.0

This commit is contained in:
Sebastian Messmer 2019-10-13 19:06:54 +07:00
parent 6164453c77
commit 7d8cdbba40
268 changed files with 19921 additions and 39236 deletions

2
vendor/README vendored
View File

@ -1,5 +1,5 @@
This directory contains external projects, taken from the following locations:
googletest: https://github.com/google/googletest/tree/release-1.8.1
googletest: https://github.com/google/googletest/tree/release-1.10.0
spdlog: https://github.com/gabime/spdlog/tree/v1.4.2/include/spdlog
cryptopp: https://github.com/weidai11/cryptopp/tree/CRYPTOPP_8_2_0
- changed: added CMakeLists.txt and cryptopp-config.cmake from https://github.com/noloader/cryptopp-cmake/tree/CRYPTOPP_8_2_0

4
vendor/googletest/gtest/.clang-format vendored Normal file
View File

@ -0,0 +1,4 @@
# Run manually to reformat a file:
# clang-format -i --style=file <file>
Language: Cpp
BasedOnStyle: Google

84
vendor/googletest/gtest/.gitignore vendored Normal file
View File

@ -0,0 +1,84 @@
# Ignore CI build directory
build/
xcuserdata
cmake-build-debug/
.idea/
bazel-bin
bazel-genfiles
bazel-googletest
bazel-out
bazel-testlogs
# python
*.pyc
# Visual Studio files
.vs
*.sdf
*.opensdf
*.VC.opendb
*.suo
*.user
_ReSharper.Caches/
Win32-Debug/
Win32-Release/
x64-Debug/
x64-Release/
# Ignore autoconf / automake files
Makefile.in
aclocal.m4
configure
build-aux/
autom4te.cache/
googletest/m4/libtool.m4
googletest/m4/ltoptions.m4
googletest/m4/ltsugar.m4
googletest/m4/ltversion.m4
googletest/m4/lt~obsolete.m4
googlemock/m4
# Ignore generated directories.
googlemock/fused-src/
googletest/fused-src/
# macOS files
.DS_Store
googletest/.DS_Store
googletest/xcode/.DS_Store
# Ignore cmake generated directories and files.
CMakeFiles
CTestTestfile.cmake
Makefile
cmake_install.cmake
googlemock/CMakeFiles
googlemock/CTestTestfile.cmake
googlemock/Makefile
googlemock/cmake_install.cmake
googlemock/gtest
/bin
/googlemock/gmock.dir
/googlemock/gmock_main.dir
/googlemock/RUN_TESTS.vcxproj.filters
/googlemock/RUN_TESTS.vcxproj
/googlemock/INSTALL.vcxproj.filters
/googlemock/INSTALL.vcxproj
/googlemock/gmock_main.vcxproj.filters
/googlemock/gmock_main.vcxproj
/googlemock/gmock.vcxproj.filters
/googlemock/gmock.vcxproj
/googlemock/gmock.sln
/googlemock/ALL_BUILD.vcxproj.filters
/googlemock/ALL_BUILD.vcxproj
/lib
/Win32
/ZERO_CHECK.vcxproj.filters
/ZERO_CHECK.vcxproj
/RUN_TESTS.vcxproj.filters
/RUN_TESTS.vcxproj
/INSTALL.vcxproj.filters
/INSTALL.vcxproj
/googletest-distribution.sln
/CMakeCache.txt
/ALL_BUILD.vcxproj.filters
/ALL_BUILD.vcxproj

73
vendor/googletest/gtest/.travis.yml vendored Normal file
View File

@ -0,0 +1,73 @@
# Build matrix / environment variable are explained on:
# https://docs.travis-ci.com/user/customizing-the-build/
# This file can be validated on:
# http://lint.travis-ci.org/
language: cpp
# Define the matrix explicitly, manually expanding the combinations of (os, compiler, env).
# It is more tedious, but grants us far more flexibility.
matrix:
include:
- os: linux
before_install: chmod -R +x ./ci/*platformio.sh
install: ./ci/install-platformio.sh
script: ./ci/build-platformio.sh
- os: linux
dist: xenial
compiler: gcc
install: ./ci/install-linux.sh && ./ci/log-config.sh
script: ./ci/build-linux-bazel.sh
- os: linux
dist: xenial
compiler: clang
install: ./ci/install-linux.sh && ./ci/log-config.sh
script: ./ci/build-linux-bazel.sh
- os: linux
compiler: gcc
env: BUILD_TYPE=Debug VERBOSE=1 CXX_FLAGS=-std=c++11
- os: linux
compiler: clang
env: BUILD_TYPE=Release VERBOSE=1 CXX_FLAGS=-std=c++11 -Wgnu-zero-variadic-macro-arguments
- os: linux
compiler: clang
env: BUILD_TYPE=Release VERBOSE=1 CXX_FLAGS=-std=c++11 NO_EXCEPTION=ON NO_RTTI=ON COMPILER_IS_GNUCXX=ON
- os: osx
compiler: gcc
env: BUILD_TYPE=Release VERBOSE=1 CXX_FLAGS=-std=c++11 HOMEBREW_LOGS=~/homebrew-logs HOMEBREW_TEMP=~/homebrew-temp
- os: osx
compiler: clang
env: BUILD_TYPE=Release VERBOSE=1 CXX_FLAGS=-std=c++11 HOMEBREW_LOGS=~/homebrew-logs HOMEBREW_TEMP=~/homebrew-temp
# These are the install and build (script) phases for the most common entries in the matrix. They could be included
# in each entry in the matrix, but that is just repetitive.
install:
- ./ci/install-${TRAVIS_OS_NAME}.sh
- . ./ci/env-${TRAVIS_OS_NAME}.sh
- ./ci/log-config.sh
script: ./ci/travis.sh
# This section installs the necessary dependencies.
addons:
apt:
# List of whitelisted in travis packages for ubuntu-precise can be found here:
# https://github.com/travis-ci/apt-package-whitelist/blob/master/ubuntu-precise
# List of whitelisted in travis apt-sources:
# https://github.com/travis-ci/apt-source-whitelist/blob/master/ubuntu.json
sources:
- ubuntu-toolchain-r-test
- llvm-toolchain-precise-3.9
packages:
- g++-4.9
- clang-3.9
update: true
homebrew:
packages:
- ccache
- gcc@4.9
- llvm@4
update: true
notifications:
email: false

View File

@ -28,22 +28,17 @@
# (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)
load("@rules_cc//cc:defs.bzl", "cc_library", "cc_test")
package(default_visibility = ["//visibility:public"])
licenses(["notice"])
config_setting(
name = "windows",
values = {"cpu": "x64_windows"},
)
config_setting(
name = "windows_msvc",
values = {"cpu": "x64_windows_msvc"},
constraint_values = ["@bazel_tools//platforms:windows"],
)
config_setting(
@ -51,6 +46,13 @@ config_setting(
values = {"define": "absl=1"},
)
# Library that defines the FRIEND_TEST macro.
cc_library(
name = "gtest_prod",
hdrs = ["googletest/include/gtest/gtest_prod.h"],
includes = ["googletest/include"],
)
# Google Test including Google Mock
cc_library(
name = "gtest",
@ -73,21 +75,18 @@ cc_library(
"googletest/include/gtest/*.h",
"googlemock/include/gmock/*.h",
]),
copts = select(
{
":windows": [],
":windows_msvc": [],
"//conditions:default": ["-pthread"],
},
),
defines = select(
{
":has_absl": [
"GTEST_HAS_ABSL=1",
],
"//conditions:default": [],
},
),
copts = select({
":windows": [],
"//conditions:default": ["-pthread"],
}),
defines = select({
":has_absl": ["GTEST_HAS_ABSL=1"],
"//conditions:default": [],
}),
features = select({
":windows": ["windows_export_all_symbols"],
"//conditions:default": [],
}),
includes = [
"googlemock",
"googlemock/include",
@ -96,31 +95,28 @@ cc_library(
],
linkopts = select({
":windows": [],
":windows_msvc": [],
"//conditions:default": [
"-pthread",
],
"//conditions:default": ["-pthread"],
}),
deps = select({
":has_absl": [
"@com_google_absl//absl/debugging:failure_signal_handler",
"@com_google_absl//absl/debugging:stacktrace",
"@com_google_absl//absl/debugging:symbolize",
"@com_google_absl//absl/strings",
"@com_google_absl//absl/types:optional",
"@com_google_absl//absl/types:variant",
],
"//conditions:default": [],
}),
deps = select(
{
":has_absl": [
"@com_google_absl//absl/debugging:failure_signal_handler",
"@com_google_absl//absl/debugging:stacktrace",
"@com_google_absl//absl/debugging:symbolize",
"@com_google_absl//absl/strings",
"@com_google_absl//absl/types:optional",
"@com_google_absl//absl/types:variant",
],
"//conditions:default": [],
},
),
)
cc_library(
name = "gtest_main",
srcs = [
"googlemock/src/gmock_main.cc",
],
srcs = ["googlemock/src/gmock_main.cc"],
features = select({
":windows": ["windows_export_all_symbols"],
"//conditions:default": [],
}),
deps = [":gtest"],
)
@ -139,14 +135,18 @@ cc_library(
"googletest/samples/sample3-inl.h",
"googletest/samples/sample4.h",
],
features = select({
":windows": ["windows_export_all_symbols"],
"//conditions:default": [],
}),
)
cc_test(
name = "gtest_samples",
size = "small",
#All Samples except:
#sample9 ( main )
#sample10 (main and takes a command line option and needs to be separate)
# All Samples except:
# sample9 (main)
# sample10 (main and takes a command line option and needs to be separate)
srcs = [
"googletest/samples/sample1_unittest.cc",
"googletest/samples/sample2_unittest.cc",
@ -157,6 +157,7 @@ cc_test(
"googletest/samples/sample7_unittest.cc",
"googletest/samples/sample8_unittest.cc",
],
linkstatic = 0,
deps = [
"gtest_sample_lib",
":gtest_main",
@ -174,7 +175,5 @@ cc_test(
name = "sample10_unittest",
size = "small",
srcs = ["googletest/samples/sample10_unittest.cc"],
deps = [
":gtest",
],
deps = [":gtest"],
)

View File

@ -1,3 +1,6 @@
# Note: CMake support is community-based. The maintainers do not use CMake
# internally.
cmake_minimum_required(VERSION 2.8.8)
if (POLICY CMP0048)
@ -5,7 +8,17 @@ if (POLICY CMP0048)
endif (POLICY CMP0048)
project(googletest-distribution)
set(GOOGLETEST_VERSION 1.9.0)
set(GOOGLETEST_VERSION 1.10.0)
if (CMAKE_VERSION VERSION_LESS "3.1")
add_definitions(-std=c++11)
else()
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
if(NOT CYGWIN)
set(CMAKE_CXX_EXTENSIONS OFF)
endif()
endif()
enable_testing()

View File

@ -2,16 +2,16 @@
## Contributor License Agreements
We'd love to accept your patches! Before we can take them, we
have to jump a couple of legal hurdles.
We'd love to accept your patches! Before we can take them, we have to jump a
couple of legal hurdles.
Please fill out either the individual or corporate Contributor License Agreement
(CLA).
* If you are an individual writing original source code and you're sure you
* 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](https://developers.google.com/open-source/cla/individual).
* If you work for a company that wants to allow you to contribute your work,
* If you work for a company that wants to allow you to contribute your work,
then you'll need to sign a
[corporate CLA](https://developers.google.com/open-source/cla/corporate).
@ -20,141 +20,123 @@ instructions for how to sign and return it. Once we receive it, we'll be able to
accept your pull requests.
## Are you a Googler?
If you are a Googler, you can either create an internal change or work on GitHub directly.
If you are a Googler, please make an attempt to submit an internal change rather
than a GitHub Pull Request. If you are not able to submit an internal change a
PR is acceptable as an alternative.
## Contributing A Patch
1. Submit an issue describing your proposed change to the
[issue tracker](https://github.com/google/googletest).
1. 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. If your proposed change is accepted, and you haven't already done so, sign a
Contributor License Agreement (see details above).
1. Fork the desired repo, develop and test your code changes.
1. Ensure that your code adheres to the existing style in the sample to which
you are contributing.
1. Ensure that your code has an appropriate set of unit tests which all pass.
1. Submit a pull request.
1. Submit an issue describing your proposed change to the
[issue tracker](https://github.com/google/googletest).
2. 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.
3. 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.
4. If your proposed change is accepted, and you haven't already done so, sign a
Contributor License Agreement (see details above).
5. Fork the desired repo, develop and test your code changes.
6. Ensure that your code adheres to the existing style in the sample to which
you are contributing.
7. Ensure that your code has an appropriate set of unit tests which all pass.
8. Submit a pull request.
## The Google Test and Google Mock Communities ##
## The Google Test and Google Mock Communities
The Google Test community exists primarily through the
[discussion group](http://groups.google.com/group/googletestframework)
and the GitHub repository.
Likewise, the Google Mock community exists primarily through their own
[discussion group](http://groups.google.com/group/googlemock).
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.
[discussion group](http://groups.google.com/group/googletestframework) and the
GitHub repository. Likewise, the Google Mock community exists primarily through
their own [discussion group](http://groups.google.com/group/googlemock). 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 ###
### 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
Test 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
Showing courtesy and respect to others is a vital part of the Google culture,
and we strongly encourage everyone participating in Google Test 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.
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.
As always, discuss Google Test in the official GoogleTest discussion group.
You don't have to actually submit code in order to sign up. Your participation
As always, discuss Google Test in the official GoogleTest discussion group. You
don't have to actually submit code in order to sign up. Your participation
itself is a valuable contribution.
## 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://google.github.io/styleguide/cppguide.html).
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://google.github.io/styleguide/cppguide.html). Use
[.clang-format](https://github.com/google/googletest/blob/master/.clang-format)
to check your formatting
## Requirements for Contributors ###
## Requirements for Contributors
If you plan to contribute a patch, you need to build Google Test,
Google Mock, and their own tests from a git checkout, which has
further requirements:
If you plan to contribute a patch, you need to build Google Test, Google Mock,
and their own tests from a git checkout, which has further requirements:
* [Python](https://www.python.org/) v2.3 or newer (for running some of
the tests and re-generating certain source files from templates)
* [CMake](https://cmake.org/) v2.6.4 or newer
* [GNU Build System](https://en.wikipedia.org/wiki/GNU_Build_System)
including automake (>= 1.9), autoconf (>= 2.59), and
libtool / libtoolize.
* [Python](https://www.python.org/) v2.3 or newer (for running some of the
tests and re-generating certain source files from templates)
* [CMake](https://cmake.org/) v2.6.4 or newer
## Developing Google Test ##
## Developing Google Test and Google Mock
This section discusses how to make your own changes to Google Test.
This section discusses how to make your own changes to the Google Test project.
### Testing Google Test Itself ###
### Testing Google Test and Google Mock Themselves
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 can use CMake:
functionality, you'll want to compile and run Google Test and GoogleMock's own
tests. For that you can use CMake:
mkdir mybuild
cd mybuild
cmake -Dgtest_build_tests=ON ${GTEST_DIR}
cmake -Dgtest_build_tests=ON -Dgmock_build_tests=ON ${GTEST_REPO_DIR}
Make sure you have Python installed, as some of Google Test's tests
are written in Python. If the cmake command complains about not being
able to find Python (`Could NOT find PythonInterp (missing:
PYTHON_EXECUTABLE)`), try telling it explicitly where your Python
executable can be found:
To choose between building only Google Test or Google Mock, you may modify your
cmake command to be one of each
cmake -DPYTHON_EXECUTABLE=path/to/python -Dgtest_build_tests=ON ${GTEST_DIR}
cmake -Dgtest_build_tests=ON ${GTEST_DIR} # sets up Google Test tests
cmake -Dgmock_build_tests=ON ${GMOCK_DIR} # sets up Google Mock tests
Next, you can build Google Test and all of its own tests. On \*nix,
this is usually done by 'make'. To run the tests, do
Make sure you have Python installed, as some of Google Test's tests are written
in Python. If the cmake command complains about not being able to find Python
(`Could NOT find PythonInterp (missing: PYTHON_EXECUTABLE)`), try telling it
explicitly where your Python executable can be found:
cmake -DPYTHON_EXECUTABLE=path/to/python ...
Next, you can build Google Test and / or Google Mock and all desired tests. On
\*nix, this is usually done by
make
To run the tests, do
make test
All tests should pass.
### Regenerating Source Files ##
### Regenerating Source Files
Some of Google Test's source files are generated from templates (not
in the C++ sense) using a script.
For example, the
file include/gtest/internal/gtest-type-util.h.pump is used to generate
Some of Google Test's source files are generated from templates (not in the C++
sense) using a script. For example, the file
include/gtest/internal/gtest-type-util.h.pump is used to generate
gtest-type-util.h in the same directory.
You don't need to worry about regenerating the source files
unless you need to modify them. You would then modify the
corresponding `.pump` files and run the '[pump.py](googletest/scripts/pump.py)'
generator script. See the [Pump Manual](googletest/docs/PumpManual.md).
## 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.
You don't need to worry about regenerating the source files unless you need to
modify them. You would then modify the corresponding `.pump` files and run the
'[pump.py](googletest/scripts/pump.py)' generator script. See the
[Pump Manual](googletest/docs/pump_manual.md).

View File

@ -1,14 +0,0 @@
## Process this file with automake to produce Makefile.in
ACLOCAL_AMFLAGS = -I m4
AUTOMAKE_OPTIONS = foreign
# Build . before src so that our all-local and clean-local hooks kicks in at
# the right time.
SUBDIRS = googletest googlemock
EXTRA_DIST = \
BUILD.bazel \
CMakeLists.txt \
README.md \
WORKSPACE

View File

@ -1,79 +1,97 @@
# Google Test
# Google Test #
#### OSS Builds Status:
[![Build Status](https://travis-ci.org/google/googletest.svg?branch=master)](https://travis-ci.org/google/googletest)
[![Build Status](https://api.travis-ci.org/google/googletest.svg?branch=master)](https://travis-ci.org/google/googletest)
[![Build status](https://ci.appveyor.com/api/projects/status/4o38plt0xbo1ubc8/branch/master?svg=true)](https://ci.appveyor.com/project/GoogleTestAppVeyor/googletest/branch/master)
**Future Plans**:
* 1.8.x Release - the 1.8.x will be the last release that works with pre-C++11 compilers. The 1.8.x will not accept any requests for any new features and any bugfix requests will only be accepted if proven "critical"
* Post 1.8.x - work to improve/cleanup/pay technical debt. When this work is completed there will be a 1.9.x tagged release
* Post 1.9.x googletest will follow [Abseil Live at Head philosophy](https://abseil.io/about/philosophy)
### Future Plans
#### 1.8.x Release:
Welcome to **Google Test**, Google's C++ test framework!
[the 1.8.x](https://github.com/google/googletest/releases/tag/release-1.8.1) is
the last release that works with pre-C++11 compilers. The 1.8.x will not accept
any requests for any new features and any bugfix requests will only be accepted
if proven "critical"
This repository is a merger of the formerly separate GoogleTest and
GoogleMock projects. These were so closely related that it makes sense to
maintain and release them together.
#### Post 1.8.x:
Please see the project page above for more information as well as the
mailing list for questions, discussions, and development. There is
also an IRC channel on [OFTC](https://webchat.oftc.net/) (irc.oftc.net) #gtest available. Please
join us!
On-going work to improve/cleanup/pay technical debt. When this work is completed
there will be a 1.9.x tagged release
Getting started information for **Google Test** is available in the
#### Post 1.9.x
Post 1.9.x googletest will follow
[Abseil Live at Head philosophy](https://abseil.io/about/philosophy)
## Welcome to **Google Test**, Google's C++ test framework!
This repository is a merger of the formerly separate GoogleTest and GoogleMock
projects. These were so closely related that it makes sense to maintain and
release them together.
Please subscribe to the mailing list at googletestframework@googlegroups.com for
questions, discussions, and development.
### Getting started:
The information for **Google Test** is available in the
[Google Test Primer](googletest/docs/primer.md) documentation.
**Google Mock** is an extension to Google Test for writing and using C++ mock
classes. See the separate [Google Mock documentation](googlemock/README.md).
classes. See the separate [Google Mock documentation](googlemock/README.md).
More detailed documentation for googletest (including build instructions) are
in its interior [googletest/README.md](googletest/README.md) file.
More detailed documentation for googletest is in its interior
[googletest/README.md](googletest/README.md) file.
## Features ##
## Features
* An [xUnit](https://en.wikipedia.org/wiki/XUnit) test framework.
* Test discovery.
* A rich set of assertions.
* User-defined assertions.
* Death tests.
* Fatal and non-fatal failures.
* Value-parameterized tests.
* Type-parameterized tests.
* Various options for running the tests.
* XML test report generation.
* An [xUnit](https://en.wikipedia.org/wiki/XUnit) test framework.
* Test discovery.
* A rich set of assertions.
* User-defined assertions.
* Death tests.
* Fatal and non-fatal failures.
* Value-parameterized tests.
* Type-parameterized tests.
* Various options for running the tests.
* XML test report generation.
## Platforms ##
## Platforms
Google test has been used on a variety of platforms:
* Linux
* Mac OS X
* Windows
* Cygwin
* MinGW
* Windows Mobile
* Symbian
* Linux
* Mac OS X
* Windows
* Cygwin
* MinGW
* Windows Mobile
* Symbian
* PlatformIO
## Who Is Using Google Test? ##
## Who Is Using Google Test?
In addition to many internal projects at Google, Google Test is also used by
the following notable projects:
In addition to many internal projects at Google, Google Test is also used by the
following notable projects:
* The [Chromium projects](http://www.chromium.org/) (behind the Chrome
browser and Chrome OS).
* The [LLVM](http://llvm.org/) compiler.
* [Protocol Buffers](https://github.com/google/protobuf), Google's data
* The [Chromium projects](http://www.chromium.org/) (behind the Chrome browser
and Chrome OS).
* The [LLVM](http://llvm.org/) compiler.
* [Protocol Buffers](https://github.com/google/protobuf), Google's data
interchange format.
* The [OpenCV](http://opencv.org/) computer vision library.
* [tiny-dnn](https://github.com/tiny-dnn/tiny-dnn): header only, dependency-free deep learning framework in C++11.
* The [OpenCV](http://opencv.org/) computer vision library.
* [tiny-dnn](https://github.com/tiny-dnn/tiny-dnn): header only,
dependency-free deep learning framework in C++11.
## Related Open Source Projects ##
## Related Open Source Projects
[GTest Runner](https://github.com/nholthaus/gtest-runner) is a Qt5 based automated test-runner and Graphical User Interface with powerful features for Windows and Linux platforms.
[GTest Runner](https://github.com/nholthaus/gtest-runner) is a Qt5 based
automated test-runner and Graphical User Interface with powerful features for
Windows and Linux platforms.
[Google Test UI](https://github.com/ospector/gtest-gbar) is test runner that runs
your test binary, allows you to track its progress via a progress bar, and
[Google Test UI](https://github.com/ospector/gtest-gbar) is test runner that
runs your test binary, allows you to track its progress via a progress bar, and
displays a list of test failures. Clicking on one shows failure text. Google
Test UI is written in C#.
@ -85,46 +103,32 @@ result output. If your test runner understands TAP, you may find it useful.
[gtest-parallel](https://github.com/google/gtest-parallel) is a test runner that
runs tests from your binary in parallel to provide significant speed-up.
[GoogleTest Adapter](https://marketplace.visualstudio.com/items?itemName=DavidSchuldenfrei.gtest-adapter) is a VS Code extension allowing to view Google Tests in a tree view, and run/debug your tests.
[GoogleTest Adapter](https://marketplace.visualstudio.com/items?itemName=DavidSchuldenfrei.gtest-adapter)
is a VS Code extension allowing to view Google Tests in a tree view, and
run/debug your tests.
## Requirements ##
## Requirements
Google Test is designed to have fairly minimal requirements to build
and use with your projects, but there are some. Currently, we support
Linux, Windows, Mac OS X, and Cygwin. We will also make our best
effort to support other platforms (e.g. Solaris, AIX, and z/OS).
However, since core members of the Google Test project have no access
to these platforms, Google Test may have outstanding issues there. If
you notice any problems on your platform, please notify
[googletestframework@googlegroups.com](https://groups.google.com/forum/#!forum/googletestframework). Patches for fixing them are
even more welcome!
Google Test is designed to have fairly minimal requirements to build and use
with your projects, but there are some. If you notice any problems on your
platform, please notify
[googletestframework@googlegroups.com](https://groups.google.com/forum/#!forum/googletestframework).
Patches for fixing them are welcome!
### Linux Requirements ###
### Build Requirements
These are the base requirements to build and use Google Test from a source
package (as described below):
package:
* GNU-compatible Make or gmake
* POSIX-standard shell
* POSIX(-2) Regular Expressions (regex.h)
* A C++98-standard-compliant compiler
* [Bazel](https://bazel.build/) or [CMake](https://cmake.org/). NOTE: Bazel is
the build system that googletest is using internally and tests against.
CMake is community-supported.
### Windows Requirements ###
* Microsoft Visual C++ 2015 or newer
### Cygwin Requirements ###
* Cygwin v1.5.25-14 or newer
### Mac OS X Requirements ###
* Mac OS X v10.4 Tiger or newer
* Xcode Developer Tools
* a C++11-standard-compliant compiler
## Contributing change
Please read the [`CONTRIBUTING.md`](CONTRIBUTING.md) for details on
how to contribute to this project.
Please read the [`CONTRIBUTING.md`](CONTRIBUTING.md) for details on how to
contribute to this project.
Happy testing!

View File

@ -1,8 +1,23 @@
workspace(name = "com_google_googletest")
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
# Abseil
http_archive(
name = "com_google_absl",
urls = ["https://github.com/abseil/abseil-cpp/archive/master.zip"],
strip_prefix = "abseil-cpp-master",
)
http_archive(
name = "rules_cc",
strip_prefix = "rules_cc-master",
urls = ["https://github.com/bazelbuild/rules_cc/archive/master.zip"],
)
http_archive(
name = "rules_python",
strip_prefix = "rules_python-master",
urls = ["https://github.com/bazelbuild/rules_python/archive/master.zip"],
)

View File

@ -6,27 +6,34 @@ environment:
matrix:
- compiler: msvc-15-seh
generator: "Visual Studio 15 2017"
build_system: cmake
APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2017
- compiler: msvc-15-seh
generator: "Visual Studio 15 2017 Win64"
build_system: cmake
APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2017
enabled_on_pr: yes
- compiler: msvc-15-seh
build_system: bazel
APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2017
enabled_on_pr: yes
- compiler: msvc-14-seh
build_system: cmake
generator: "Visual Studio 14 2015"
enabled_on_pr: yes
- compiler: msvc-14-seh
build_system: cmake
generator: "Visual Studio 14 2015 Win64"
- compiler: gcc-5.3.0-posix
generator: "MinGW Makefiles"
cxx_path: 'C:\mingw-w64\i686-5.3.0-posix-dwarf-rt_v4-rev0\mingw32\bin'
- compiler: gcc-6.3.0-posix
build_system: cmake
generator: "MinGW Makefiles"
cxx_path: 'C:\mingw-w64\i686-6.3.0-posix-dwarf-rt_v5-rev1\mingw32\bin'
enabled_on_pr: yes
configuration:
- Debug
@ -38,6 +45,8 @@ install:
- ps: |
Write-Output "Compiler: $env:compiler"
Write-Output "Generator: $env:generator"
Write-Output "Env:Configuation: $env:configuration"
Write-Output "Env: $env"
if (-not (Test-Path env:APPVEYOR_PULL_REQUEST_NUMBER)) {
Write-Output "This is *NOT* a pull request build"
} else {
@ -47,20 +56,44 @@ install:
}
}
# git bash conflicts with MinGW makefiles
if ($env:generator -eq "MinGW Makefiles") {
$env:path = $env:path.replace("C:\Program Files\Git\usr\bin;", "")
if ($env:cxx_path -ne "") {
$env:path += ";$env:cxx_path"
# install Bazel
if ($env:build_system -eq "bazel") {
appveyor DownloadFile https://github.com/bazelbuild/bazel/releases/download/0.28.1/bazel-0.28.1-windows-x86_64.exe -FileName bazel.exe
}
if ($env:build_system -eq "cmake") {
# git bash conflicts with MinGW makefiles
if ($env:generator -eq "MinGW Makefiles") {
$env:path = $env:path.replace("C:\Program Files\Git\usr\bin;", "")
if ($env:cxx_path -ne "") {
$env:path += ";$env:cxx_path"
}
}
}
before_build:
- ps: |
$env:root=$env:APPVEYOR_BUILD_FOLDER
Write-Output "env:root: $env:root"
build_script:
- ps: |
# Only enable some builds for pull requests, the AppVeyor queue is too long.
if ((Test-Path env:APPVEYOR_PULL_REQUEST_NUMBER) -And (-not (Test-Path env:enabled_on_pr) -or $env:enabled_on_pr -ne "yes")) {
return
} else {
# special case - build with Bazel
if ($env:build_system -eq "bazel") {
& $env:root\bazel.exe build -c opt //:gtest_samples
if ($LastExitCode -eq 0) { # bazel writes to StdErr and PowerShell interprets it as an error
$host.SetShouldExit(0)
} else { # a real error
throw "Exec: $ErrorMessage"
}
return
}
}
# by default build with CMake
md _build -Force | Out-Null
cd _build
@ -89,12 +122,25 @@ test_script:
if ((Test-Path env:APPVEYOR_PULL_REQUEST_NUMBER) -And (-not (Test-Path env:enabled_on_pr) -or $env:enabled_on_pr -ne "yes")) {
return
}
if ($env:generator -eq "MinGW Makefiles") {
return # No test available for MinGW
if ($env:build_system -eq "bazel") {
# special case - testing with Bazel
& $env:root\bazel.exe test //:gtest_samples
if ($LastExitCode -eq 0) { # bazel writes to StdErr and PowerShell interprets it as an error
$host.SetShouldExit(0)
} else { # a real error
throw "Exec: $ErrorMessage"
}
}
& ctest -C $env:configuration --timeout 600 --output-on-failure
if ($LastExitCode -ne 0) {
throw "Exec: $ErrorMessage"
if ($env:build_system -eq "cmake") {
# built with CMake - test with CTest
if ($env:generator -eq "MinGW Makefiles") {
return # No test available for MinGW
}
& ctest -C $env:configuration --timeout 600 --output-on-failure
if ($LastExitCode -ne 0) {
throw "Exec: $ErrorMessage"
}
}
artifacts:
@ -102,3 +148,7 @@ artifacts:
name: logs
- path: '_build/Testing/**/*.xml'
name: test_results
- path: 'bazel-testlogs/**/test.log'
name: test_logs
- path: 'bazel-testlogs/**/test.xml'
name: test_results

View File

@ -31,6 +31,7 @@
set -e
bazel version
bazel build --curses=no //...:all
bazel test --curses=no //...:all
bazel test --curses=no //...:all --define absl=1

View File

@ -0,0 +1,2 @@
# run PlatformIO builds
platformio run

View File

@ -34,7 +34,14 @@
#
# TODO() - we can check if this is being sourced using $BASH_VERSION and $BASH_SOURCE[0] != ${0}.
#
if [ "${TRAVIS_OS_NAME}" = "linux" ]; then
if [ "$CXX" = "clang++" ]; then export CXX="clang++-3.9" CC="clang-3.9"; fi
if [ "${TRAVIS_OS_NAME}" = "osx" ]; then
if [ "$CXX" = "clang++" ]; then
# $PATH needs to be adjusted because the llvm tap doesn't install the
# package to /usr/local/bin, etc, like the gcc tap does.
# See: https://github.com/Homebrew/legacy-homebrew/issues/29733
clang_version=3.9
export PATH="/usr/local/opt/llvm@${clang_version}/bin:$PATH";
fi
fi

View File

@ -36,4 +36,5 @@ if [ "${TRAVIS_OS_NAME}" != "osx" ]; then
exit 0
fi
brew install ccache
brew update
brew install ccache gcc@4.9

View File

@ -0,0 +1,5 @@
# install PlatformIO
sudo pip install -U platformio
# update PlatformIO
platformio update

View File

@ -1,16 +0,0 @@
AC_INIT([Google C++ Mocking and Testing Frameworks],
[1.8.0],
[googlemock@googlegroups.com],
[googletest])
# Provide various options to initialize the Autoconf and configure processes.
AC_PREREQ([2.59])
AC_CONFIG_SRCDIR([./README.md])
AC_CONFIG_AUX_DIR([build-aux])
AC_CONFIG_FILES([Makefile])
AC_CONFIG_SUBDIRS([googletest googlemock])
AM_INIT_AUTOMAKE
# Output the generated files. No further autoconf macros may be used.
AC_OUTPUT

View File

@ -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 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

View File

@ -1,4 +1,7 @@
########################################################################
# Note: CMake support is community-based. The maintainers do not use CMake
# internally.
#
# CMake build script for Google Mock.
#
# To run the tests for Google Mock itself on Linux, use 'make test' or
@ -49,7 +52,7 @@ endif()
# targets to the current scope. We are placing Google Test's binary
# directory in a subdirectory of our own as VC compilation may break
# if they are the same (the default).
add_subdirectory("${gtest_dir}" "${gmock_BINARY_DIR}/gtest")
add_subdirectory("${gtest_dir}" "${gmock_BINARY_DIR}/${gtest_dir}")
# These commands only run if this is the main project
@ -75,18 +78,6 @@ set(gmock_build_include_dirs
"${gtest_SOURCE_DIR}")
include_directories(${gmock_build_include_dirs})
# 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
# VS 2015 14 1900 std::tuple
# VS 2017 15 >= 1910 std::tuple
if (MSVC AND MSVC_VERSION EQUAL 1700)
add_definitions(/D _VARIADIC_MAX=10)
endif()
########################################################################
#
# Defines the gmock & gmock_main libraries. User tests should link
@ -145,15 +136,37 @@ 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 OR CYGWIN)
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()
if (MINGW OR CYGWIN)
if (CMAKE_VERSION VERSION_LESS "2.8.12")
add_compile_options("-Wa,-mbig-obj")
else()
add_definitions("-Wa,-mbig-obj")
endif()
endif()
############################################################
# C++ tests built with standard compiler flags.
cxx_test(gmock-actions_test gmock_main)
cxx_test(gmock-cardinalities_test gmock_main)
cxx_test(gmock_ex_test gmock_main)
cxx_test(gmock-function-mocker_test gmock_main)
cxx_test(gmock-generated-actions_test gmock_main)
cxx_test(gmock-generated-function-mockers_test gmock_main)
cxx_test(gmock-generated-internal-utils_test gmock_main)
cxx_test(gmock-generated-matchers_test gmock_main)
cxx_test(gmock-internal-utils_test gmock_main)
cxx_test(gmock-matchers_test gmock_main)
@ -182,25 +195,12 @@ if (gmock_build_tests)
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_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}"
"${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)
cxx_library(gmock_main_use_own_tuple "${cxx_use_own_tuple}" src/gmock_main.cc)
target_link_libraries(gmock_main_use_own_tuple 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)

View File

@ -1,224 +0,0 @@
# Automake file
# Nonstandard package files for distribution.
EXTRA_DIST = LICENSE
# We may need to build our internally packaged gtest. If so, it will be
# included in the 'subdirs' variable.
SUBDIRS = $(subdirs)
# This is generated by the configure script, so clean it for distribution.
DISTCLEANFILES = scripts/gmock-config
# We define the global AM_CPPFLAGS as everything we compile includes from these
# directories.
AM_CPPFLAGS = $(GTEST_CPPFLAGS) -I$(srcdir)/include
# Modifies compiler and linker flags for pthreads compatibility.
if HAVE_PTHREADS
AM_CXXFLAGS = @PTHREAD_CFLAGS@ -DGTEST_HAS_PTHREAD=1
AM_LIBS = @PTHREAD_LIBS@
endif
# Build rules for libraries.
lib_LTLIBRARIES = lib/libgmock.la lib/libgmock_main.la
lib_libgmock_la_SOURCES = src/gmock-all.cc
pkginclude_HEADERS = \
include/gmock/gmock-actions.h \
include/gmock/gmock-cardinalities.h \
include/gmock/gmock-generated-actions.h \
include/gmock/gmock-generated-function-mockers.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 \
include/gmock/gmock-spec-builders.h \
include/gmock/gmock.h
pkginclude_internaldir = $(pkgincludedir)/internal
pkginclude_internal_HEADERS = \
include/gmock/internal/gmock-generated-internal-utils.h \
include/gmock/internal/gmock-internal-utils.h \
include/gmock/internal/gmock-port.h \
include/gmock/internal/custom/gmock-generated-actions.h \
include/gmock/internal/custom/gmock-matchers.h \
include/gmock/internal/custom/gmock-port.h
lib_libgmock_main_la_SOURCES = src/gmock_main.cc
lib_libgmock_main_la_LIBADD = lib/libgmock.la
# Build rules for tests. Automake's naming for some of these variables isn't
# terribly obvious, so this is a brief reference:
#
# TESTS -- Programs run automatically by "make check"
# check_PROGRAMS -- Programs built by "make check" but not necessarily run
TESTS=
check_PROGRAMS=
AM_LDFLAGS = $(GTEST_LDFLAGS)
# This exercises all major components of Google Mock. It also
# verifies that libgmock works.
TESTS += test/gmock-spec-builders_test
check_PROGRAMS += test/gmock-spec-builders_test
test_gmock_spec_builders_test_SOURCES = test/gmock-spec-builders_test.cc
test_gmock_spec_builders_test_LDADD = $(GTEST_LIBS) lib/libgmock.la
# This tests using Google Mock in multiple translation units. It also
# verifies that libgmock_main and libgmock work.
TESTS += test/gmock_link_test
check_PROGRAMS += test/gmock_link_test
test_gmock_link_test_SOURCES = \
test/gmock_link2_test.cc \
test/gmock_link_test.cc \
test/gmock_link_test.h
test_gmock_link_test_LDADD = $(GTEST_LIBS) lib/libgmock_main.la lib/libgmock.la
if HAVE_PYTHON
# Tests that fused gmock files compile and work.
TESTS += test/gmock_fused_test
check_PROGRAMS += test/gmock_fused_test
test_gmock_fused_test_SOURCES = \
fused-src/gmock-gtest-all.cc \
fused-src/gmock/gmock.h \
fused-src/gmock_main.cc \
fused-src/gtest/gtest.h \
test/gmock_test.cc
test_gmock_fused_test_CPPFLAGS = -I"$(srcdir)/fused-src"
endif
# Google Mock source files that we don't compile directly.
GMOCK_SOURCE_INGLUDES = \
src/gmock-cardinalities.cc \
src/gmock-internal-utils.cc \
src/gmock-matchers.cc \
src/gmock-spec-builders.cc \
src/gmock.cc
EXTRA_DIST += $(GMOCK_SOURCE_INGLUDES)
# C++ tests that we don't compile using autotools.
EXTRA_DIST += \
test/gmock-actions_test.cc \
test/gmock_all_test.cc \
test/gmock-cardinalities_test.cc \
test/gmock_ex_test.cc \
test/gmock-generated-actions_test.cc \
test/gmock-generated-function-mockers_test.cc \
test/gmock-generated-internal-utils_test.cc \
test/gmock-generated-matchers_test.cc \
test/gmock-internal-utils_test.cc \
test/gmock-matchers_test.cc \
test/gmock-more-actions_test.cc \
test/gmock-nice-strict_test.cc \
test/gmock-port_test.cc \
test/gmock_stress_test.cc
# Python tests, which we don't run using autotools.
EXTRA_DIST += \
test/gmock_leak_test.py \
test/gmock_leak_test_.cc \
test/gmock_output_test.py \
test/gmock_output_test_.cc \
test/gmock_output_test_golden.txt \
test/gmock_test_utils.py
# Nonstandard package files for distribution.
EXTRA_DIST += \
CHANGES \
CONTRIBUTORS \
make/Makefile
# Pump scripts for generating Google Mock headers.
# TODO(chandlerc@google.com): automate the generation of *.h from *.h.pump.
EXTRA_DIST += \
include/gmock/gmock-generated-actions.h.pump \
include/gmock/gmock-generated-function-mockers.h.pump \
include/gmock/gmock-generated-matchers.h.pump \
include/gmock/gmock-generated-nice-strict.h.pump \
include/gmock/internal/gmock-generated-internal-utils.h.pump \
include/gmock/internal/custom/gmock-generated-actions.h.pump
# Script for fusing Google Mock and Google Test source files.
EXTRA_DIST += scripts/fuse_gmock_files.py
# The Google Mock Generator tool from the cppclean project.
EXTRA_DIST += \
scripts/generator/LICENSE \
scripts/generator/README \
scripts/generator/README.cppclean \
scripts/generator/cpp/__init__.py \
scripts/generator/cpp/ast.py \
scripts/generator/cpp/gmock_class.py \
scripts/generator/cpp/keywords.py \
scripts/generator/cpp/tokenize.py \
scripts/generator/cpp/utils.py \
scripts/generator/gmock_gen.py
# Script for diagnosing compiler errors in programs that use Google
# Mock.
EXTRA_DIST += scripts/gmock_doctor.py
# CMake scripts.
EXTRA_DIST += \
CMakeLists.txt
# Microsoft Visual Studio 2005 projects.
EXTRA_DIST += \
msvc/2005/gmock.sln \
msvc/2005/gmock.vcproj \
msvc/2005/gmock_config.vsprops \
msvc/2005/gmock_main.vcproj \
msvc/2005/gmock_test.vcproj
# Microsoft Visual Studio 2010 projects.
EXTRA_DIST += \
msvc/2010/gmock.sln \
msvc/2010/gmock.vcxproj \
msvc/2010/gmock_config.props \
msvc/2010/gmock_main.vcxproj \
msvc/2010/gmock_test.vcxproj
if HAVE_PYTHON
# gmock_test.cc does not really depend on files generated by the
# fused-gmock-internal rule. However, gmock_test.o does, and it is
# important to include test/gmock_test.cc as part of this rule in order to
# prevent compiling gmock_test.o until all dependent files have been
# generated.
$(test_gmock_fused_test_SOURCES): fused-gmock-internal
# TODO(vladl@google.com): Find a way to add Google Tests's sources here.
fused-gmock-internal: $(pkginclude_HEADERS) $(pkginclude_internal_HEADERS) \
$(lib_libgmock_la_SOURCES) $(GMOCK_SOURCE_INGLUDES) \
$(lib_libgmock_main_la_SOURCES) \
scripts/fuse_gmock_files.py
mkdir -p "$(srcdir)/fused-src"
chmod -R u+w "$(srcdir)/fused-src"
rm -f "$(srcdir)/fused-src/gtest/gtest.h"
rm -f "$(srcdir)/fused-src/gmock/gmock.h"
rm -f "$(srcdir)/fused-src/gmock-gtest-all.cc"
"$(srcdir)/scripts/fuse_gmock_files.py" "$(srcdir)/fused-src"
cp -f "$(srcdir)/src/gmock_main.cc" "$(srcdir)/fused-src"
maintainer-clean-local:
rm -rf "$(srcdir)/fused-src"
endif
# Death tests may produce core dumps in the build directory. In case
# this happens, clean them to keep distcleancheck happy.
CLEANFILES = core
# Disables 'make install' as installing a compiled version of Google
# Mock can lead to undefined behavior due to violation of the
# One-Definition Rule.
install-exec-local:
echo "'make install' is dangerous and not supported. Instead, see README for how to integrate Google Mock into your build system."
false
install-data-local:
echo "'make install' is dangerous and not supported. Instead, see README for how to integrate Google Mock into your build system."
false

View File

@ -1,323 +1,44 @@
## Google Mock ##
# Googletest Mocking (gMock) Framework
The Google C++ mocking framework.
### Overview
### Overview ###
Google's framework for writing and using C++ mock classes.
It can help you derive better designs of your system and write better tests.
Google's framework for writing and using C++ mock classes. It can help you
derive better designs of your system and write better tests.
It is inspired by:
* [jMock](http://www.jmock.org/),
* [EasyMock](http://www.easymock.org/), and
* [Hamcrest](http://code.google.com/p/hamcrest/),
* [jMock](http://www.jmock.org/),
* [EasyMock](http://www.easymock.org/), and
* [Hamcrest](http://code.google.com/p/hamcrest/),
and designed with C++'s specifics in mind.
Google mock:
* lets you create mock classes trivially using simple macros.
* supports a rich set of matchers and actions.
* handles unordered, partially ordered, or completely ordered expectations.
* is extensible by users.
We hope you find it useful!
### Features ###
* Provides a declarative syntax for defining mocks.
* Can easily define partial (hybrid) mocks, which are a cross of real
and mock objects.
* Handles functions of arbitrary types and overloaded functions.
* Comes with a rich set of matchers for validating function arguments.
* Uses an intuitive syntax for controlling the behavior of a mock.
* Does automatic verification of expectations (no record-and-replay needed).
* Allows arbitrary (partial) ordering constraints on
function calls to be expressed,.
* Lets an user extend it by defining new matchers and actions.
* Does not use exceptions.
* Is easy to learn and use.
Please see the project page above for more information as well as the
mailing list for questions, discussions, and development. There is
also an IRC channel on OFTC (irc.oftc.net) #gtest available. Please
join us!
Please note that code under [scripts/generator](scripts/generator/) is
from [cppclean](http://code.google.com/p/cppclean/) and released under
the Apache License, which is different from Google Mock's license.
## Getting Started ##
If you are new to the project, we suggest that you read the user
documentation in the following order:
* Learn the [basics](../../master/googletest/docs/primer.md) of
Google Test, if you choose to use Google Mock with it (recommended).
* Read [Google Mock for Dummies](../../master/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](../../master/googlemock/docs/CheatSheet.md) - all the commonly used stuff
at a glance.
* [CookBook](../../master/googlemock/docs/CookBook.md) - recipes for getting things done,
including advanced techniques.
If you need help, please check the
[KnownIssues](docs/KnownIssues.md) and
[FrequentlyAskedQuestions](docs/FrequentlyAskedQuestions.md) before
posting a question on the
[discussion group](http://groups.google.com/group/googlemock).
### Using Google Mock Without Google Test ###
Google Mock is not a testing framework itself. Instead, it needs a
testing framework for writing tests. Google Mock works seamlessly
with [Google Test](https://github.com/google/googletest), but
you can also use it with [any C++ testing framework](../../master/googlemock/docs/ForDummies.md#using-google-mock-with-any-testing-framework).
### Requirements for End Users ###
Google Mock is implemented on top of [Google Test](
http://github.com/google/googletest/), and depends on it.
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"](
../../master/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
modern compiler. The following are needed to use Google Mock:
#### Linux Requirements ####
* GNU-compatible Make or "gmake"
* POSIX-standard shell
* POSIX(-2) Regular Expressions (regex.h)
* C++98-standard-compliant compiler (e.g. GCC 3.4 or newer)
#### Windows Requirements ####
* Microsoft Visual C++ 8.0 SP1 or newer
#### Mac OS X Requirements ####
* Mac OS X 10.4 Tiger or newer
* Developer Tools Installed
### Requirements for Contributors ###
We welcome patches. If you plan to contribute a patch, you need to
build Google Mock and its tests, which has further requirements:
* Automake version 1.9 or newer
* Autoconf version 2.59 or newer
* Libtool / Libtoolize
* Python version 2.3 or newer (for running some of the tests and
re-generating certain source files from templates)
### 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
system to build Google Mock (described below), you'll need to
configure it now.
To prepare the Autotools build system:
cd googlemock
autoreconf -fvi
To build Google Mock and your tests that use it, you need to tell your
build system where to find its headers and source files. The exact
way to do it depends on which build system you use, and is usually
straightforward.
This section shows how you can integrate Google Mock into your
existing build system.
Suppose you put Google Mock in directory `${GMOCK_DIR}` and Google Test
in `${GTEST_DIR}` (the latter is `${GMOCK_DIR}/gtest` by default). To
build Google Mock, create a library build target (or a project as
called by Visual Studio and Xcode) to compile
${GTEST_DIR}/src/gtest-all.cc and ${GMOCK_DIR}/src/gmock-all.cc
with
${GTEST_DIR}/include and ${GMOCK_DIR}/include
in the system header search path, and
${GTEST_DIR} and ${GMOCK_DIR}
in the normal header search path. Assuming a Linux-like system and gcc,
something like the following will do:
g++ -isystem ${GTEST_DIR}/include -I${GTEST_DIR} \
-isystem ${GMOCK_DIR}/include -I${GMOCK_DIR} \
-pthread -c ${GTEST_DIR}/src/gtest-all.cc
g++ -isystem ${GTEST_DIR}/include -I${GTEST_DIR} \
-isystem ${GMOCK_DIR}/include -I${GMOCK_DIR} \
-pthread -c ${GMOCK_DIR}/src/gmock-all.cc
ar -rv libgmock.a gtest-all.o gmock-all.o
(We need -pthread as Google Test and Google Mock use threads.)
Next, you should compile your test source file with
${GTEST\_DIR}/include and ${GMOCK\_DIR}/include in the header search
path, and link it with gmock and any other necessary libraries:
g++ -isystem ${GTEST_DIR}/include -isystem ${GMOCK_DIR}/include \
-pthread path/to/your_test.cc libgmock.a -o your_test
As an example, the make/ directory contains a Makefile that you can
use to build Google Mock on systems where GNU make is available
(e.g. Linux, Mac OS X, and Cygwin). It doesn't try to build Google
Mock's own tests. Instead, it just builds the Google Mock library and
a sample test. You can use it as a starting point for your own build
script.
If the default settings are correct for your environment, the
following commands should succeed:
cd ${GMOCK_DIR}/make
make
./gmock_test
If you see errors, try to tweak the contents of
[make/Makefile](make/Makefile) to make them go away.
### Windows ###
The msvc/2005 directory contains VC++ 2005 projects and the msvc/2010
directory contains VC++ 2010 projects for building Google Mock and
selected tests.
Change to the appropriate directory and run "msbuild gmock.sln" to
build the library and tests (or open the gmock.sln in the MSVC IDE).
If you want to create your own project to use with Google Mock, you'll
have to configure it to use the `gmock_config` propety sheet. For that:
* Open the Property Manager window (View | Other Windows | Property Manager)
* Right-click on your project and select "Add Existing Property Sheet..."
* Navigate to `gmock_config.vsprops` or `gmock_config.props` and select it.
* In Project Properties | Configuration Properties | General | Additional
Include Directories, type <path to Google Mock>/include.
### Tweaking Google Mock ###
Google Mock can be used in diverse environments. The default
configuration may not work (or may not work well) out of the box in
some environments. However, you can easily tweak Google Mock by
defining control macros on the compiler command line. Generally,
these macros are named like `GTEST_XYZ` and you define them to either 1
or 0 to enable or disable a certain feature.
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
library for the simplicity. Google Mock can be used as a DLL, but the
same DLL must contain Google Test as well. See
[Google Test's README][gtest_readme]
for instructions on how to set up necessary compiler settings.
### Tweaking Google Mock ###
Most of Google Test's control macros apply to Google Mock as well.
Please see [Google Test's README][gtest_readme] for how to tweak them.
### Upgrading from an Earlier Version ###
We strive to keep Google Mock releases backward compatible.
Sometimes, though, we have to make some breaking changes for the
users' long-term benefits. This section describes what you'll need to
do if you are upgrading from an earlier version of Google Mock.
#### Upgrading from 1.1.0 or Earlier ####
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)".
#### 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.
If you have custom matchers defined using `MatcherInterface` or
`MakePolymorphicMatcher()`, you'll need to update their definitions to
use the new matcher API (
[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.
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"
gMock:
- provides a declarative syntax for defining mocks,
- can define partial (hybrid) mocks, which are a cross of real and mock
objects,
- handles functions of arbitrary types and overloaded functions,
- comes with a rich set of matchers for validating function arguments,
- uses an intuitive syntax for controlling the behavior of a mock,
- 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.
- does not use exceptions, and
- is easy to learn and use.
Details and examples can be found here:
* [gMock for Dummies](docs/for_dummies.md)
* [Legacy gMock FAQ](docs/gmock_faq.md)
* [gMock Cookbook](docs/cook_book.md)
* [gMock Cheat Sheet](docs/cheat_sheet.md)
Please note that code under scripts/generator/ is from the [cppclean
project](http://code.google.com/p/cppclean/) and under the Apache
License, which is different from Google Mock's license.
Google Mock is a part of
[Google Test C++ testing framework](http://github.com/google/googletest/) and a
subject to the same requirements.

View File

@ -1,9 +1,11 @@
libdir=@CMAKE_INSTALL_FULL_LIBDIR@
includedir=@CMAKE_INSTALL_FULL_INCLUDEDIR@
prefix=${pcfiledir}/../..
libdir=${prefix}/@CMAKE_INSTALL_LIBDIR@
includedir=${prefix}/@CMAKE_INSTALL_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@

View File

@ -1,9 +1,11 @@
libdir=@CMAKE_INSTALL_FULL_LIBDIR@
includedir=@CMAKE_INSTALL_FULL_INCLUDEDIR@
prefix=${pcfiledir}/../..
libdir=${prefix}/@CMAKE_INSTALL_LIBDIR@
includedir=${prefix}/@CMAKE_INSTALL_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@

View File

@ -1,146 +0,0 @@
m4_include(../googletest/m4/acx_pthread.m4)
AC_INIT([Google C++ Mocking Framework],
[1.8.0],
[googlemock@googlegroups.com],
[gmock])
# Provide various options to initialize the Autoconf and configure processes.
AC_PREREQ([2.59])
AC_CONFIG_SRCDIR([./LICENSE])
AC_CONFIG_AUX_DIR([build-aux])
AC_CONFIG_HEADERS([build-aux/config.h])
AC_CONFIG_FILES([Makefile])
AC_CONFIG_FILES([scripts/gmock-config], [chmod +x scripts/gmock-config])
# Initialize Automake with various options. We require at least v1.9, prevent
# pedantic complaints about package files, and enable various distribution
# targets.
AM_INIT_AUTOMAKE([1.9 dist-bzip2 dist-zip foreign subdir-objects])
# Check for programs used in building Google Test.
AC_PROG_CC
AC_PROG_CXX
AC_LANG([C++])
AC_PROG_LIBTOOL
# TODO(chandlerc@google.com): Currently we aren't running the Python tests
# against the interpreter detected by AM_PATH_PYTHON, and so we condition
# HAVE_PYTHON by requiring "python" to be in the PATH, and that interpreter's
# version to be >= 2.3. This will allow the scripts to use a "/usr/bin/env"
# hashbang.
PYTHON= # We *do not* allow the user to specify a python interpreter
AC_PATH_PROG([PYTHON],[python],[:])
AS_IF([test "$PYTHON" != ":"],
[AM_PYTHON_CHECK_VERSION([$PYTHON],[2.3],[:],[PYTHON=":"])])
AM_CONDITIONAL([HAVE_PYTHON],[test "$PYTHON" != ":"])
# TODO(chandlerc@google.com) Check for the necessary system headers.
# Configure pthreads.
AC_ARG_WITH([pthreads],
[AS_HELP_STRING([--with-pthreads],
[use pthreads (default is yes)])],
[with_pthreads=$withval],
[with_pthreads=check])
have_pthreads=no
AS_IF([test "x$with_pthreads" != "xno"],
[ACX_PTHREAD(
[],
[AS_IF([test "x$with_pthreads" != "xcheck"],
[AC_MSG_FAILURE(
[--with-pthreads was specified, but unable to be used])])])
have_pthreads="$acx_pthread_ok"])
AM_CONDITIONAL([HAVE_PTHREADS],[test "x$have_pthreads" == "xyes"])
AC_SUBST(PTHREAD_CFLAGS)
AC_SUBST(PTHREAD_LIBS)
# GoogleMock currently has hard dependencies upon GoogleTest above and beyond
# running its own test suite, so we both provide our own version in
# a subdirectory and provide some logic to use a custom version or a system
# installed version.
AC_ARG_WITH([gtest],
[AS_HELP_STRING([--with-gtest],
[Specifies how to find the gtest package. If no
arguments are given, the default behavior, a
system installed gtest will be used if present,
and an internal version built otherwise. If a
path is provided, the gtest built or installed at
that prefix will be used.])],
[],
[with_gtest=yes])
AC_ARG_ENABLE([external-gtest],
[AS_HELP_STRING([--disable-external-gtest],
[Disables any detection or use of a system
installed or user provided gtest. Any option to
'--with-gtest' is ignored. (Default is enabled.)])
], [], [enable_external_gtest=yes])
AS_IF([test "x$with_gtest" == "xno"],
[AC_MSG_ERROR([dnl
Support for GoogleTest was explicitly disabled. Currently GoogleMock has a hard
dependency upon GoogleTest to build, please provide a version, or allow
GoogleMock to use any installed version and fall back upon its internal
version.])])
# Setup various GTEST variables. TODO(chandlerc@google.com): When these are
# used below, they should be used such that any pre-existing values always
# trump values we set them to, so that they can be used to selectively override
# details of the detection process.
AC_ARG_VAR([GTEST_CONFIG],
[The exact path of Google Test's 'gtest-config' script.])
AC_ARG_VAR([GTEST_CPPFLAGS],
[C-like preprocessor flags for Google Test.])
AC_ARG_VAR([GTEST_CXXFLAGS],
[C++ compile flags for Google Test.])
AC_ARG_VAR([GTEST_LDFLAGS],
[Linker path and option flags for Google Test.])
AC_ARG_VAR([GTEST_LIBS],
[Library linking flags for Google Test.])
AC_ARG_VAR([GTEST_VERSION],
[The version of Google Test available.])
HAVE_BUILT_GTEST="no"
GTEST_MIN_VERSION="1.8.0"
AS_IF([test "x${enable_external_gtest}" = "xyes"],
[# Begin filling in variables as we are able.
AS_IF([test "x${with_gtest}" != "xyes"],
[AS_IF([test -x "${with_gtest}/scripts/gtest-config"],
[GTEST_CONFIG="${with_gtest}/scripts/gtest-config"],
[GTEST_CONFIG="${with_gtest}/bin/gtest-config"])
AS_IF([test -x "${GTEST_CONFIG}"], [],
[AC_MSG_ERROR([dnl
Unable to locate either a built or installed Google Test at '${with_gtest}'.])
])])
AS_IF([test -x "${GTEST_CONFIG}"], [],
[AC_PATH_PROG([GTEST_CONFIG], [gtest-config])])
AS_IF([test -x "${GTEST_CONFIG}"],
[AC_MSG_CHECKING([for Google Test version >= ${GTEST_MIN_VERSION}])
AS_IF([${GTEST_CONFIG} --min-version=${GTEST_MIN_VERSION}],
[AC_MSG_RESULT([yes])
HAVE_BUILT_GTEST="yes"],
[AC_MSG_RESULT([no])])])])
AS_IF([test "x${HAVE_BUILT_GTEST}" = "xyes"],
[GTEST_CPPFLAGS=`${GTEST_CONFIG} --cppflags`
GTEST_CXXFLAGS=`${GTEST_CONFIG} --cxxflags`
GTEST_LDFLAGS=`${GTEST_CONFIG} --ldflags`
GTEST_LIBS=`${GTEST_CONFIG} --libs`
GTEST_VERSION=`${GTEST_CONFIG} --version`],
[
# 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'
GTEST_CXXFLAGS='-g'
GTEST_LDFLAGS=''
GTEST_LIBS='$(top_builddir)/../googletest/lib/libgtest.la'
GTEST_VERSION="${GTEST_MIN_VERSION}"])
# TODO(chandlerc@google.com) Check the types, structures, and other compiler
# and architecture characteristics.
# Output the generated files. No further autoconf macros may be used.
AC_OUTPUT

View File

@ -1,564 +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_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.
# 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](../../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;
// Sets the default value to be returned. T must be CopyConstructible.
DefaultValue<T>::Set(value);
// Sets a factory. Will be invoked on demand. T must be MoveConstructible.
// T MakeT();
DefaultValue<T>::SetFactory(&MakeT);
// ... use the mocks ...
// Resets the default value.
DefaultValue<T>::Clear();
```
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).|
|`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.|
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](../../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](../../googletest/docs/advanced.md#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, STL-style container, 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, STL-style container, or C-style array. |
| `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)).
* 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:
```
using ::testing::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`.|
|:-----------|:-----------------------------------------------------------------------------------------------|
|`WhenDynamicCastTo<T>(m)`| when `argument` is passed through `dynamic_cast<T>()`, it 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](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 ##
|`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](../../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 #
**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](CookBook.md#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. |

File diff suppressed because it is too large Load Diff

View File

@ -1,280 +0,0 @@
This page discusses the design of new Google Mock features.
# Macros for Defining Actions #
## Problem ##
Due to the lack of closures in C++, it currently requires some
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:
```
int IncrementArg1(Unused, int* p, Unused) {
return ++(*p);
}
... WillOnce(Invoke(IncrementArg1));
```
There are several things unsatisfactory about this approach:
* Even though the action only cares about the second argument of the mock function, its definition needs to list other arguments as dummies. This is tedious.
* The defined action is usable only in mock functions that takes exactly 3 arguments - an unnecessary restriction.
* To use the action, one has to say `Invoke(IncrementArg1)`, which isn't as nice as `IncrementArg1()`.
The latter two problems can be overcome using `MakePolymorphicAction()`,
but it requires much more boilerplate code:
```
class IncrementArg1Action {
public:
template <typename Result, typename ArgumentTuple>
Result Perform(const ArgumentTuple& args) const {
return ++(*tr1::get<1>(args));
}
};
PolymorphicAction<IncrementArg1Action> IncrementArg1() {
return MakePolymorphicAction(IncrementArg1Action());
}
... WillOnce(IncrementArg1());
```
Our goal is to allow defining custom actions with the least amount of
boiler-plate C++ requires.
## Solution ##
We propose to introduce a new macro:
```
ACTION(name) { statements; }
```
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:
```
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, as brevity is a top design goal here. Rest assured that
your code is still 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*)` |
## Parameterized actions ##
Sometimes you'll want to parameterize the action. For that we propose
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.
We will also provide `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.
## Advanced Usages ##
### Overloading Actions ###
You can 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 ###
For maximum brevity and reusability, the `ACTION*` macros don't let
you specify 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 we plan to add to
Google Test (the name is chosen to match `static_assert` in C++0x).
### 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_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,
or the action definitions cannot be overloaded on the number of
parameters.
## When to Use ##
While the new macros are very convenient, please also consider other
means of implementing actions (e.g. via `ActionInterface` or
`MakePolymorphicAction()`), especially if you need to use the defined
action a lot. While the other approaches require more work, they give
you more control on the types of the mock function arguments and the
action parameters, which in general leads to better compiler error
messages that pay off in the long run. They also allow overloading
actions based on parameter types, as opposed to just the number of
parameters.
## Related Work ##
As you may have realized, the `ACTION*` macros resemble closures (also
known as lambda expressions or anonymous functions). Indeed, both of
them seek to lower the syntactic overhead for defining a function.
C++0x will support lambdas, but they are not part of C++ right now.
Some non-standard libraries (most notably BLL or Boost Lambda Library)
try to alleviate this problem. However, they are not a good choice
for defining actions as:
* They are non-standard and not widely installed. Google Mock only depends on standard libraries and `tr1::tuple`, which is part of the new C++ standard and comes with gcc 4+. We want to keep it that way.
* They are not trivial to learn.
* They will become obsolete when C++0x's lambda feature is widely supported. We don't want to make our users use a dying library.
* Since they are based on operators, they are rather ad hoc: you cannot use statements, and you cannot pass the lambda arguments to a function, for example.
* They have subtle semantics that easily confuses new users. For example, in expression `_1++ + foo++`, `foo` will be incremented only once where the expression is evaluated, while `_1` will be incremented every time the unnamed function is invoked. This is far from intuitive.
`ACTION*` avoid all these problems.
## Future Improvements ##
There may be a need for composing `ACTION*` definitions (i.e. invoking
another `ACTION` inside the definition of one `ACTION*`). We are not
sure we want it yet, as one can get a similar effect by putting
`ACTION` definitions in function templates and composing the function
templates. We'll revisit this based on user feedback.
The reason we don't allow `ACTION*()` inside a function body is that
the current C++ standard doesn't allow function-local types to be used
to instantiate templates. The upcoming C++0x standard will lift this
restriction. Once this feature is widely supported by compilers, we
can revisit the implementation and add support for using `ACTION*()`
inside a function.
C++0x will also support lambda expressions. When they become
available, we may want to support using lambdas as actions.
# Macros for Defining Matchers #
Once the macros for defining actions are implemented, we plan to do
the same for matchers:
```
MATCHER(name) { statements; }
```
where you can refer to the value being matched as `arg`. For example,
given:
```
MATCHER(IsPositive) { return arg > 0; }
```
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.

View File

@ -1,15 +0,0 @@
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.
* [CookBook](CookBook.md) -- recipes for doing various tasks using Google Mock.
* [FrequentlyAskedQuestions](FrequentlyAskedQuestions.md) -- check here before asking a question on the mailing list.
To contribute code to Google Mock, read:
* [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.

View File

@ -1,447 +0,0 @@
(**Note:** If you get compiler errors that you don't understand, be sure to consult [Google Mock Doctor](FrequentlyAskedQuestions.md#how-am-i-supposed-to-make-sense-of-these-horrible-template-errors).)
# 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 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.
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](CookBook.md#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](../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://sourceforge.net/projects/cppunit/) or
[CxxTest](https://cxxtest.com/)) 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](../../googletest/docs/advanced.md#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](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](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). In addition, in C++ 11 and above, a mock function whose return type is default-constructible (i.e. has a default constructor) has a default action of returning a default-constructed value. 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](CheatSheet.md#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](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](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::_;
...
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](CookBook.md). You can learn many advanced features of Google Mock there -- and advance your level of enjoyment and testing bliss.

View File

@ -1,627 +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](CookBook.md#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](CookBook.md#writing-new-monomorphic-matchers)
[recipes](CookBook.md#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](ForDummies.md#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 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
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()](CookBook.md#writing-new-actions) 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).
## 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](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! ##
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](CookBook.md#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. 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](https://github.com/google/googletest/issues) 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.

View File

@ -1,19 +0,0 @@
As any non-trivial software system, Google Mock has some known limitations and problems. We are working on improving it, and welcome your help! The follow is a list of issues we know about.
## README contains outdated information on Google Mock's compatibility with other testing frameworks ##
The `README` file in release 1.1.0 still says that Google Mock only works with Google Test. Actually, you can configure Google Mock to work with any testing framework you choose.
## Tests failing on machines using Power PC CPUs (e.g. some Macs) ##
`gmock_output_test` and `gmock-printers_test` are known to fail with Power PC CPUs. This is due to portability issues with these tests, and is not an indication of problems in Google Mock itself. You can safely ignore them.
## Failed to resolve libgtest.so.0 in tests when built against installed Google Test ##
This only applies if you manually built and installed Google Test, and then built a Google Mock against it (either explicitly, or because gtest-config was in your path post-install). In this situation, Libtool has a known issue with certain systems' ldconfig setup:
http://article.gmane.org/gmane.comp.sysutils.automake.general/9025
This requires a manual run of "sudo ldconfig" after the "sudo make install" for Google Test before any binaries which link against it can be executed. This isn't a bug in our install, but we should at least have documented it or hacked a work-around into our install. We should have one of these solutions in our next release.

View File

@ -0,0 +1,781 @@
## gMock Cheat Sheet
<!-- GOOGLETEST_CM0019 DO NOT DELETE -->
<!-- GOOGLETEST_CM0033 DO NOT DELETE -->
### Defining a Mock Class
#### Mocking a Normal Class {#MockClass}
Given
```cpp
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
```cpp
#include "gmock/gmock.h"
class MockFoo : public Foo {
...
MOCK_METHOD(int, GetSize, (), (const, override));
MOCK_METHOD(string, Describe, (const char* name), (override));
MOCK_METHOD(string, Describe, (int type), (override));
MOCK_METHOD(bool, Process, (Bar elem, int count), (override));
};
```
To create a "nice" mock, which ignores all uninteresting calls, a "naggy" mock,
which warns on all uninteresting calls, or a "strict" mock, which treats them as
failures:
```cpp
using ::testing::NiceMock;
using ::testing::NaggyMock;
using ::testing::StrictMock;
NiceMock<MockFoo> nice_foo; // The type is a subclass of MockFoo.
NaggyMock<MockFoo> naggy_foo; // The type is a subclass of MockFoo.
StrictMock<MockFoo> strict_foo; // The type is a subclass of MockFoo.
```
**Note:** A mock object is currently naggy by default. We may make it nice by
default in the future.
#### Mocking a Class Template {#MockTemplate}
Class templates can be mocked just like any class.
To mock
```cpp
template <typename Elem>
class StackInterface {
...
virtual ~StackInterface();
virtual int GetSize() const = 0;
virtual void Push(const Elem& x) = 0;
};
```
(note that all member functions that are mocked, including `~StackInterface()`
**must** be virtual).
```cpp
template <typename Elem>
class MockStack : public StackInterface<Elem> {
...
MOCK_METHOD(int, GetSize, (), (const, override));
MOCK_METHOD(void, Push, (const Elem& x), (override));
};
```
#### Specifying Calling Conventions for Mock Functions
If your mock function doesn't use the default calling convention, you can
specify it by adding `Calltype(convention)` to `MOCK_METHOD`'s 4th parameter.
For example,
```cpp
MOCK_METHOD(bool, Foo, (int n), (Calltype(STDMETHODCALLTYPE)));
MOCK_METHOD(int, Bar, (double x, double y),
(const, Calltype(STDMETHODCALLTYPE)));
```
where `STDMETHODCALLTYPE` is defined by `<objbase.h>` on Windows.
### Using Mocks in Tests {#UsingMocks}
The typical work flow is:
1. Import the gMock names you need to use. All gMock symbols are in the
`testing` namespace unless they are macros or otherwise noted.
2. Create the mock objects.
3. Optionally, set the default actions of the mock objects.
4. Set your expectations on the mock objects (How will they be called? What
will they do?).
5. Exercise code that uses the mock objects; if necessary, check the result
using googletest assertions.
6. When a mock object is destructed, gMock automatically verifies that all
expectations on it have been satisfied.
Here's an example:
```cpp
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 {#OnCall}
gMock has a **built-in default action** for any function that returns `void`,
`bool`, a numeric value, or a pointer. In C++11, it will additionally returns
the default-constructed value, if one exists for the given type.
To customize the default action for functions with return type *`T`*:
```cpp
using ::testing::DefaultValue;
// Sets the default value to be returned. T must be CopyConstructible.
DefaultValue<T>::Set(value);
// Sets a factory. Will be invoked on demand. T must be MoveConstructible.
// T MakeT();
DefaultValue<T>::SetFactory(&MakeT);
// ... use the mocks ...
// Resets the default value.
DefaultValue<T>::Clear();
```
Example usage:
```cpp
// 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();
```
To customize the default action for a particular method of a specific mock
object, use `ON_CALL()`. `ON_CALL()` has a similar syntax to `EXPECT_CALL()`,
but it is used for setting default behaviors (when you do not require that the
mock method is called). See [here](cook_book.md#UseOnCall) for a more detailed
discussion.
```cpp
ON_CALL(mock-object, method(matchers))
.With(multi-argument-matcher) ?
.WillByDefault(action);
```
### Setting Expectations {#ExpectCall}
`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) ?
.InSequence(sequences) *
.After(expectations) *
.WillOnce(action) *
.WillRepeatedly(action) ?
.RetiresOnSaturation(); ?
```
For each item above, `?` means it can be used at most once, while `*` means it
can be used any number of times.
In order to pass, `EXPECT_CALL` must be used before the calls are actually made.
The `(matchers)` is a comma-separated list of matchers that correspond to each
of the arguments of `method`, and sets the expectation only for calls of
`method` that matches all of the matchers.
If `(matchers)` is omitted, the expectation is the same as if the matchers were
set to anything matchers (for example, `(_, _, _, _)` for a four-arg method).
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 {#MatcherList}
<!-- GOOGLETEST_CM0020 DO NOT DELETE -->
A **matcher** matches a *single* argument. You can use it inside `ON_CALL()` or
`EXPECT_CALL()`, or use it to validate a value directly using two macros:
<!-- mdformat off(github rendering does not support multiline tables) -->
| Macro | Description |
| :----------------------------------- | :------------------------------------ |
| `EXPECT_THAT(actual_value, matcher)` | Asserts that `actual_value` matches `matcher`. |
| `ASSERT_THAT(actual_value, matcher)` | The same as `EXPECT_THAT(actual_value, matcher)`, except that it generates a **fatal** failure. |
<!-- mdformat on -->
Built-in matchers (where `argument` is the function argument, e.g.
`actual_value` in the example above, or when used in the context of
`EXPECT_CALL(mock_object, method(matchers))`, the arguments of `method`) 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
<!-- mdformat off(no multiline tables) -->
| Matcher | Description |
| :--------------------- | :-------------------------------------------------- |
| `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` |
| `IsFalse()` | `argument` evaluates to `false` in a Boolean context. |
| `IsTrue()` | `argument` evaluates to `true` in a Boolean context. |
| `IsNull()` | `argument` is a `NULL` pointer (raw or smart). |
| `NotNull()` | `argument` is a non-null pointer (raw or smart). |
| `Optional(m)` | `argument` is `optional<>` that contains a value matching `m`. |
| `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. |
<!-- mdformat on -->
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 {#FpMatchers}
<!-- mdformat off(no multiline tables) -->
| 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. |
<!-- mdformat on -->
The above matchers use ULP-based comparison (the same as used in 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.
<!-- mdformat off(no multiline tables) -->
| 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. |
<!-- mdformat on -->
#### String Matchers
The `argument` can be either a C string or a C++ string object:
<!-- mdformat off(no multiline tables) -->
| 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. |
| `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`. |
<!-- mdformat on -->
`ContainsRegex()` and `MatchesRegex()` take ownership of the `RE` object. They
use the regular expression syntax defined
[here](../../googletest/docs/advanced.md#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:
<!-- mdformat off(no multiline tables) -->
| Matcher | Description |
| :---------------------------------------- | :------------------------------- |
| `BeginEndDistanceIs(m)` | `argument` is a container whose `begin()` and `end()` iterators are separated by a number of increments matching `m`. E.g. `BeginEndDistanceIs(2)` or `BeginEndDistanceIs(Lt(2))`. For containers that define a `size()` method, `SizeIs(m)` may be more efficient. |
| `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. |
| `ElementsAreArray({e0, e1, ..., en})`, `ElementsAreArray(a_container)`, `ElementsAreArray(begin, end)`, `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, iterator range, or C-style array. |
| `IsEmpty()` | `argument` is an empty container (`container.empty()`). |
| `IsSubsetOf({e0, e1, ..., en})`, `IsSubsetOf(a_container)`, `IsSubsetOf(begin, end)`, `IsSubsetOf(array)`, or `IsSubsetOf(array, count)` | `argument` matches `UnorderedElementsAre(x0, x1, ..., xk)` for some subset `{x0, x1, ..., xk}` of the expected matchers. |
| `IsSupersetOf({e0, e1, ..., en})`, `IsSupersetOf(a_container)`, `IsSupersetOf(begin, end)`, `IsSupersetOf(array)`, or `IsSupersetOf(array, count)` | Some subset of `argument` matches `UnorderedElementsAre(`expected matchers`)`. |
| `Pointwise(m, container)`, `Pointwise(m, {e0, e1, ..., en})` | `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 of the elements, each element matches an `ei` (for a different `i`), which can be a value or a matcher. |
| `UnorderedElementsAreArray({e0, e1, ..., en})`, `UnorderedElementsAreArray(a_container)`, `UnorderedElementsAreArray(begin, end)`, `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, iterator range, or C-style array. |
| `UnorderedPointwise(m, container)`, `UnorderedPointwise(m, {e0, e1, ..., en})` | Like `Pointwise(m, container)`, but ignores the order of elements. |
| `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(), ElementsAre(3, 2, 1))`. |
<!-- mdformat on -->
**Notes:**
* These matchers can also match:
1. a native array passed by reference (e.g. in `Foo(const int (&a)[5])`),
and
2. an array passed as a pointer and a count (e.g. in `Bar(const T* buffer,
int len)` -- see [Multi-argument Matchers](#MultiArgMatchers)).
* 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::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==`, one might write:
```cpp
using ::std::get;
MATCHER(FooEq, "") {
return std::get<0>(arg).Equals(std::get<1>(arg));
}
...
EXPECT_THAT(actual_foos, Pointwise(FooEq(), expected_foos));
```
#### Member Matchers
<!-- mdformat off(no multiline tables) -->
| 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`. |
| `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_. |
<!-- mdformat on -->
#### Matching the Result of a Function, Functor, or Callback
<!-- mdformat off(no multiline tables) -->
| Matcher | Description |
| :--------------- | :------------------------------------------------ |
| `ResultOf(f, m)` | `f(argument)` matches matcher `m`, where `f` is a function or functor. |
<!-- mdformat on -->
#### Pointer Matchers
<!-- mdformat off(no multiline tables) -->
| 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`. |
<!-- mdformat on -->
<!-- GOOGLETEST_CM0026 DO NOT DELETE -->
<!-- GOOGLETEST_CM0027 DO NOT DELETE -->
#### Multi-argument Matchers {#MultiArgMatchers}
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`
`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:
<!-- mdformat off(no multiline tables) -->
| 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())`. |
<!-- mdformat on -->
#### Composite Matchers
You can make a matcher from one or more other matchers:
<!-- mdformat off(no multiline tables) -->
| Matcher | Description |
| :------------------------------- | :-------------------------------------- |
| `AllOf(m1, m2, ..., mn)` | `argument` matches all of the matchers `m1` to `mn`. |
| `AllOfArray({m0, m1, ..., mn})`, `AllOfArray(a_container)`, `AllOfArray(begin, end)`, `AllOfArray(array)`, or `AllOfArray(array, count)` | The same as `AllOf()` except that the matchers come from an initializer list, STL-style container, iterator range, or C-style array. |
| `AnyOf(m1, m2, ..., mn)` | `argument` matches at least one of the matchers `m1` to `mn`. |
| `AnyOfArray({m0, m1, ..., mn})`, `AnyOfArray(a_container)`, `AnyOfArray(begin, end)`, `AnyOfArray(array)`, or `AnyOfArray(array, count)` | The same as `AnyOf()` except that the matchers come from an initializer list, STL-style container, iterator range, or C-style array. |
| `Not(m)` | `argument` doesn't match matcher `m`. |
<!-- mdformat on -->
<!-- GOOGLETEST_CM0028 DO NOT DELETE -->
#### Adapters for Matchers
<!-- mdformat off(no multiline tables) -->
| Matcher | Description |
| :---------------------- | :------------------------------------ |
| `MatcherCast<T>(m)` | casts matcher `m` to type `Matcher<T>`. |
| `SafeMatcherCast<T>(m)` | [safely casts](cook_book.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. |
<!-- mdformat on -->
`AddressSatisfies(callback)` and `Truly(callback)` take ownership of `callback`,
which must be a permanent callback.
#### Using Matchers as Predicates {#MatchersAsPredicatesCheat}
<!-- mdformat off(no multiline tables) -->
| 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`. |
<!-- mdformat on -->
#### Defining Matchers
<!-- mdformat off(no multiline tables) -->
| 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`]. |
<!-- mdformat on -->
**Notes:**
1. The `MATCHER*` macros cannot be used inside a function or class.
2. 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).
3. You can use `PrintToString(x)` to convert a value `x` of any type to a
string.
### Actions {#ActionList}
**Actions** specify what a mock function should do when invoked.
#### Returning a Value
<!-- mdformat off(no multiline tables) -->
| | |
| :-------------------------- | :-------------------------------------------- |
| `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. |
<!-- mdformat on -->
#### Side Effects
<!-- mdformat off(no multiline tables) -->
| | |
| :--------------------------------- | :-------------------------------------- |
| `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. |
<!-- mdformat on -->
#### Using a Function, Functor, or Lambda as an Action
In the following, by "callable" we mean a free function, `std::function`,
functor, or lambda.
<!-- mdformat off(no multiline tables) -->
| | |
| :---------------------------------- | :------------------------------------- |
| `f` | Invoke f with the arguments passed to the mock function, where f is a callable. |
| `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. |
<!-- mdformat on -->
The return value of the invoked function is used as the return value of the
action.
When defining a callable to be used with `Invoke*()`, you can declare any unused
parameters as `Unused`:
```cpp
using ::testing::Invoke;
double Distance(Unused, double x, double y) { return sqrt(x*x + y*y); }
...
EXPECT_CALL(mock, Foo("Hi", _, _)).WillOnce(Invoke(Distance));
```
`Invoke(callback)` and `InvokeWithoutArgs(callback)` take ownership of
`callback`, which must be permanent. The type of `callback` must be a base
callback type instead of a derived one, e.g.
```cpp
BlockingClosure* done = new BlockingClosure;
... Invoke(done) ...; // This won't compile!
Closure* done2 = new BlockingClosure;
... Invoke(done2) ...; // This works.
```
In `InvokeArgument<N>(...)`, if an argument needs to be passed by reference,
wrap it inside `ByRef()`. For example,
```cpp
using ::testing::ByRef;
using ::testing::InvokeArgument;
...
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
<!-- mdformat off(no multiline tables) -->
| Matcher | Description |
| :------------ | :----------------------------------------------------- |
| `DoDefault()` | Do the default action (specified by `ON_CALL()` or the built-in one). |
<!-- mdformat on -->
**Note:** due to technical reasons, `DoDefault()` cannot be used inside a
composite action - trying to do so will result in a run-time error.
<!-- GOOGLETEST_CM0032 DO NOT DELETE -->
#### Composite Actions
<!-- mdformat off(no multiline tables) -->
| | |
| :----------------------------- | :------------------------------------------ |
| `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. |
<!-- mdformat on -->
#### Defining Actions
<table border="1" cellspacing="0" cellpadding="1">
<tr>
<td>`struct SumAction {` <br>
&emsp;`template <typename T>` <br>
&emsp;`T operator()(T x, Ty) { return x + y; }` <br>
`};`
</td>
<td> Defines a generic functor that can be used as an action summing its
arguments. </td> </tr>
<tr>
</tr>
</table>
<!-- mdformat off(no multiline tables) -->
| | |
| :--------------------------------- | :-------------------------------------- |
| `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`. |
<!-- mdformat on -->
The `ACTION*` macros cannot be used inside a function or class.
### Cardinalities {#CardinalityList}
These are used in `Times()` to specify how many times a mock function will be
called:
<!-- mdformat off(no multiline tables) -->
| | |
| :---------------- | :----------------------------------------------------- |
| `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. |
<!-- mdformat on -->
### 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 {#AfterClause}
```cpp
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:
```cpp
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 {#UsingSequences}
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. *All expected calls* in the same sequence must
occur in the order they are specified.
```cpp
using ::testing::Return;
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:
```cpp
using ::testing::InSequence;
{
InSequence seq;
EXPECT_CALL(...)...;
EXPECT_CALL(...)...;
...
EXPECT_CALL(...)...;
}
```
says that all expected calls in the scope of `seq` must occur in strict order.
The name `seq` is irrelevant.
### Verifying and Resetting a Mock
gMock 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;
// returns true if and only if successful.
Mock::VerifyAndClearExpectations(&mock_obj);
...
// Verifies and removes the expectations on mock_obj;
// also removes the default actions set by ON_CALL();
// returns true if and only if successful.
Mock::VerifyAndClear(&mock_obj);
```
You can also tell gMock that a mock object can be leaked and doesn't need to be
verified:
```cpp
Mock::AllowLeak(&mock_obj);
```
### Mock Classes
gMock defines a convenient mock class template
```cpp
class MockFunction<R(A1, ..., An)> {
public:
MOCK_METHOD(R, Call, (A1, ..., An));
};
```
See this [recipe](cook_book.md#using-check-points) for one application of it.
### Flags
<!-- mdformat off(no multiline tables) -->
| 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. |
<!-- mdformat on -->

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,700 @@
## gMock for Dummies {#GMockForDummies}
<!-- GOOGLETEST_CM0013 DO NOT DELETE -->
### What Is gMock?
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 shall become much
clearer once you start to use mocks.
**gMock** 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/EasyMock does to Java (well, more or less).
When using gMock,
1. first, you use some simple macros to describe the interface you want to
mock, and they will expand to the implementation of your mock class;
2. next, you create some mock objects and specify its expectations and behavior
using an intuitive syntax;
3. then you exercise code that uses the mock objects. gMock will catch any
violation to the expectations as soon as it arises.
### Why gMock?
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
one.
In contrast, Java and Python programmers have some fine mock frameworks (jMock,
EasyMock, [Mox](http://wtf/mox), etc), 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.
gMock was built to help C++ programmers. It was inspired by jMock and EasyMock,
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, but it's 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 gMock 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
gMock is bundled with googletest.
### A Case for Mock Turtles
Let's look at an example. Suppose you are developing a graphics program that
relies on a [LOGO](http://en.wikipedia.org/wiki/Logo_programming_language)-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](http://en.wikipedia.org/wiki/Dependency_injection) and know the right thing
to do: instead of having your application talk to the system API directly, wrap
the API in an interface (say, `Turtle`) and code to that interface:
```cpp
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 - gMock 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:
* Derive a class `MockTurtle` from `Turtle`.
* Take a *virtual* function of `Turtle` (while it's possible to
[mock non-virtual methods using templates](cook_book.md#MockingNonVirtualMethods),
it's much more involved).
* In the `public:` section of the child class, write `MOCK_METHOD();`
* Now comes the fun part: you take the function signature, cut-and-paste it
into the macro, and add two commas - one between the return type and the
name, another between the name and the argument list.
* If you're mocking a const method, add a 4th parameter containing `(const)`
(the parentheses are required).
* Since you're overriding a virtual method, we suggest adding the `override`
keyword. For const methods the 4th parameter becomes `(const, override)`,
for non-const methods just `(override)`. This isn't mandatory.
* Repeat until all virtual functions you want to mock are done. (It goes
without saying that *all* pure virtual methods in your abstract class must
be either mocked or overridden.)
After the process, you should have something like:
```cpp
#include "gmock/gmock.h" // Brings in gMock.
class MockTurtle : public Turtle {
public:
...
MOCK_METHOD(void, PenUp, (), (override));
MOCK_METHOD(void, PenDown, (), (override));
MOCK_METHOD(void, Forward, (int distance), (override));
MOCK_METHOD(void, Turn, (int degrees), (override));
MOCK_METHOD(void, GoTo, (int x, int y), (override));
MOCK_METHOD(int, GetX, (), (const, override));
MOCK_METHOD(int, GetY, (), (const, override));
};
```
You don't need to define these mock methods somewhere else - the `MOCK_METHOD`
macro will generate the definitions for you. It's that simple!
#### 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), put
it in a `.h` and a `cc_library`. Then everyone can reference them 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.
<!-- GOOGLETEST_CM0029 DO NOT DELETE -->
### Using Mocks in Tests
Once you have a mock class, using it is easy. The typical work flow is:
1. Import the gMock 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.
2. Create some mock objects.
3. Specify your expectations on them (How many times will a method be called?
With what arguments? What should it do? etc.).
4. Exercise some code that uses the mocks; optionally, check the result using
googletest assertions. If a mock method is called more than expected or with
wrong arguments, you'll get an error immediately.
5. When a mock is destructed, gMock will automatically check whether all
expectations on it have been satisfied.
Here's an example:
```cpp
#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
}
```
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:
```text
path/to/my_test.cc:119: Failure
Actual function call count doesn't match this expectation:
Actually: never called;
Expected: called at least once.
Stack trace:
...
```
**Tip 1:** If you run the test from an Emacs buffer, you can hit <Enter> on the
line number 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 turn on the heap checker in your tests
when you allocate mocks on the heap. You get that automatically if you use the
`gtest_main` library already.
**Important note:** gMock 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 gMock work like that?
Well, specifying the expectation beforehand allows gMock to report a violation
as soon as it rises, 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 gMock. However, as we shall reveal soon, gMock
allows you to do *so much more* with the mocks.
### 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. gMock provides the necessary means for you to do it "just
right."
#### General Syntax
In gMock 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)
.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.)
If the method is not overloaded, the macro can also be called without matchers:
```cpp
EXPECT_CALL(mock_object, non-overloaded-method)
.Times(cardinality)
.WillOnce(action)
.WillRepeatedly(action);
```
This syntax allows the test writer to specify "called with any arguments"
without explicitly specifying the number or types of arguments. To avoid
unintended ambiguity, this syntax may only be used for methods which are not
overloaded
Either form of 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
```cpp
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? Well it serves two purposes: first
it makes expectations easily identifiable (either by `gsearch` or by a human
reader), and second it allows gMock 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 may specify what arguments we are
expecting, for example:
```cpp
// Expects the turtle to move forward by 100 units.
EXPECT_CALL(turtle, Forward(100));
```
Oftentimes you do 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 aren't interested in the value of an argument, write `_`
as the argument, which means "anything goes":
```cpp
using ::testing::_;
...
// Expects that the turtle jumps to somewhere on the x=50 line.
EXPECT_CALL(turtle, GoTo(50, _));
```
`_` 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. `_` is a
convenient way of saying "any value".
In the above examples, `100` and `50` are also matchers; implicitly, they are
the same as `Eq(100)` and `Eq(50)`, which specify that the argument must be
equal (using `operator==`) to the matcher argument. There are many
[built-in matchers](#MatcherList) for common types (as well as
[custom matchers](cook_book.md#NewMatchers)); for example:
```cpp
using ::testing::Ge;
...
// Expects the turtle moves forward by at least 100.
EXPECT_CALL(turtle, Forward(Ge(100)));
```
If you don't care about *any* arguments, rather than specify `_` for each of
them you may instead omit the parameter list:
```cpp
// Expects the turtle to move forward.
EXPECT_CALL(turtle, Forward);
// Expects the turtle to jump somewhere.
EXPECT_CALL(turtle, GoTo);
```
This works for all non-overloaded methods; if a method is overloaded, you need
to help gMock resolve which overload is expected by specifying the number of
arguments and possibly also the
[types of the arguments](cook_book.md#SelectOverload).
#### 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
gMock will report a googletest 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
[here](cheat_sheet.md#CardinalityList).
The `Times()` clause can be omitted. **If you omit `Times()`, gMock 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
gMock.
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). In
addition, in C++ 11 and above, a mock function whose return type is
default-constructible (i.e. has a default constructor) has a default action of
returning a default-constructed value. 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,
```cpp
using ::testing::Return;
...
EXPECT_CALL(turtle, GetX())
.WillOnce(Return(100))
.WillOnce(Return(200))
.WillOnce(Return(300));
```
says that `turtle.GetX()` will be called *exactly three times* (gMock 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.
```cpp
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* (gMock knows this as
we've written two `WillOnce()` clauses and a `WillRepeatedly()` while having no
explicit `Times()`), will return 100 and 200 respectively the first two times,
and 300 from the third time on.
Of course, if you explicitly write a `Times()`, gMock 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, gMock 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](cook_book.md#using-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:
```cpp
using ::testing::Return;
...
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
[cook book](http://<!-- GOOGLETEST_CM0012 DO NOT DELETE -->).
Time for another quiz! What do you think the following means?
```cpp
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 {#MultiExpectations}
So far we've only shown examples where you have a single expectation. More
realistically, you'll specify expectations on multiple mock methods which may be
from multiple mock objects.
By default, when a mock method is invoked, gMock 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:
```cpp
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.
**Note:** Why does gMock 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.
**Tip:** It is very common to start with a catch-all expectation for a method
and `Times(AnyNumber())` (omitting arguments, or with `_` for all arguments, if
overloaded). This makes any calls to the method expected. This is not necessary
for methods that are not mentioned at all (these are "uninteresting"), but is
useful for methods that have some expectations, but for which other calls are
ok. See
[Understanding Uninteresting vs Unexpected Calls](cook_book.md#uninteresting-vs-unexpected).
#### Ordered vs Unordered Calls {#OrderedCalls}
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 gMock is easy:
```cpp
using ::testing::InSequence;
...
TEST(FooTest, DrawsLineSegment) {
...
{
InSequence seq;
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! The
details can be found [here](cook_book.md#OrderedCalls).)
#### All Expectations Are Sticky (Unless Said Otherwise) {#StickyExpectations}
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!):
```cpp
using ::testing::_;
using ::testing::AnyNumber;
...
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, gMock 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, gMock will report an error immediately. This is basically what we've
told you in the [Using Multiple Expectations](#MultiExpectations) section above.
This example shows that **expectations in gMock 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?
```cpp
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 violated" 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:
```cpp
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:
```cpp
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 gMock, 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. This is called "naggy" behavior; to change, see
[The Nice, the Strict, and the Naggy](cook_book.md#NiceStrictNaggy).

View File

@ -0,0 +1,396 @@
## Legacy gMock FAQ {#GMockFaq}
<!-- GOOGLETEST_CM0021 DO NOT DELETE -->
### 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](#MockingNonVirtualMethods).
### Can I mock a variadic function?
You cannot mock a variadic function (i.e. a function taking ellipsis (`...`)
arguments) directly in gMock.
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 or her 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:
```cpp
class Foo {
...
virtual void Bar(const int i) = 0;
};
class MockFoo : public Foo {
...
MOCK_METHOD(void, Bar, (const int i), (override));
};
```
You may get the following warning:
```shell
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:
```shell
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:
```cpp
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:
```cpp
void Bar(int* p); // Neither p nor *p is const.
void Bar(const int* p); // p is not const, but *p is.
```
<!-- GOOGLETEST_CM0030 DO NOT DELETE -->
### I can't figure out why gMock thinks my expectations are not satisfied. What should I do?
You might want to run your test with `--gmock_verbose=info`. This flag lets
gMock 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.
If you see the message "The mock function has no default action set, and its
return type has no default value set.", then try
[adding a default action](for_dummies.md#DefaultValue). Due to a known issue,
unexpected calls on mocks without default actions don't print out a detailed
comparison between the actual arguments and the expected arguments.
### My program crashed and `ScopedMockLog` spit out tons of messages. Is it a gMock bug?
gMock and `ScopedMockLog` are likely doing the right thing here.
When a test crashes, the failure signal handler will try to log a lot of
information (the stack trace, and the address map, for example). The messages
are compounded if you have many threads with depth stacks. When `ScopedMockLog`
intercepts these messages and finds that they don't match any expectations, it
prints an error for each of them.
You can learn to ignore the errors, or you can rewrite your expectations to make
your test more robust, for example, by adding something like:
```cpp
using ::testing::AnyNumber;
using ::testing::Not;
...
// Ignores any log not done by us.
EXPECT_CALL(log, Log(_, Not(EndsWith("/my_file.cc")), _))
.Times(AnyNumber());
```
### How can I assert that a function is NEVER called?
```cpp
using ::testing::_;
...
EXPECT_CALL(foo, Bar(_))
.Times(0);
```
<!-- GOOGLETEST_CM0031 DO NOT DELETE -->
### I have a failed test where gMock tells me TWICE that a particular expectation is not satisfied. Isn't this redundant?
When gMock 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, gMock 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 heapcheck 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:
```cpp
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 gMock do that?
When people complain about this, often they are referring to code like:
```cpp
using ::testing::Return;
...
// 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
gMock'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:
```cpp
using ::testing::Return;
...
// 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:
```cpp
using ::testing::Return;
...
// 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 gMock 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
gMock searches from front to back, this very useful pattern won't be possible.
### gMock 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
```cpp
using ::testing::_;
...
EXPECT_CALL(foo, Bar(_))
.WillRepeatedly(...);
```
instead of
```cpp
using ::testing::_;
...
ON_CALL(foo, Bar(_))
.WillByDefault(...);
```
This tells gMock that you do expect the calls and no warning should be printed.
Also, you can control the verbosity by specifying `--gmock_verbose=error`. Other
values are `info` and `warning`. 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 your mock function takes a pointer argument and you want to delete that
argument, you can use testing::DeleteArg<N>() to delete the N'th (zero-indexed)
argument:
```cpp
using ::testing::_;
...
MOCK_METHOD(void, Bar, (X* x, const Y& y));
...
EXPECT_CALL(mock_foo_, Bar(_, _))
.WillOnce(testing::DeleteArg<0>()));
```
### How can I perform an arbitrary action on a mock function's argument?
If you find yourself needing to perform some action that's not supported by
gMock directly, remember that you can define your own actions using
[`MakeAction()`](#NewMonoActions) or
[`MakePolymorphicAction()`](#NewPolyActions), or you can write a stub function
and invoke it using [`Invoke()`](#FunctionsAsActions).
```cpp
using ::testing::_;
using ::testing::Invoke;
...
MOCK_METHOD(void, Bar, (X* p));
...
EXPECT_CALL(mock_foo_, Bar(_))
.WillOnce(Invoke(MyAction(...)));
```
### 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](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. gMock sucks!
I know it's not a question, but you get an answer for free any way. :-)
With gMock, 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 gMock'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, gMock 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, gMock dumps the stack trace when an uninteresting call is encountered.
From that you can figure out which mock function it is, and how it is called.
### I want to define a custom action. Should I use Invoke() or implement the ActionInterface 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
`testing/base/public/gmock-actions.h` for an example.
### I use SetArgPointee() in WillOnce(), but gcc complains about "conflicting return type specified". What does it mean?
You got this error as gMock 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()` that provides a value appropriate to the API
being mocked.
See this [recipe](cook_book.md#mocking-side-effects) for more details and an
example.
### 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.

View File

@ -42,15 +42,19 @@
#endif
#include <algorithm>
#include <functional>
#include <memory>
#include <string>
#include <type_traits>
#include <utility>
#include "gmock/internal/gmock-internal-utils.h"
#include "gmock/internal/gmock-port.h"
#if GTEST_LANG_CXX11 // Defined by gtest-port.h via gmock-port.h.
#include <functional>
#include <type_traits>
#endif // GTEST_LANG_CXX11
#ifdef _MSC_VER
# pragma warning(push)
# pragma warning(disable:4100)
#endif
namespace testing {
@ -65,9 +69,6 @@ namespace testing {
namespace internal {
template <typename F1, typename F2>
class ActionAdaptor;
// BuiltInDefaultValueGetter<T, true>::Get() returns a
// default-constructed T value. BuiltInDefaultValueGetter<T,
// false>::Get() crashes with an error.
@ -98,8 +99,8 @@ struct BuiltInDefaultValueGetter<T, false> {
template <typename T>
class BuiltInDefaultValue {
public:
#if GTEST_LANG_CXX11
// This function returns true iff type T has a built-in default value.
// This function returns true if and only if type T has a built-in default
// value.
static bool Exists() {
return ::std::is_default_constructible<T>::value;
}
@ -108,18 +109,6 @@ class BuiltInDefaultValue {
return BuiltInDefaultValueGetter<
T, ::std::is_default_constructible<T>::value>::Get();
}
#else // GTEST_LANG_CXX11
// This function returns true iff type T has a built-in default value.
static bool Exists() {
return false;
}
static T Get() {
return BuiltInDefaultValueGetter<T, false>::Get();
}
#endif // GTEST_LANG_CXX11
};
// This partial specialization says that we use the same built-in
@ -137,7 +126,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
@ -151,9 +140,6 @@ class BuiltInDefaultValue<T*> {
}
GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(void, ); // NOLINT
#if GTEST_HAS_GLOBAL_STRING
GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(::string, "");
#endif // GTEST_HAS_GLOBAL_STRING
GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(::std::string, "");
GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(bool, false);
GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned char, '\0');
@ -220,11 +206,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; }
// Returns true if and only if the user has set the default value for type T.
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.
@ -236,8 +222,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:
@ -250,7 +236,7 @@ class DefaultValue {
class FixedValueProducer : public ValueProducer {
public:
explicit FixedValueProducer(T value) : value_(value) {}
virtual T Produce() { return value_; }
T Produce() override { return value_; }
private:
const T value_;
@ -261,7 +247,7 @@ class DefaultValue {
public:
explicit FactoryValueProducer(FactoryFunction factory)
: factory_(factory) {}
virtual T Produce() { return factory_(); }
T Produce() override { return factory_(); }
private:
const FactoryFunction factory_;
@ -282,12 +268,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; }
// Returns true if and only if the user has set the default value for type T&.
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.
@ -299,8 +283,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:
@ -318,11 +302,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>
@ -347,14 +331,25 @@ class ActionInterface {
// An Action<F> is a copyable and IMMUTABLE (except by assignment)
// object that represents an action to be taken when a mock function
// of type F is called. The implementation of Action<T> is just a
// linked_ptr to const ActionInterface<T>, so copying is fairly cheap.
// Don't inherit from Action!
//
// std::shared_ptr to const ActionInterface<T>. Don't inherit from Action!
// You can view an object implementing ActionInterface<F> as a
// concrete action (including its current state), and an Action<F>
// object as a handle to it.
template <typename F>
class Action {
// Adapter class to allow constructing Action from a legacy ActionInterface.
// New code should create Actions from functors instead.
struct ActionAdapter {
// Adapter must be copyable to satisfy std::function requirements.
::std::shared_ptr<ActionInterface<F>> impl_;
template <typename... Args>
typename internal::Function<F>::Result operator()(Args&&... args) {
return impl_->Perform(
::std::forward_as_tuple(::std::forward<Args>(args)...));
}
};
public:
typedef typename internal::Function<F>::Result Result;
typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
@ -363,7 +358,6 @@ class Action {
// STL containers.
Action() {}
#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).
@ -371,26 +365,19 @@ class Action {
typename = typename ::std::enable_if<
::std::is_constructible<::std::function<F>, G>::value>::type>
Action(G&& fun) : fun_(::std::forward<G>(fun)) {} // NOLINT
#endif
// Constructs an Action from its implementation.
explicit Action(ActionInterface<F>* impl) : impl_(impl) {}
explicit Action(ActionInterface<F>* impl)
: fun_(ActionAdapter{::std::shared_ptr<ActionInterface<F>>(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
// to Func's and Func's return type can be implicitly converted to
// F's.
// to Func's and Func's return type can be implicitly converted to F's.
template <typename Func>
explicit Action(const Action<Func>& action);
explicit Action(const Action<Func>& action) : fun_(action.fun_) {}
// Returns true iff this is the DoDefault() action.
bool IsDoDefault() const {
#if GTEST_LANG_CXX11
return impl_ == nullptr && fun_ == nullptr;
#else
return impl_ == NULL;
#endif
}
// Returns true if and only if this is the DoDefault() action.
bool IsDoDefault() const { return fun_ == nullptr; }
// Performs the action. Note that this method is const even though
// the corresponding method in ActionInterface is not. The reason
@ -402,31 +389,15 @@ class Action {
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);
return internal::Apply(fun_, ::std::move(args));
}
private:
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
// fun_ is an empty function if and only if this is the DoDefault() action.
::std::function<F> fun_;
#endif
internal::linked_ptr<ActionInterface<F> > impl_;
};
// The PolymorphicAction class template makes it easy to implement a
@ -441,7 +412,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.
// }
// ...
// };
@ -469,7 +440,7 @@ class PolymorphicAction {
explicit MonomorphicImpl(const Impl& impl) : impl_(impl) {}
virtual Result Perform(const ArgumentTuple& args) {
Result Perform(const ArgumentTuple& args) override {
return impl_.template Perform<Result>(args);
}
@ -505,31 +476,11 @@ inline PolymorphicAction<Impl> MakePolymorphicAction(const Impl& impl) {
namespace internal {
// Allows an Action<F2> object to pose as an Action<F1>, as long as F2
// and F1 are compatible.
template <typename F1, typename F2>
class ActionAdaptor : public ActionInterface<F1> {
public:
typedef typename internal::Function<F1>::Result Result;
typedef typename internal::Function<F1>::ArgumentTuple ArgumentTuple;
explicit ActionAdaptor(const Action<F2>& from) : impl_(from.impl_) {}
virtual Result Perform(const ArgumentTuple& args) {
return impl_->Perform(args);
}
private:
const internal::linked_ptr<ActionInterface<F2> > impl_;
GTEST_DISALLOW_ASSIGN_(ActionAdaptor);
};
// Helper struct to specialize ReturnAction to execute a move instead of a copy
// on return. Useful for move-only types, but could be used on any type.
template <typename T>
struct ByMoveWrapper {
explicit ByMoveWrapper(T value) : payload(internal::move(value)) {}
explicit ByMoveWrapper(T value) : payload(std::move(value)) {}
T payload;
};
@ -566,12 +517,12 @@ class ReturnAction {
// Constructs a ReturnAction object from the value to be returned.
// 'value' is passed by value instead of by const reference in order
// to allow Return("string literal") to compile.
explicit ReturnAction(R value) : value_(new R(internal::move(value))) {}
explicit ReturnAction(R value) : value_(new R(std::move(value))) {}
// This template type conversion operator allows Return(x) to be
// used in ANY function that returns x's type.
template <typename F>
operator Action<F>() const {
operator Action<F>() const { // NOLINT
// Assert statement belongs here because this is the best place to verify
// conditions on F. It produces the clearest error messages
// in most compilers.
@ -582,8 +533,10 @@ class ReturnAction {
// in the Impl class. But both definitions must be the same.
typedef typename Function<F>::Result Result;
GTEST_COMPILE_ASSERT_(
!is_reference<Result>::value,
!std::is_reference<Result>::value,
use_ReturnRef_instead_of_Return_to_return_a_reference);
static_assert(!std::is_void<Result>::value,
"Can't use Return() on an action expected to return `void`.");
return Action<F>(new Impl<R, F>(value_));
}
@ -602,14 +555,14 @@ class ReturnAction {
// Result to call. ImplicitCast_ forces the compiler to convert R to
// Result without considering explicit constructors, thus resolving the
// ambiguity. value_ is then initialized using its copy constructor.
explicit Impl(const linked_ptr<R>& value)
explicit Impl(const std::shared_ptr<R>& value)
: value_before_cast_(*value),
value_(ImplicitCast_<Result>(value_before_cast_)) {}
virtual Result Perform(const ArgumentTuple&) { return value_; }
Result Perform(const ArgumentTuple&) override { return value_; }
private:
GTEST_COMPILE_ASSERT_(!is_reference<Result>::value,
GTEST_COMPILE_ASSERT_(!std::is_reference<Result>::value,
Result_cannot_be_a_reference_type);
// We save the value before casting just in case it is being cast to a
// wrapper type.
@ -627,24 +580,24 @@ class ReturnAction {
typedef typename Function<F>::Result Result;
typedef typename Function<F>::ArgumentTuple ArgumentTuple;
explicit Impl(const linked_ptr<R>& wrapper)
explicit Impl(const std::shared_ptr<R>& wrapper)
: performed_(false), wrapper_(wrapper) {}
virtual Result Perform(const ArgumentTuple&) {
Result Perform(const ArgumentTuple&) override {
GTEST_CHECK_(!performed_)
<< "A ByMove() action should only be performed once.";
performed_ = true;
return internal::move(wrapper_->payload);
return std::move(wrapper_->payload);
}
private:
bool performed_;
const linked_ptr<R> wrapper_;
const std::shared_ptr<R> wrapper_;
GTEST_DISALLOW_ASSIGN_(Impl);
};
const linked_ptr<R> value_;
const std::shared_ptr<R> value_;
GTEST_DISALLOW_ASSIGN_(ReturnAction);
};
@ -657,13 +610,7 @@ class ReturnNullAction {
// pointer type on compile time.
template <typename Result, typename ArgumentTuple>
static Result Perform(const ArgumentTuple&) {
#if GTEST_LANG_CXX11
return nullptr;
#else
GTEST_COMPILE_ASSERT_(internal::is_pointer<Result>::value,
ReturnNull_can_be_used_to_return_a_pointer_only);
return NULL;
#endif // GTEST_LANG_CXX11
}
};
@ -673,7 +620,7 @@ class ReturnVoidAction {
// Allows Return() to be used in any void-returning function.
template <typename Result, typename ArgumentTuple>
static void Perform(const ArgumentTuple&) {
CompileAssertTypesEqual<void, Result>();
static_assert(std::is_void<Result>::value, "Result should be void.");
}
};
@ -694,7 +641,7 @@ class ReturnRefAction {
// Asserts that the function return type is a reference. This
// catches the user error of using ReturnRef(x) when Return(x)
// should be used, and generates some helpful error message.
GTEST_COMPILE_ASSERT_(internal::is_reference<Result>::value,
GTEST_COMPILE_ASSERT_(std::is_reference<Result>::value,
use_Return_instead_of_ReturnRef_to_return_a_value);
return Action<F>(new Impl<F>(ref_));
}
@ -709,9 +656,7 @@ class ReturnRefAction {
explicit Impl(T& ref) : ref_(ref) {} // NOLINT
virtual Result Perform(const ArgumentTuple&) {
return ref_;
}
Result Perform(const ArgumentTuple&) override { return ref_; }
private:
T& ref_;
@ -743,7 +688,7 @@ class ReturnRefOfCopyAction {
// catches the user error of using ReturnRefOfCopy(x) when Return(x)
// should be used, and generates some helpful error message.
GTEST_COMPILE_ASSERT_(
internal::is_reference<Result>::value,
std::is_reference<Result>::value,
use_Return_instead_of_ReturnRefOfCopy_to_return_a_value);
return Action<F>(new Impl<F>(value_));
}
@ -758,9 +703,7 @@ class ReturnRefOfCopyAction {
explicit Impl(const T& value) : value_(value) {} // NOLINT
virtual Result Perform(const ArgumentTuple&) {
return value_;
}
Result Perform(const ArgumentTuple&) override { return value_; }
private:
T value_;
@ -827,114 +770,58 @@ class SetErrnoAndReturnAction {
#endif // !GTEST_OS_WINDOWS_MOBILE
// Implements the SetArgumentPointee<N>(x) action for any function
// whose N-th argument (0-based) is a pointer to x's type. The
// template parameter kIsProto is true iff type A is ProtocolMessage,
// proto2::Message, or a sub-class of those.
template <size_t N, typename A, bool kIsProto>
class SetArgumentPointeeAction {
public:
// Constructs an action that sets the variable pointed to by the
// N-th function argument to 'value'.
explicit SetArgumentPointeeAction(const A& value) : value_(value) {}
// whose N-th argument (0-based) is a pointer to x's type.
template <size_t N, typename A, typename = void>
struct SetArgumentPointeeAction {
A value;
template <typename Result, typename ArgumentTuple>
void Perform(const ArgumentTuple& args) const {
CompileAssertTypesEqual<void, Result>();
*::testing::get<N>(args) = value_;
template <typename... Args>
void operator()(const Args&... args) const {
*::std::get<N>(std::tie(args...)) = value;
}
private:
const A value_;
GTEST_DISALLOW_ASSIGN_(SetArgumentPointeeAction);
};
template <size_t N, typename Proto>
class SetArgumentPointeeAction<N, Proto, true> {
public:
// Constructs an action that sets the variable pointed to by the
// N-th function argument to 'proto'. Both ProtocolMessage and
// proto2::Message have the CopyFrom() method, so the same
// implementation works for both.
explicit SetArgumentPointeeAction(const Proto& proto) : proto_(new Proto) {
proto_->CopyFrom(proto);
// Implements the Invoke(object_ptr, &Class::Method) action.
template <class Class, typename MethodPtr>
struct InvokeMethodAction {
Class* const obj_ptr;
const MethodPtr method_ptr;
template <typename... Args>
auto operator()(Args&&... args) const
-> decltype((obj_ptr->*method_ptr)(std::forward<Args>(args)...)) {
return (obj_ptr->*method_ptr)(std::forward<Args>(args)...);
}
template <typename Result, typename ArgumentTuple>
void Perform(const ArgumentTuple& args) const {
CompileAssertTypesEqual<void, Result>();
::testing::get<N>(args)->CopyFrom(*proto_);
}
private:
const internal::linked_ptr<Proto> proto_;
GTEST_DISALLOW_ASSIGN_(SetArgumentPointeeAction);
};
// Implements the InvokeWithoutArgs(f) action. The template argument
// FunctionImpl is the implementation type of f, which can be either a
// function pointer or a functor. InvokeWithoutArgs(f) can be used as an
// Action<F> as long as f's type is compatible with F (i.e. f can be
// assigned to a tr1::function<F>).
// Action<F> as long as f's type is compatible with F.
template <typename FunctionImpl>
class InvokeWithoutArgsAction {
public:
// The c'tor makes a copy of function_impl (either a function
// pointer or a functor).
explicit InvokeWithoutArgsAction(FunctionImpl function_impl)
: function_impl_(function_impl) {}
struct InvokeWithoutArgsAction {
FunctionImpl function_impl;
// Allows InvokeWithoutArgs(f) to be used as any action whose type is
// compatible with f.
template <typename Result, typename ArgumentTuple>
Result Perform(const ArgumentTuple&) { return function_impl_(); }
private:
FunctionImpl function_impl_;
GTEST_DISALLOW_ASSIGN_(InvokeWithoutArgsAction);
template <typename... Args>
auto operator()(const Args&...) -> decltype(function_impl()) {
return function_impl();
}
};
// Implements the InvokeWithoutArgs(object_ptr, &Class::Method) action.
template <class Class, typename MethodPtr>
class InvokeMethodWithoutArgsAction {
public:
InvokeMethodWithoutArgsAction(Class* obj_ptr, MethodPtr method_ptr)
: obj_ptr_(obj_ptr), method_ptr_(method_ptr) {}
struct InvokeMethodWithoutArgsAction {
Class* const obj_ptr;
const MethodPtr method_ptr;
template <typename Result, typename ArgumentTuple>
Result Perform(const ArgumentTuple&) const {
return (obj_ptr_->*method_ptr_)();
using ReturnType = typename std::result_of<MethodPtr(Class*)>::type;
template <typename... Args>
ReturnType operator()(const Args&...) const {
return (obj_ptr->*method_ptr)();
}
private:
Class* const obj_ptr_;
const MethodPtr method_ptr_;
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.
@ -956,7 +843,7 @@ class IgnoreResultAction {
typedef typename internal::Function<F>::Result Result;
// Asserts at compile time that F returns void.
CompileAssertTypesEqual<void, Result>();
static_assert(std::is_void<Result>::value, "Result type should be void.");
return Action<F>(new Impl<F>(action_));
}
@ -970,7 +857,7 @@ class IgnoreResultAction {
explicit Impl(const A& action) : action_(action) {}
virtual void Perform(const ArgumentTuple& args) {
void Perform(const ArgumentTuple& args) override {
// Performs the action and ignores its result.
action_.Perform(args);
}
@ -991,76 +878,51 @@ class IgnoreResultAction {
GTEST_DISALLOW_ASSIGN_(IgnoreResultAction);
};
// A ReferenceWrapper<T> object represents a reference to type T,
// which can be either const or not. It can be explicitly converted
// from, and implicitly converted to, a T&. Unlike a reference,
// ReferenceWrapper<T> can be copied and can survive template type
// inference. This is used to support by-reference arguments in the
// InvokeArgument<N>(...) action. The idea was from "reference
// wrappers" in tr1, which we don't have in our source tree yet.
template <typename T>
class ReferenceWrapper {
public:
// Constructs a ReferenceWrapper<T> object from a T&.
explicit ReferenceWrapper(T& l_value) : pointer_(&l_value) {} // NOLINT
template <typename InnerAction, size_t... I>
struct WithArgsAction {
InnerAction action;
// Allows a ReferenceWrapper<T> object to be implicitly converted to
// a T&.
operator T&() const { return *pointer_; }
private:
T* pointer_;
// The inner action could be anything convertible to Action<X>.
// We use the conversion operator to detect the signature of the inner Action.
template <typename R, typename... Args>
operator Action<R(Args...)>() const { // NOLINT
Action<R(typename std::tuple_element<I, std::tuple<Args...>>::type...)>
converted(action);
return [converted](Args... args) -> R {
return converted.Perform(std::forward_as_tuple(
std::get<I>(std::forward_as_tuple(std::forward<Args>(args)...))...));
};
}
};
// Allows the expression ByRef(x) to be printed as a reference to x.
template <typename T>
void PrintTo(const ReferenceWrapper<T>& ref, ::std::ostream* os) {
T& value = ref;
UniversalPrinter<T&>::Print(value, os);
}
// Does two actions sequentially. Used for implementing the DoAll(a1,
// a2, ...) action.
template <typename Action1, typename Action2>
class DoBothAction {
public:
DoBothAction(Action1 action1, Action2 action2)
: action1_(action1), action2_(action2) {}
// This template type conversion operator allows DoAll(a1, ..., a_n)
// to be used in ANY function of compatible type.
template <typename F>
operator Action<F>() const {
return Action<F>(new Impl<F>(action1_, action2_));
template <typename... Actions>
struct DoAllAction {
private:
template <typename... Args, size_t... I>
std::vector<Action<void(Args...)>> Convert(IndexSequence<I...>) const {
return {std::get<I>(actions)...};
}
private:
// Implements the DoAll(...) action for a particular function type F.
template <typename F>
class Impl : public ActionInterface<F> {
public:
typedef typename Function<F>::Result Result;
typedef typename Function<F>::ArgumentTuple ArgumentTuple;
typedef typename Function<F>::MakeResultVoid VoidResult;
public:
std::tuple<Actions...> actions;
Impl(const Action<VoidResult>& action1, const Action<F>& action2)
: action1_(action1), action2_(action2) {}
virtual Result Perform(const ArgumentTuple& args) {
action1_.Perform(args);
return action2_.Perform(args);
}
private:
const Action<VoidResult> action1_;
const Action<F> action2_;
GTEST_DISALLOW_ASSIGN_(Impl);
};
Action1 action1_;
Action2 action2_;
GTEST_DISALLOW_ASSIGN_(DoBothAction);
template <typename R, typename... Args>
operator Action<R(Args...)>() const { // NOLINT
struct Op {
std::vector<Action<void(Args...)>> converted;
Action<R(Args...)> last;
R operator()(Args... args) const {
auto tuple_args = std::forward_as_tuple(std::forward<Args>(args)...);
for (auto& a : converted) {
a.Perform(tuple_args);
}
return last.Perform(tuple_args);
}
};
return Op{Convert<Args...>(MakeIndexSequence<sizeof...(Actions) - 1>()),
std::get<sizeof...(Actions) - 1>(actions)};
}
};
} // namespace internal
@ -1097,19 +959,43 @@ class DoBothAction {
// EXPECT_CALL(mock, Bar(5, _, _)).WillOnce(Invoke(DistanceToOrigin));
typedef internal::IgnoredValue Unused;
// This constructor allows us to turn an Action<From> object into an
// Action<To>, as long as To's arguments can be implicitly converted
// to From's and From's return type cann be implicitly converted to
// To's.
template <typename To>
template <typename From>
Action<To>::Action(const Action<From>& from)
:
#if GTEST_LANG_CXX11
fun_(from.fun_),
#endif
impl_(from.impl_ == NULL ? NULL
: new internal::ActionAdaptor<To, From>(from)) {
// Creates an action that does actions a1, a2, ..., sequentially in
// each invocation.
template <typename... Action>
internal::DoAllAction<typename std::decay<Action>::type...> DoAll(
Action&&... action) {
return {std::forward_as_tuple(std::forward<Action>(action)...)};
}
// WithArg<k>(an_action) creates an action that passes the k-th
// (0-based) argument of the mock function to an_action and performs
// it. It adapts an action accepting one argument to one that accepts
// multiple arguments. For convenience, we also provide
// WithArgs<k>(an_action) (defined below) as a synonym.
template <size_t k, typename InnerAction>
internal::WithArgsAction<typename std::decay<InnerAction>::type, k>
WithArg(InnerAction&& action) {
return {std::forward<InnerAction>(action)};
}
// WithArgs<N1, N2, ..., Nk>(an_action) creates an action that passes
// the selected arguments of the mock function to an_action and
// performs it. It serves as an adaptor between actions with
// different argument lists.
template <size_t k, size_t... ks, typename InnerAction>
internal::WithArgsAction<typename std::decay<InnerAction>::type, k, ks...>
WithArgs(InnerAction&& action) {
return {std::forward<InnerAction>(action)};
}
// WithoutArgs(inner_action) can be used in a mock function with a
// non-empty argument list to perform inner_action, which takes no
// argument. In other words, it adapts an action accepting no
// argument to one that accepts (and ignores) arguments.
template <typename InnerAction>
internal::WithArgsAction<typename std::decay<InnerAction>::type>
WithoutArgs(InnerAction&& action) {
return {std::forward<InnerAction>(action)};
}
// Creates an action that returns 'value'. 'value' is passed by value
@ -1117,7 +1003,7 @@ Action<To>::Action(const Action<From>& from)
// will trigger a compiler error about using array as initializer.
template <typename R>
internal::ReturnAction<R> Return(R value) {
return internal::ReturnAction<R>(internal::move(value));
return internal::ReturnAction<R>(std::move(value));
}
// Creates an action that returns NULL.
@ -1150,7 +1036,7 @@ inline internal::ReturnRefOfCopyAction<R> ReturnRefOfCopy(const R& x) {
// invariant.
template <typename R>
internal::ByMoveWrapper<R> ByMove(R x) {
return internal::ByMoveWrapper<R>(internal::move(x));
return internal::ByMoveWrapper<R>(std::move(x));
}
// Creates an action that does the default action for the give mock function.
@ -1161,43 +1047,14 @@ inline internal::DoDefaultAction DoDefault() {
// Creates an action that sets the variable pointed by the N-th
// (0-based) function argument to 'value'.
template <size_t N, typename T>
PolymorphicAction<
internal::SetArgumentPointeeAction<
N, T, internal::IsAProtocolMessage<T>::value> >
SetArgPointee(const T& x) {
return MakePolymorphicAction(internal::SetArgumentPointeeAction<
N, T, internal::IsAProtocolMessage<T>::value>(x));
internal::SetArgumentPointeeAction<N, T> SetArgPointee(T x) {
return {std::move(x)};
}
#if !((GTEST_GCC_VER_ && GTEST_GCC_VER_ < 40000) || GTEST_OS_SYMBIAN)
// This overload allows SetArgPointee() to accept a string literal.
// GCC prior to the version 4.0 and Symbian C++ compiler cannot distinguish
// this overload from the templated version and emit a compile error.
template <size_t N>
PolymorphicAction<
internal::SetArgumentPointeeAction<N, const char*, false> >
SetArgPointee(const char* p) {
return MakePolymorphicAction(internal::SetArgumentPointeeAction<
N, const char*, false>(p));
}
template <size_t N>
PolymorphicAction<
internal::SetArgumentPointeeAction<N, const wchar_t*, false> >
SetArgPointee(const wchar_t* p) {
return MakePolymorphicAction(internal::SetArgumentPointeeAction<
N, const wchar_t*, false>(p));
}
#endif
// The following version is DEPRECATED.
template <size_t N, typename T>
PolymorphicAction<
internal::SetArgumentPointeeAction<
N, T, internal::IsAProtocolMessage<T>::value> >
SetArgumentPointee(const T& x) {
return MakePolymorphicAction(internal::SetArgumentPointeeAction<
N, T, internal::IsAProtocolMessage<T>::value>(x));
internal::SetArgumentPointeeAction<N, T> SetArgumentPointee(T x) {
return {std::move(x)};
}
// Creates an action that sets a pointer referent to a given value.
@ -1218,24 +1075,38 @@ SetErrnoAndReturn(int errval, T result) {
#endif // !GTEST_OS_WINDOWS_MOBILE
// Various overloads for InvokeWithoutArgs().
// Various overloads for Invoke().
// Legacy function.
// Actions can now be implicitly constructed from callables. No need to create
// wrapper objects.
// This function exists for backwards compatibility.
template <typename FunctionImpl>
typename std::decay<FunctionImpl>::type Invoke(FunctionImpl&& function_impl) {
return std::forward<FunctionImpl>(function_impl);
}
// Creates an action that invokes the given method on the given object
// with the mock function's arguments.
template <class Class, typename MethodPtr>
internal::InvokeMethodAction<Class, MethodPtr> Invoke(Class* obj_ptr,
MethodPtr method_ptr) {
return {obj_ptr, method_ptr};
}
// Creates an action that invokes 'function_impl' with no argument.
template <typename FunctionImpl>
PolymorphicAction<internal::InvokeWithoutArgsAction<FunctionImpl> >
internal::InvokeWithoutArgsAction<typename std::decay<FunctionImpl>::type>
InvokeWithoutArgs(FunctionImpl function_impl) {
return MakePolymorphicAction(
internal::InvokeWithoutArgsAction<FunctionImpl>(function_impl));
return {std::move(function_impl)};
}
// Creates an action that invokes the given method on the given object
// with no argument.
template <class Class, typename MethodPtr>
PolymorphicAction<internal::InvokeMethodWithoutArgsAction<Class, MethodPtr> >
InvokeWithoutArgs(Class* obj_ptr, MethodPtr method_ptr) {
return MakePolymorphicAction(
internal::InvokeMethodWithoutArgsAction<Class, MethodPtr>(
obj_ptr, method_ptr));
internal::InvokeMethodWithoutArgsAction<Class, MethodPtr> InvokeWithoutArgs(
Class* obj_ptr, MethodPtr method_ptr) {
return {obj_ptr, method_ptr};
}
// Creates an action that performs an_action and throws away its
@ -1253,11 +1124,19 @@ inline internal::IgnoreResultAction<A> IgnoreResult(const A& an_action) {
// where Base is a base class of Derived, just write:
//
// ByRef<const Base>(derived)
//
// N.B. ByRef is redundant with std::ref, std::cref and std::reference_wrapper.
// However, it may still be used for consistency with ByMove().
template <typename T>
inline internal::ReferenceWrapper<T> ByRef(T& l_value) { // NOLINT
return internal::ReferenceWrapper<T>(l_value);
inline ::std::reference_wrapper<T> ByRef(T& l_value) { // NOLINT
return ::std::reference_wrapper<T>(l_value);
}
} // namespace testing
#ifdef _MSC_VER
# pragma warning(pop)
#endif
#endif // GMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_

View File

@ -40,6 +40,7 @@
#define GMOCK_INCLUDE_GMOCK_GMOCK_CARDINALITIES_H_
#include <limits.h>
#include <memory>
#include <ostream> // NOLINT
#include "gmock/internal/gmock-port.h"
#include "gtest/gtest.h"
@ -69,10 +70,12 @@ class CardinalityInterface {
virtual int ConservativeLowerBound() const { return 0; }
virtual int ConservativeUpperBound() const { return INT_MAX; }
// Returns true iff call_count calls will satisfy this cardinality.
// Returns true if and only if 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.
// Returns true if and only if call_count calls will saturate this
// cardinality.
virtual bool IsSaturatedByCallCount(int call_count) const = 0;
// Describes self to an ostream.
@ -81,9 +84,8 @@ class CardinalityInterface {
// A Cardinality is a copyable and IMMUTABLE (except by assignment)
// object that specifies how many times a mock function is expected to
// be called. The implementation of Cardinality is just a linked_ptr
// to const CardinalityInterface, so copying is fairly cheap.
// Don't inherit from Cardinality!
// be called. The implementation of Cardinality is just a std::shared_ptr
// to const CardinalityInterface. Don't inherit from Cardinality!
class GTEST_API_ Cardinality {
public:
// Constructs a null cardinality. Needed for storing Cardinality
@ -98,17 +100,19 @@ class GTEST_API_ Cardinality {
int ConservativeLowerBound() const { return impl_->ConservativeLowerBound(); }
int ConservativeUpperBound() const { return impl_->ConservativeUpperBound(); }
// Returns true iff call_count calls will satisfy this cardinality.
// Returns true if and only if call_count calls will satisfy this
// cardinality.
bool IsSatisfiedByCallCount(int call_count) const {
return impl_->IsSatisfiedByCallCount(call_count);
}
// Returns true iff call_count calls will saturate this cardinality.
// Returns true if and only if call_count calls will saturate this
// cardinality.
bool IsSaturatedByCallCount(int call_count) const {
return impl_->IsSaturatedByCallCount(call_count);
}
// Returns true iff call_count calls will over-saturate this
// Returns true if and only if call_count calls will over-saturate this
// cardinality, i.e. exceed the maximum number of allowed calls.
bool IsOverSaturatedByCallCount(int call_count) const {
return impl_->IsSaturatedByCallCount(call_count) &&
@ -123,7 +127,7 @@ class GTEST_API_ Cardinality {
::std::ostream* os);
private:
internal::linked_ptr<const CardinalityInterface> impl_;
std::shared_ptr<const CardinalityInterface> impl_;
};
// Creates a cardinality that allows at least n calls.

View File

@ -0,0 +1,253 @@
// Copyright 2007, 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.
// Google Mock - a framework for writing C++ mock classes.
//
// This file implements MOCK_METHOD.
// GOOGLETEST_CM0002 DO NOT DELETE
#ifndef THIRD_PARTY_GOOGLETEST_GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_FUNCTION_MOCKER_H_ // NOLINT
#define THIRD_PARTY_GOOGLETEST_GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_FUNCTION_MOCKER_H_ // NOLINT
#include "gmock/gmock-generated-function-mockers.h" // NOLINT
#include "gmock/internal/gmock-pp.h"
#define MOCK_METHOD(...) \
GMOCK_PP_VARIADIC_CALL(GMOCK_INTERNAL_MOCK_METHOD_ARG_, __VA_ARGS__)
#define GMOCK_INTERNAL_MOCK_METHOD_ARG_1(...) \
GMOCK_INTERNAL_WRONG_ARITY(__VA_ARGS__)
#define GMOCK_INTERNAL_MOCK_METHOD_ARG_2(...) \
GMOCK_INTERNAL_WRONG_ARITY(__VA_ARGS__)
#define GMOCK_INTERNAL_MOCK_METHOD_ARG_3(_Ret, _MethodName, _Args) \
GMOCK_INTERNAL_MOCK_METHOD_ARG_4(_Ret, _MethodName, _Args, ())
#define GMOCK_INTERNAL_MOCK_METHOD_ARG_4(_Ret, _MethodName, _Args, _Spec) \
GMOCK_INTERNAL_ASSERT_PARENTHESIS(_Args); \
GMOCK_INTERNAL_ASSERT_PARENTHESIS(_Spec); \
GMOCK_INTERNAL_ASSERT_VALID_SIGNATURE( \
GMOCK_PP_NARG0 _Args, GMOCK_INTERNAL_SIGNATURE(_Ret, _Args)); \
GMOCK_INTERNAL_ASSERT_VALID_SPEC(_Spec) \
GMOCK_INTERNAL_MOCK_METHOD_IMPL( \
GMOCK_PP_NARG0 _Args, _MethodName, GMOCK_INTERNAL_HAS_CONST(_Spec), \
GMOCK_INTERNAL_HAS_OVERRIDE(_Spec), GMOCK_INTERNAL_HAS_FINAL(_Spec), \
GMOCK_INTERNAL_HAS_NOEXCEPT(_Spec), GMOCK_INTERNAL_GET_CALLTYPE(_Spec), \
(GMOCK_INTERNAL_SIGNATURE(_Ret, _Args)))
#define GMOCK_INTERNAL_MOCK_METHOD_ARG_5(...) \
GMOCK_INTERNAL_WRONG_ARITY(__VA_ARGS__)
#define GMOCK_INTERNAL_MOCK_METHOD_ARG_6(...) \
GMOCK_INTERNAL_WRONG_ARITY(__VA_ARGS__)
#define GMOCK_INTERNAL_MOCK_METHOD_ARG_7(...) \
GMOCK_INTERNAL_WRONG_ARITY(__VA_ARGS__)
#define GMOCK_INTERNAL_WRONG_ARITY(...) \
static_assert( \
false, \
"MOCK_METHOD must be called with 3 or 4 arguments. _Ret, " \
"_MethodName, _Args and optionally _Spec. _Args and _Spec must be " \
"enclosed in parentheses. If _Ret is a type with unprotected commas, " \
"it must also be enclosed in parentheses.")
#define GMOCK_INTERNAL_ASSERT_PARENTHESIS(_Tuple) \
static_assert( \
GMOCK_PP_IS_ENCLOSED_PARENS(_Tuple), \
GMOCK_PP_STRINGIZE(_Tuple) " should be enclosed in parentheses.")
#define GMOCK_INTERNAL_ASSERT_VALID_SIGNATURE(_N, ...) \
static_assert( \
std::is_function<__VA_ARGS__>::value, \
"Signature must be a function type, maybe return type contains " \
"unprotected comma."); \
static_assert( \
::testing::tuple_size<typename ::testing::internal::Function< \
__VA_ARGS__>::ArgumentTuple>::value == _N, \
"This method does not take " GMOCK_PP_STRINGIZE( \
_N) " arguments. Parenthesize all types with unproctected commas.")
#define GMOCK_INTERNAL_ASSERT_VALID_SPEC(_Spec) \
GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_ASSERT_VALID_SPEC_ELEMENT, ~, _Spec)
#define GMOCK_INTERNAL_MOCK_METHOD_IMPL(_N, _MethodName, _Constness, \
_Override, _Final, _Noexcept, \
_CallType, _Signature) \
typename ::testing::internal::Function<GMOCK_PP_REMOVE_PARENS( \
_Signature)>::Result \
GMOCK_INTERNAL_EXPAND(_CallType) \
_MethodName(GMOCK_PP_REPEAT(GMOCK_INTERNAL_PARAMETER, _Signature, _N)) \
GMOCK_PP_IF(_Constness, const, ) GMOCK_PP_IF(_Noexcept, noexcept, ) \
GMOCK_PP_IF(_Override, override, ) \
GMOCK_PP_IF(_Final, final, ) { \
GMOCK_MOCKER_(_N, _Constness, _MethodName) \
.SetOwnerAndName(this, #_MethodName); \
return GMOCK_MOCKER_(_N, _Constness, _MethodName) \
.Invoke(GMOCK_PP_REPEAT(GMOCK_INTERNAL_FORWARD_ARG, _Signature, _N)); \
} \
::testing::MockSpec<GMOCK_PP_REMOVE_PARENS(_Signature)> gmock_##_MethodName( \
GMOCK_PP_REPEAT(GMOCK_INTERNAL_MATCHER_PARAMETER, _Signature, _N)) \
GMOCK_PP_IF(_Constness, const, ) { \
GMOCK_MOCKER_(_N, _Constness, _MethodName).RegisterOwner(this); \
return GMOCK_MOCKER_(_N, _Constness, _MethodName) \
.With(GMOCK_PP_REPEAT(GMOCK_INTERNAL_MATCHER_ARGUMENT, , _N)); \
} \
::testing::MockSpec<GMOCK_PP_REMOVE_PARENS(_Signature)> gmock_##_MethodName( \
const ::testing::internal::WithoutMatchers&, \
GMOCK_PP_IF(_Constness, const, )::testing::internal::Function< \
GMOCK_PP_REMOVE_PARENS(_Signature)>*) \
const GMOCK_PP_IF(_Noexcept, noexcept, ) { \
return GMOCK_PP_CAT(::testing::internal::AdjustConstness_, \
GMOCK_PP_IF(_Constness, const, ))(this) \
->gmock_##_MethodName(GMOCK_PP_REPEAT( \
GMOCK_INTERNAL_A_MATCHER_ARGUMENT, _Signature, _N)); \
} \
mutable ::testing::FunctionMocker<GMOCK_PP_REMOVE_PARENS(_Signature)> \
GMOCK_MOCKER_(_N, _Constness, _MethodName)
#define GMOCK_INTERNAL_EXPAND(...) __VA_ARGS__
// Five Valid modifiers.
#define GMOCK_INTERNAL_HAS_CONST(_Tuple) \
GMOCK_PP_HAS_COMMA(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_DETECT_CONST, ~, _Tuple))
#define GMOCK_INTERNAL_HAS_OVERRIDE(_Tuple) \
GMOCK_PP_HAS_COMMA( \
GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_DETECT_OVERRIDE, ~, _Tuple))
#define GMOCK_INTERNAL_HAS_FINAL(_Tuple) \
GMOCK_PP_HAS_COMMA(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_DETECT_FINAL, ~, _Tuple))
#define GMOCK_INTERNAL_HAS_NOEXCEPT(_Tuple) \
GMOCK_PP_HAS_COMMA( \
GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_DETECT_NOEXCEPT, ~, _Tuple))
#define GMOCK_INTERNAL_GET_CALLTYPE(_Tuple) \
GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_GET_CALLTYPE_IMPL, ~, _Tuple)
#define GMOCK_INTERNAL_ASSERT_VALID_SPEC_ELEMENT(_i, _, _elem) \
static_assert( \
(GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_CONST(_i, _, _elem)) + \
GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_OVERRIDE(_i, _, _elem)) + \
GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_FINAL(_i, _, _elem)) + \
GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_NOEXCEPT(_i, _, _elem)) + \
GMOCK_INTERNAL_IS_CALLTYPE(_elem)) == 1, \
GMOCK_PP_STRINGIZE( \
_elem) " cannot be recognized as a valid specification modifier.");
// Modifiers implementation.
#define GMOCK_INTERNAL_DETECT_CONST(_i, _, _elem) \
GMOCK_PP_CAT(GMOCK_INTERNAL_DETECT_CONST_I_, _elem)
#define GMOCK_INTERNAL_DETECT_CONST_I_const ,
#define GMOCK_INTERNAL_DETECT_OVERRIDE(_i, _, _elem) \
GMOCK_PP_CAT(GMOCK_INTERNAL_DETECT_OVERRIDE_I_, _elem)
#define GMOCK_INTERNAL_DETECT_OVERRIDE_I_override ,
#define GMOCK_INTERNAL_DETECT_FINAL(_i, _, _elem) \
GMOCK_PP_CAT(GMOCK_INTERNAL_DETECT_FINAL_I_, _elem)
#define GMOCK_INTERNAL_DETECT_FINAL_I_final ,
// TODO(iserna): Maybe noexcept should accept an argument here as well.
#define GMOCK_INTERNAL_DETECT_NOEXCEPT(_i, _, _elem) \
GMOCK_PP_CAT(GMOCK_INTERNAL_DETECT_NOEXCEPT_I_, _elem)
#define GMOCK_INTERNAL_DETECT_NOEXCEPT_I_noexcept ,
#define GMOCK_INTERNAL_GET_CALLTYPE_IMPL(_i, _, _elem) \
GMOCK_PP_IF(GMOCK_INTERNAL_IS_CALLTYPE(_elem), \
GMOCK_INTERNAL_GET_VALUE_CALLTYPE, GMOCK_PP_EMPTY) \
(_elem)
// TODO(iserna): GMOCK_INTERNAL_IS_CALLTYPE and
// GMOCK_INTERNAL_GET_VALUE_CALLTYPE needed more expansions to work on windows
// maybe they can be simplified somehow.
#define GMOCK_INTERNAL_IS_CALLTYPE(_arg) \
GMOCK_INTERNAL_IS_CALLTYPE_I( \
GMOCK_PP_CAT(GMOCK_INTERNAL_IS_CALLTYPE_HELPER_, _arg))
#define GMOCK_INTERNAL_IS_CALLTYPE_I(_arg) GMOCK_PP_IS_ENCLOSED_PARENS(_arg)
#define GMOCK_INTERNAL_GET_VALUE_CALLTYPE(_arg) \
GMOCK_INTERNAL_GET_VALUE_CALLTYPE_I( \
GMOCK_PP_CAT(GMOCK_INTERNAL_IS_CALLTYPE_HELPER_, _arg))
#define GMOCK_INTERNAL_GET_VALUE_CALLTYPE_I(_arg) \
GMOCK_PP_CAT(GMOCK_PP_IDENTITY, _arg)
#define GMOCK_INTERNAL_IS_CALLTYPE_HELPER_Calltype
#define GMOCK_INTERNAL_SIGNATURE(_Ret, _Args) \
GMOCK_PP_IF(GMOCK_PP_IS_BEGIN_PARENS(_Ret), GMOCK_PP_REMOVE_PARENS, \
GMOCK_PP_IDENTITY) \
(_Ret)(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_GET_TYPE, _, _Args))
#define GMOCK_INTERNAL_GET_TYPE(_i, _, _elem) \
GMOCK_PP_COMMA_IF(_i) \
GMOCK_PP_IF(GMOCK_PP_IS_BEGIN_PARENS(_elem), GMOCK_PP_REMOVE_PARENS, \
GMOCK_PP_IDENTITY) \
(_elem)
#define GMOCK_INTERNAL_PARAMETER(_i, _Signature, _) \
GMOCK_PP_COMMA_IF(_i) \
GMOCK_INTERNAL_ARG_O(typename, GMOCK_PP_INC(_i), \
GMOCK_PP_REMOVE_PARENS(_Signature)) \
gmock_a##_i
#define GMOCK_INTERNAL_FORWARD_ARG(_i, _Signature, _) \
GMOCK_PP_COMMA_IF(_i) \
::std::forward<GMOCK_INTERNAL_ARG_O(typename, GMOCK_PP_INC(_i), \
GMOCK_PP_REMOVE_PARENS(_Signature))>( \
gmock_a##_i)
#define GMOCK_INTERNAL_MATCHER_PARAMETER(_i, _Signature, _) \
GMOCK_PP_COMMA_IF(_i) \
GMOCK_INTERNAL_MATCHER_O(typename, GMOCK_PP_INC(_i), \
GMOCK_PP_REMOVE_PARENS(_Signature)) \
gmock_a##_i
#define GMOCK_INTERNAL_MATCHER_ARGUMENT(_i, _1, _2) \
GMOCK_PP_COMMA_IF(_i) \
gmock_a##_i
#define GMOCK_INTERNAL_A_MATCHER_ARGUMENT(_i, _Signature, _) \
GMOCK_PP_COMMA_IF(_i) \
::testing::A<GMOCK_INTERNAL_ARG_O(typename, GMOCK_PP_INC(_i), \
GMOCK_PP_REMOVE_PARENS(_Signature))>()
#define GMOCK_INTERNAL_ARG_O(_tn, _i, ...) GMOCK_ARG_(_tn, _i, __VA_ARGS__)
#define GMOCK_INTERNAL_MATCHER_O(_tn, _i, ...) \
GMOCK_MATCHER_(_tn, _i, __VA_ARGS__)
#endif // THIRD_PARTY_GOOGLETEST_GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_FUNCTION_MOCKER_H_

File diff suppressed because it is too large Load Diff

View File

@ -43,173 +43,15 @@ $$}} This meta comment fixes auto-indentation in editors.
#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_ACTIONS_H_
#define GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_ACTIONS_H_
#include <memory>
#include <utility>
#include "gmock/gmock-actions.h"
#include "gmock/internal/gmock-port.h"
namespace testing {
namespace internal {
// InvokeHelper<F> knows how to unpack an N-tuple and invoke an N-ary
// 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)]]]]
template <typename R$types>
class InvokeHelper<R, ::testing::tuple<$as> > {
public:
template <typename Function>
static R Invoke(Function function, const ::testing::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) {
return (obj_ptr->*method_ptr)($gets);
}
$if i <= max_callback_arity [[
template <typename CallbackType>
static R InvokeCallback(CallbackType* callback,
const ::testing::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
$range i 1..n
// 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
// 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))
// returns tuple (2.5, true).
//
// The numbers in list k1, k2, ..., k_n must be >= 0, where n can be
// in the range [0, $n]. Duplicates are allowed and they don't have
// to be in an ascending or descending order.
template <typename Result, typename ArgumentTuple, $for i, [[int k$i]]>
class SelectArgs {
public:
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)]]);
}
};
$for i [[
$range j 1..n
$range j1 1..i-1
template <typename Result, typename ArgumentTuple$for j1[[, int k$j1]]>
class SelectArgs<Result, ArgumentTuple,
$for j, [[$if j <= i-1 [[k$j]] $else [[-1]]]]> {
public:
typedef Result type($for j1, [[GMOCK_FIELD_(ArgumentTuple, k$j1)]]);
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)]]);
}
};
]]
#undef GMOCK_FIELD_
$var ks = [[$for i, [[k$i]]]]
// Implements the WithArgs action.
template <typename InnerAction, $for i, [[int k$i = -1]]>
class WithArgsAction {
public:
explicit WithArgsAction(const InnerAction& action) : action_(action) {}
template <typename F>
operator Action<F>() const { return MakeAction(new Impl<F>(action_)); }
private:
template <typename F>
class Impl : public ActionInterface<F> {
public:
typedef typename Function<F>::Result Result;
typedef typename Function<F>::ArgumentTuple ArgumentTuple;
explicit Impl(const InnerAction& action) : action_(action) {}
virtual Result Perform(const ArgumentTuple& args) {
return action_.Perform(SelectArgs<Result, ArgumentTuple, $ks>::Select(args));
}
private:
typedef typename SelectArgs<Result, ArgumentTuple,
$ks>::type InnerFunctionType;
Action<InnerFunctionType> action_;
};
const InnerAction action_;
GTEST_DISALLOW_ASSIGN_(WithArgsAction);
};
// A macro from the ACTION* family (defined later in this file)
// defines an action that can be used in a mock function. Typically,
// these actions only care about a subset of the arguments of the mock
@ -240,12 +82,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);
}
@ -253,53 +95,6 @@ $template
};
} // namespace internal
// Various overloads for Invoke().
// WithArgs<N1, N2, ..., Nk>(an_action) creates an action that passes
// the selected arguments of the mock function to an_action and
// performs it. It serves as an adaptor between actions with
// different argument lists. C++ doesn't support default arguments for
// function templates, so we have to overload it.
$range i 1..n
$for i [[
$range j 1..i
template <$for j [[int k$j, ]]typename InnerAction>
inline internal::WithArgsAction<InnerAction$for j [[, k$j]]>
WithArgs(const InnerAction& action) {
return internal::WithArgsAction<InnerAction$for j [[, k$j]]>(action);
}
]]
// Creates an action that does actions a1, a2, ..., sequentially in
// each invocation.
$range i 2..n
$for i [[
$range j 2..i
$var types = [[$for j, [[typename Action$j]]]]
$var Aas = [[$for j [[, Action$j a$j]]]]
template <typename Action1, $types>
$range k 1..i-1
inline $for k [[internal::DoBothAction<Action$k, ]]Action$i$for k [[>]]
DoAll(Action1 a1$Aas) {
$if i==2 [[
return internal::DoBothAction<Action1, Action2>(a1, a2);
]] $else [[
$range j2 2..i
return DoAll(a1, DoAll($for j2, [[a$j2]]));
]]
}
]]
} // namespace testing
// The ACTION* family of macros can be used in a namespace scope to
@ -387,16 +182,15 @@ $range j2 2..i
//
// CAVEAT:
//
// ACTION*() can only be used in a namespace scope. The reason is
// that C++ doesn't yet allow function-local types to be used to
// instantiate templates. The up-coming C++0x standard will fix this.
// Once that's done, we'll consider supporting using ACTION*() inside
// a function.
// ACTION*() can only be used in a namespace scope as templates cannot be
// declared inside of a local class.
// Users can, however, define any local functors (e.g. a lambda) that
// can be used as actions.
//
// MORE INFORMATION:
//
// To learn more about using these macros, please search for 'ACTION'
// on https://github.com/google/googletest/blob/master/googlemock/docs/CookBook.md
// To learn more about using these macros, please search for 'ACTION' on
// https://github.com/google/googletest/blob/master/googlemock/docs/cook_book.md
$range i 0..n
$range k 0..n-1
@ -405,7 +199,7 @@ $range k 0..n-1
#define GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_\
const args_type& args GTEST_ATTRIBUTE_UNUSED_
$for k [[, \
arg$k[[]]_type arg$k GTEST_ATTRIBUTE_UNUSED_]]
const arg$k[[]]_type& arg$k GTEST_ATTRIBUTE_UNUSED_]]
// Sometimes you want to give an action explicit template parameters
@ -432,7 +226,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;
@ -525,7 +319,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(::testing::internal::move(gmock_p$j))]]
($for j, [[p$j##_type gmock_p$j]])$if i>0 [[ : ]]$for j, [[p$j(::std::move(gmock_p$j))]]
]]
@ -607,7 +401,7 @@ $range k 0..n-1
}\
template <$for k, [[typename arg$k[[]]_type]]>\
return_type gmock_PerformImpl(const args_type& args[[]]
$for k [[, arg$k[[]]_type arg$k]]) const;\
$for k [[, const arg$k[[]]_type& arg$k]]) const;\
GMOCK_INTERNAL_DEFN_##value_params\
private:\
GTEST_DISALLOW_ASSIGN_(gmock_Impl);\
@ -658,7 +452,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(::testing::internal::forward<p$j##_type>(gmock_p$j))]]]]]]
$var inits = [[$if i==0 [[]] $else [[ : $for j, [[p$j(::std::forward<p$j##_type>(gmock_p$j))]]]]]]
$var param_field_decls = [[$for j
[[
@ -672,7 +466,7 @@ $var param_field_decls2 = [[$for j
$var params = [[$for j, [[p$j]]]]
$var param_types = [[$if i==0 [[]] $else [[<$for j, [[p$j##_type]]>]]]]
$var typename_arg_types = [[$for k, [[typename arg$k[[]]_type]]]]
$var arg_types_and_names = [[$for k, [[arg$k[[]]_type arg$k]]]]
$var arg_types_and_names = [[$for k, [[const arg$k[[]]_type& arg$k]]]]
$var macro_name = [[$if i==0 [[ACTION]] $elif i==1 [[ACTION_P]]
$else [[ACTION_P$i]]]]
@ -796,7 +590,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]]);
}
]]

View File

@ -42,59 +42,16 @@ $var n = 10 $$ The maximum arity we support.
#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_FUNCTION_MOCKERS_H_
#define GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_FUNCTION_MOCKERS_H_
#include <functional>
#include <utility>
#include "gmock/gmock-spec-builders.h"
#include "gmock/internal/gmock-internal-utils.h"
#if GTEST_HAS_STD_FUNCTION_
# include <functional>
#endif
namespace testing {
namespace internal {
template <typename F>
class FunctionMockerBase;
// Note: class FunctionMocker really belongs to the ::testing
// namespace. However if we define it in ::testing, MSVC will
// complain when classes in ::testing::internal declare it as a
// friend class template. To workaround this compiler bug, we define
// FunctionMocker in ::testing::internal and import it into ::testing.
template <typename F>
class FunctionMocker;
$range i 0..n
$for i [[
$range j 1..i
$var typename_As = [[$for j [[, typename 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]]]]
template <typename R$typename_As>
class FunctionMocker<R($As)> : public
internal::FunctionMockerBase<R($As)> {
public:
typedef R F($As);
typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
MockSpec<F> With($matchers) {
return MockSpec<F>(this, ::testing::make_tuple($ms));
}
R Invoke($Aas) {
// Even though gcc and MSVC don't enforce it, 'this->' is required
// 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($as));
}
};
]]
// Removes the given pointer; this is a helper for the expectation setter method
// for parameterless matchers.
//
@ -167,7 +124,7 @@ using internal::FunctionMocker;
// The type of argument N of the given function type.
// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!!
#define GMOCK_ARG_(tn, N, ...) \
tn ::testing::internal::Function<__VA_ARGS__>::Argument##N
tn ::testing::internal::Function<__VA_ARGS__>::template Arg<N-1>::type
// The matcher type for argument N of the given function type.
// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!!
@ -184,7 +141,7 @@ $for i [[
$range j 1..i
$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)]]]]
[[::std::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]]]]
@ -192,11 +149,9 @@ $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, ...) \
static_assert($i == ::testing::internal::Function<__VA_ARGS__>::ArgumentCount, "MOCK_METHOD<N> must match argument count.");\
GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \
$arg_as) constness { \
GTEST_COMPILE_ASSERT_((::testing::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); \
} \
@ -267,82 +222,6 @@ $for i [[
]]
// A MockFunction<F> class has one mock method whose type is F. It is
// useful when you just want your test code to emit some messages and
// have Google Mock verify the right messages are sent (and perhaps at
// the right times). 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:
//
// TEST(FooTest, InvokesBarCorrectly) {
// MyMock mock;
// 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().
//
// MockFunction<F> can also be used to exercise code that accepts
// std::function<F> callbacks. To do so, use AsStdFunction() method
// to create std::function proxy forwarding to original object's Call.
// Example:
//
// TEST(FooTest, RunsCallbackWithBarArgument) {
// MockFunction<int(string)> callback;
// EXPECT_CALL(callback, Call("bar")).WillOnce(Return(1));
// Foo(callback.AsStdFunction());
// }
template <typename F>
class MockFunction;
$for i [[
$range j 0..i-1
$var ArgTypes = [[$for j, [[A$j]]]]
$var ArgValues = [[$for j, [[::std::move(a$j)]]]]
$var ArgDecls = [[$for j, [[A$j a$j]]]]
template <typename R$for j [[, typename A$j]]>
class MockFunction<R($ArgTypes)> {
public:
MockFunction() {}
MOCK_METHOD$i[[]]_T(Call, R($ArgTypes));
#if GTEST_HAS_STD_FUNCTION_
::std::function<R($ArgTypes)> AsStdFunction() {
return [this]($ArgDecls) -> R {
return this->Call($ArgValues);
};
}
#endif // GTEST_HAS_STD_FUNCTION_
private:
GTEST_DISALLOW_COPY_AND_ASSIGN_(MockFunction);
};
]]
} // namespace testing
#endif // GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_FUNCTION_MOCKERS_H_

File diff suppressed because it is too large Load Diff

View File

@ -45,340 +45,10 @@ $$ }} This line fixes auto-indentation of the following code in Emacs.
#include <iterator>
#include <sstream>
#include <string>
#include <utility>
#include <vector>
#include "gmock/gmock-matchers.h"
namespace testing {
namespace internal {
$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
// TupleFields<Tuple, k0, ..., kn> is for selecting fields from a
// tuple of type Tuple. It has two members:
//
// 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:
//
// type is tuple<int, bool>, and
// GetSelectedFields(make_tuple(true, 'a', 42)) is (42, true).
template <class Tuple$for i [[, int k$i = -1]]>
class TupleFields;
// This generic version is used when there are $n selectors.
template <class Tuple$for i [[, int k$i]]>
class TupleFields {
public:
typedef ::testing::tuple<$for i, [[GMOCK_FIELD_TYPE_(Tuple, k$i)]]> type;
static type GetSelectedFields(const Tuple& t) {
return type($for i, [[get<k$i>(t)]]);
}
};
// The following specialization is used for 0 ~ $(n-1) selectors.
$for i [[
$$ }}}
$range j 0..i-1
$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;
static type GetSelectedFields(const Tuple& $if i==0 [[/* t */]] $else [[t]]) {
return type($for j, [[get<k$j>(t)]]);
}
};
]]
#undef GMOCK_FIELD_TYPE_
// Implements the Args() matcher.
$var ks = [[$for i, [[k$i]]]]
template <class ArgsTuple$for i [[, int k$i = -1]]>
class ArgsMatcherImpl : public MatcherInterface<ArgsTuple> {
public:
// ArgsTuple may have top-level const or reference modifiers.
typedef GTEST_REMOVE_REFERENCE_AND_CONST_(ArgsTuple) RawArgsTuple;
typedef typename internal::TupleFields<RawArgsTuple, $ks>::type SelectedArgs;
typedef Matcher<const SelectedArgs&> MonomorphicInnerMatcher;
template <typename InnerMatcher>
explicit ArgsMatcherImpl(const InnerMatcher& inner_matcher)
: inner_matcher_(SafeMatcherCast<const SelectedArgs&>(inner_matcher)) {}
virtual bool MatchAndExplain(ArgsTuple args,
MatchResultListener* listener) const {
const SelectedArgs& selected_args = GetSelectedArgs(args);
if (!listener->IsInterested())
return inner_matcher_.Matches(selected_args);
PrintIndices(listener->stream());
*listener << "are " << PrintToString(selected_args);
StringMatchResultListener inner_listener;
const bool match = inner_matcher_.MatchAndExplain(selected_args,
&inner_listener);
PrintIfNotEmpty(inner_listener.str(), listener->stream());
return match;
}
virtual void DescribeTo(::std::ostream* os) const {
*os << "are a tuple ";
PrintIndices(os);
inner_matcher_.DescribeTo(os);
}
virtual void DescribeNegationTo(::std::ostream* os) const {
*os << "are a tuple ";
PrintIndices(os);
inner_matcher_.DescribeNegationTo(os);
}
private:
static SelectedArgs GetSelectedArgs(ArgsTuple args) {
return TupleFields<RawArgsTuple, $ks>::GetSelectedFields(args);
}
// Prints the indices of the selected fields.
static void PrintIndices(::std::ostream* os) {
*os << "whose fields (";
const int indices[$n] = { $ks };
for (int i = 0; i < $n; i++) {
if (indices[i] < 0)
break;
if (i >= 1)
*os << ", ";
*os << "#" << indices[i];
}
*os << ") ";
}
const MonomorphicInnerMatcher inner_matcher_;
GTEST_DISALLOW_ASSIGN_(ArgsMatcherImpl);
};
template <class InnerMatcher$for i [[, int k$i = -1]]>
class ArgsMatcher {
public:
explicit ArgsMatcher(const InnerMatcher& inner_matcher)
: inner_matcher_(inner_matcher) {}
template <typename ArgsTuple>
operator Matcher<ArgsTuple>() const {
return MakeMatcher(new ArgsMatcherImpl<ArgsTuple, $ks>(inner_matcher_));
}
private:
const InnerMatcher inner_matcher_;
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
// fields of it matches a_matcher. C++ doesn't support default
// arguments for function templates, so we have to overload it.
$range i 0..n
$for i [[
$range j 1..i
template <$for j [[int k$j, ]]typename InnerMatcher>
inline internal::ArgsMatcher<InnerMatcher$for j [[, k$j]]>
Args(const InnerMatcher& matcher) {
return internal::ArgsMatcher<InnerMatcher$for j [[, k$j]]>(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.
//
// If you have >$n elements, consider UnorderedElementsAreArray() or
// UnorderedPointwise() instead.
$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
$$ // show up in the generated code.
// The MATCHER* family of macros can be used in a namespace scope to
// define custom matchers easily.
//
@ -582,18 +252,15 @@ $$ // show up in the generated code.
// overloading matchers based on parameter types (as opposed to just
// based on the number of parameters).
//
// MATCHER*() can only be used in a namespace scope. The reason is
// that C++ doesn't yet allow function-local types to be used to
// instantiate templates. The up-coming C++0x standard will fix this.
// Once that's done, we'll consider supporting using MATCHER*() inside
// a function.
// MATCHER*() can only be used in a namespace scope as templates cannot be
// declared inside of a local class.
//
// More Information
// ================
//
// To learn more about using these macros, please search for 'MATCHER'
// on
// https://github.com/google/googletest/blob/master/googlemock/docs/CookBook.md
// https://github.com/google/googletest/blob/master/googlemock/docs/cook_book.md
$range i 0..n
$for i
@ -610,8 +277,8 @@ $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(::testing::internal::move(gmock_p$j))]]]]]]
$var inits = [[$if i==0 [[]] $else [[ : $for j, [[p$j(::testing::internal::move(gmock_p$j))]]]]]]
$var impl_inits = [[$if i==0 [[]] $else [[ : $for j, [[p$j(::std::move(gmock_p$j))]]]]]]
$var inits = [[$if i==0 [[]] $else [[ : $for j, [[p$j(::std::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]]]]
@ -647,12 +314,13 @@ $var param_field_decls2 = [[$for j
private:\
::std::string FormatDescription(bool negation) const {\
::std::string gmock_description = (description);\
if (!gmock_description.empty())\
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]])));\
}\
};\
template <typename arg_type>\

View File

@ -1,459 +0,0 @@
// This file was GENERATED by command:
// pump.py gmock-generated-nice-strict.h.pump
// DO NOT EDIT BY HAND!!!
// Copyright 2008, 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.
// Implements class templates NiceMock, NaggyMock, and StrictMock.
//
// Given a mock class MockFoo that is created using Google Mock,
// NiceMock<MockFoo> is a subclass of MockFoo that allows
// uninteresting calls (i.e. calls to mock methods that have no
// EXPECT_CALL specs), NaggyMock<MockFoo> is a subclass of MockFoo
// that prints a warning when an uninteresting call occurs, and
// StrictMock<MockFoo> is a subclass of MockFoo that treats all
// uninteresting calls as errors.
//
// Currently a mock is naggy by default, so MockFoo and
// NaggyMock<MockFoo> behave like the same. However, we will soon
// switch the default behavior of mocks to be nice, as that in general
// leads to more maintainable tests. When that happens, MockFoo will
// stop behaving like NaggyMock<MockFoo> and start behaving like
// NiceMock<MockFoo>.
//
// NiceMock, NaggyMock, and StrictMock "inherit" the constructors of
// 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
// 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, NaggyMock, and StrictMock is NOT
// supported.
// GOOGLETEST_CM0002 DO NOT DELETE
#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_NICE_STRICT_H_
#define GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_NICE_STRICT_H_
#include "gmock/gmock-spec-builders.h"
#include "gmock/internal/gmock-port.h"
namespace testing {
template <class MockClass>
class NiceMock : public MockClass {
public:
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));
}
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(
internal::ImplicitCast_<MockClass*>(this));
}
template <typename A1, typename A2>
NiceMock(const A1& a1, const A2& a2) : MockClass(a1, a2) {
::testing::Mock::AllowUninterestingCalls(
internal::ImplicitCast_<MockClass*>(this));
}
template <typename A1, typename A2, typename A3>
NiceMock(const A1& a1, const A2& a2, const A3& a3) : MockClass(a1, a2, a3) {
::testing::Mock::AllowUninterestingCalls(
internal::ImplicitCast_<MockClass*>(this));
}
template <typename A1, typename A2, typename A3, typename A4>
NiceMock(const A1& a1, const A2& a2, const A3& a3,
const A4& a4) : MockClass(a1, a2, a3, a4) {
::testing::Mock::AllowUninterestingCalls(
internal::ImplicitCast_<MockClass*>(this));
}
template <typename A1, typename A2, typename A3, typename A4, typename A5>
NiceMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4,
const A5& a5) : MockClass(a1, a2, a3, a4, a5) {
::testing::Mock::AllowUninterestingCalls(
internal::ImplicitCast_<MockClass*>(this));
}
template <typename A1, typename A2, typename A3, typename A4, typename A5,
typename A6>
NiceMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4,
const A5& a5, const A6& a6) : MockClass(a1, a2, a3, a4, a5, a6) {
::testing::Mock::AllowUninterestingCalls(
internal::ImplicitCast_<MockClass*>(this));
}
template <typename A1, typename A2, typename A3, typename A4, typename A5,
typename A6, typename A7>
NiceMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4,
const A5& a5, const A6& a6, const A7& a7) : MockClass(a1, a2, a3, a4, a5,
a6, a7) {
::testing::Mock::AllowUninterestingCalls(
internal::ImplicitCast_<MockClass*>(this));
}
template <typename A1, typename A2, typename A3, typename A4, typename A5,
typename A6, typename A7, typename A8>
NiceMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4,
const A5& a5, const A6& a6, const A7& a7, const A8& a8) : MockClass(a1,
a2, a3, a4, a5, a6, a7, a8) {
::testing::Mock::AllowUninterestingCalls(
internal::ImplicitCast_<MockClass*>(this));
}
template <typename A1, typename A2, typename A3, typename A4, typename A5,
typename A6, typename A7, typename A8, typename A9>
NiceMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4,
const A5& a5, const A6& a6, const A7& a7, const A8& a8,
const A9& a9) : MockClass(a1, a2, a3, a4, a5, a6, a7, a8, a9) {
::testing::Mock::AllowUninterestingCalls(
internal::ImplicitCast_<MockClass*>(this));
}
template <typename A1, typename A2, typename A3, typename A4, typename A5,
typename A6, typename A7, typename A8, typename A9, typename A10>
NiceMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4,
const A5& a5, const A6& a6, const A7& a7, const A8& a8, const A9& a9,
const A10& a10) : MockClass(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10) {
::testing::Mock::AllowUninterestingCalls(
internal::ImplicitCast_<MockClass*>(this));
}
#endif // GTEST_LANG_CXX11
~NiceMock() {
::testing::Mock::UnregisterCallReaction(
internal::ImplicitCast_<MockClass*>(this));
}
private:
GTEST_DISALLOW_COPY_AND_ASSIGN_(NiceMock);
};
template <class MockClass>
class NaggyMock : public MockClass {
public:
NaggyMock() : MockClass() {
::testing::Mock::WarnUninterestingCalls(
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 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(
internal::ImplicitCast_<MockClass*>(this));
}
template <typename A1, typename A2>
NaggyMock(const A1& a1, const A2& a2) : MockClass(a1, a2) {
::testing::Mock::WarnUninterestingCalls(
internal::ImplicitCast_<MockClass*>(this));
}
template <typename A1, typename A2, typename A3>
NaggyMock(const A1& a1, const A2& a2, const A3& a3) : MockClass(a1, a2, a3) {
::testing::Mock::WarnUninterestingCalls(
internal::ImplicitCast_<MockClass*>(this));
}
template <typename A1, typename A2, typename A3, typename A4>
NaggyMock(const A1& a1, const A2& a2, const A3& a3,
const A4& a4) : MockClass(a1, a2, a3, a4) {
::testing::Mock::WarnUninterestingCalls(
internal::ImplicitCast_<MockClass*>(this));
}
template <typename A1, typename A2, typename A3, typename A4, typename A5>
NaggyMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4,
const A5& a5) : MockClass(a1, a2, a3, a4, a5) {
::testing::Mock::WarnUninterestingCalls(
internal::ImplicitCast_<MockClass*>(this));
}
template <typename A1, typename A2, typename A3, typename A4, typename A5,
typename A6>
NaggyMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4,
const A5& a5, const A6& a6) : MockClass(a1, a2, a3, a4, a5, a6) {
::testing::Mock::WarnUninterestingCalls(
internal::ImplicitCast_<MockClass*>(this));
}
template <typename A1, typename A2, typename A3, typename A4, typename A5,
typename A6, typename A7>
NaggyMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4,
const A5& a5, const A6& a6, const A7& a7) : MockClass(a1, a2, a3, a4, a5,
a6, a7) {
::testing::Mock::WarnUninterestingCalls(
internal::ImplicitCast_<MockClass*>(this));
}
template <typename A1, typename A2, typename A3, typename A4, typename A5,
typename A6, typename A7, typename A8>
NaggyMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4,
const A5& a5, const A6& a6, const A7& a7, const A8& a8) : MockClass(a1,
a2, a3, a4, a5, a6, a7, a8) {
::testing::Mock::WarnUninterestingCalls(
internal::ImplicitCast_<MockClass*>(this));
}
template <typename A1, typename A2, typename A3, typename A4, typename A5,
typename A6, typename A7, typename A8, typename A9>
NaggyMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4,
const A5& a5, const A6& a6, const A7& a7, const A8& a8,
const A9& a9) : MockClass(a1, a2, a3, a4, a5, a6, a7, a8, a9) {
::testing::Mock::WarnUninterestingCalls(
internal::ImplicitCast_<MockClass*>(this));
}
template <typename A1, typename A2, typename A3, typename A4, typename A5,
typename A6, typename A7, typename A8, typename A9, typename A10>
NaggyMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4,
const A5& a5, const A6& a6, const A7& a7, const A8& a8, const A9& a9,
const A10& a10) : MockClass(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10) {
::testing::Mock::WarnUninterestingCalls(
internal::ImplicitCast_<MockClass*>(this));
}
#endif // GTEST_LANG_CXX11
~NaggyMock() {
::testing::Mock::UnregisterCallReaction(
internal::ImplicitCast_<MockClass*>(this));
}
private:
GTEST_DISALLOW_COPY_AND_ASSIGN_(NaggyMock);
};
template <class MockClass>
class StrictMock : public MockClass {
public:
StrictMock() : MockClass() {
::testing::Mock::FailUninterestingCalls(
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 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(
internal::ImplicitCast_<MockClass*>(this));
}
template <typename A1, typename A2>
StrictMock(const A1& a1, const A2& a2) : MockClass(a1, a2) {
::testing::Mock::FailUninterestingCalls(
internal::ImplicitCast_<MockClass*>(this));
}
template <typename A1, typename A2, typename A3>
StrictMock(const A1& a1, const A2& a2, const A3& a3) : MockClass(a1, a2, a3) {
::testing::Mock::FailUninterestingCalls(
internal::ImplicitCast_<MockClass*>(this));
}
template <typename A1, typename A2, typename A3, typename A4>
StrictMock(const A1& a1, const A2& a2, const A3& a3,
const A4& a4) : MockClass(a1, a2, a3, a4) {
::testing::Mock::FailUninterestingCalls(
internal::ImplicitCast_<MockClass*>(this));
}
template <typename A1, typename A2, typename A3, typename A4, typename A5>
StrictMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4,
const A5& a5) : MockClass(a1, a2, a3, a4, a5) {
::testing::Mock::FailUninterestingCalls(
internal::ImplicitCast_<MockClass*>(this));
}
template <typename A1, typename A2, typename A3, typename A4, typename A5,
typename A6>
StrictMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4,
const A5& a5, const A6& a6) : MockClass(a1, a2, a3, a4, a5, a6) {
::testing::Mock::FailUninterestingCalls(
internal::ImplicitCast_<MockClass*>(this));
}
template <typename A1, typename A2, typename A3, typename A4, typename A5,
typename A6, typename A7>
StrictMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4,
const A5& a5, const A6& a6, const A7& a7) : MockClass(a1, a2, a3, a4, a5,
a6, a7) {
::testing::Mock::FailUninterestingCalls(
internal::ImplicitCast_<MockClass*>(this));
}
template <typename A1, typename A2, typename A3, typename A4, typename A5,
typename A6, typename A7, typename A8>
StrictMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4,
const A5& a5, const A6& a6, const A7& a7, const A8& a8) : MockClass(a1,
a2, a3, a4, a5, a6, a7, a8) {
::testing::Mock::FailUninterestingCalls(
internal::ImplicitCast_<MockClass*>(this));
}
template <typename A1, typename A2, typename A3, typename A4, typename A5,
typename A6, typename A7, typename A8, typename A9>
StrictMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4,
const A5& a5, const A6& a6, const A7& a7, const A8& a8,
const A9& a9) : MockClass(a1, a2, a3, a4, a5, a6, a7, a8, a9) {
::testing::Mock::FailUninterestingCalls(
internal::ImplicitCast_<MockClass*>(this));
}
template <typename A1, typename A2, typename A3, typename A4, typename A5,
typename A6, typename A7, typename A8, typename A9, typename A10>
StrictMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4,
const A5& a5, const A6& a6, const A7& a7, const A8& a8, const A9& a9,
const A10& a10) : MockClass(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10) {
::testing::Mock::FailUninterestingCalls(
internal::ImplicitCast_<MockClass*>(this));
}
#endif // GTEST_LANG_CXX11
~StrictMock() {
::testing::Mock::UnregisterCallReaction(
internal::ImplicitCast_<MockClass*>(this));
}
private:
GTEST_DISALLOW_COPY_AND_ASSIGN_(StrictMock);
};
// The following specializations catch some (relatively more common)
// user errors of nesting nice and strict mocks. They do NOT catch
// all possible errors.
// These specializations are declared but not defined, as NiceMock,
// NaggyMock, and StrictMock cannot be nested.
template <typename MockClass>
class NiceMock<NiceMock<MockClass> >;
template <typename MockClass>
class NiceMock<NaggyMock<MockClass> >;
template <typename MockClass>
class NiceMock<StrictMock<MockClass> >;
template <typename MockClass>
class NaggyMock<NiceMock<MockClass> >;
template <typename MockClass>
class NaggyMock<NaggyMock<MockClass> >;
template <typename MockClass>
class NaggyMock<StrictMock<MockClass> >;
template <typename MockClass>
class StrictMock<NiceMock<MockClass> >;
template <typename MockClass>
class StrictMock<NaggyMock<MockClass> >;
template <typename MockClass>
class StrictMock<StrictMock<MockClass> >;
} // namespace testing
#endif // GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_NICE_STRICT_H_

File diff suppressed because it is too large Load Diff

View File

@ -38,59 +38,13 @@
#define GMOCK_INCLUDE_GMOCK_GMOCK_MORE_ACTIONS_H_
#include <algorithm>
#include <type_traits>
#include "gmock/gmock-generated-actions.h"
namespace testing {
namespace internal {
// Implements the Invoke(f) action. The template argument
// FunctionImpl is the implementation type of f, which can be either a
// function pointer or a functor. Invoke(f) can be used as an
// Action<F> as long as f's type is compatible with F (i.e. f can be
// assigned to a tr1::function<F>).
template <typename FunctionImpl>
class InvokeAction {
public:
// The c'tor makes a copy of function_impl (either a function
// pointer or a functor).
explicit InvokeAction(FunctionImpl function_impl)
: function_impl_(function_impl) {}
template <typename Result, typename ArgumentTuple>
Result Perform(const ArgumentTuple& args) {
return InvokeHelper<Result, ArgumentTuple>::Invoke(function_impl_, args);
}
private:
FunctionImpl function_impl_;
GTEST_DISALLOW_ASSIGN_(InvokeAction);
};
// Implements the Invoke(object_ptr, &Class::Method) action.
template <class Class, typename MethodPtr>
class InvokeMethodAction {
public:
InvokeMethodAction(Class* obj_ptr, MethodPtr method_ptr)
: method_ptr_(method_ptr), obj_ptr_(obj_ptr) {}
template <typename Result, typename ArgumentTuple>
Result Perform(const ArgumentTuple& args) const {
return InvokeHelper<Result, ArgumentTuple>::InvokeMethod(
obj_ptr_, method_ptr_, args);
}
private:
// The order of these members matters. Reversing the order can trigger
// warning C4121 in MSVC (see
// http://computer-programming-forum.com/7-vc.net/6fbc30265f860ad1.htm ).
const MethodPtr method_ptr_;
Class* const obj_ptr_;
GTEST_DISALLOW_ASSIGN_(InvokeMethodAction);
};
// An internal replacement for std::copy which mimics its behavior. This is
// necessary because Visual Studio deprecates ::std::copy, issuing warning 4996.
// However Visual Studio 2010 and later do not honor #pragmas which disable that
@ -109,45 +63,6 @@ inline OutputIterator CopyElements(InputIterator first,
// Various overloads for Invoke().
// Creates an action that invokes 'function_impl' with the mock
// function's arguments.
template <typename FunctionImpl>
PolymorphicAction<internal::InvokeAction<FunctionImpl> > Invoke(
FunctionImpl function_impl) {
return MakePolymorphicAction(
internal::InvokeAction<FunctionImpl>(function_impl));
}
// Creates an action that invokes the given method on the given object
// with the mock function's arguments.
template <class Class, typename MethodPtr>
PolymorphicAction<internal::InvokeMethodAction<Class, MethodPtr> > Invoke(
Class* obj_ptr, MethodPtr method_ptr) {
return MakePolymorphicAction(
internal::InvokeMethodAction<Class, MethodPtr>(obj_ptr, method_ptr));
}
// WithoutArgs(inner_action) can be used in a mock function with a
// non-empty argument list to perform inner_action, which takes no
// argument. In other words, it adapts an action accepting no
// argument to one that accepts (and ignores) arguments.
template <typename InnerAction>
inline internal::WithArgsAction<InnerAction>
WithoutArgs(const InnerAction& action) {
return internal::WithArgsAction<InnerAction>(action);
}
// WithArg<k>(an_action) creates an action that passes the k-th
// (0-based) argument of the mock function to an_action and performs
// it. It adapts an action accepting one argument to one that accepts
// multiple arguments. For convenience, we also provide
// WithArgs<k>(an_action) (defined below) as a synonym.
template <int k, typename InnerAction>
inline internal::WithArgsAction<InnerAction, k>
WithArg(const InnerAction& action) {
return internal::WithArgsAction<InnerAction, k>(action);
}
// The ACTION*() macros trigger warning C4100 (unreferenced formal
// parameter) in MSVC with -W4. Unfortunately they cannot be fixed in
// the macro definition, as the warnings are generated when the macro
@ -162,7 +77,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
@ -170,7 +85,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
@ -178,7 +93,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
@ -186,13 +101,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,
GTEST_COMPILE_ASSERT_(std::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
@ -205,9 +120,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
}
@ -216,7 +131,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'.

View File

@ -1,8 +1,3 @@
$$ -*- mode: c++; -*-
$$ 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.
// All rights reserved.
//
@ -65,34 +60,22 @@ $var n = 10 $$ The maximum arity we support.
// GOOGLETEST_CM0002 DO NOT DELETE
#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_NICE_STRICT_H_
#define GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_NICE_STRICT_H_
#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_NICE_STRICT_H_
#define GMOCK_INCLUDE_GMOCK_GMOCK_NICE_STRICT_H_
#include "gmock/gmock-spec-builders.h"
#include "gmock/internal/gmock-port.h"
namespace testing {
$range kind 0..2
$for kind [[
$var clazz=[[$if kind==0 [[NiceMock]]
$elif kind==1 [[NaggyMock]]
$else [[StrictMock]]]]
$var method=[[$if kind==0 [[AllowUninterestingCalls]]
$elif kind==1 [[WarnUninterestingCalls]]
$else [[FailUninterestingCalls]]]]
template <class MockClass>
class $clazz : public MockClass {
class NiceMock : public MockClass {
public:
$clazz() : MockClass() {
::testing::Mock::$method(
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
@ -101,50 +84,103 @@ class $clazz : public MockClass {
// 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(
explicit NiceMock(A&& arg) : MockClass(std::forward<A>(arg)) {
::testing::Mock::AllowUninterestingCalls(
internal::ImplicitCast_<MockClass*>(this));
}
template <typename A1, typename A2, typename... An>
$clazz(A1&& arg1, A2&& arg2, An&&... args)
NiceMock(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(
::testing::Mock::AllowUninterestingCalls(
internal::ImplicitCast_<MockClass*>(this));
}
$range i 2..n
$for i [[
$range j 1..i
template <$for j, [[typename A$j]]>
$clazz($for j, [[const A$j& a$j]]) : MockClass($for j, [[a$j]]) {
::testing::Mock::$method(
internal::ImplicitCast_<MockClass*>(this));
}
]]
#endif // GTEST_LANG_CXX11
~$clazz() {
~NiceMock() { // NOLINT
::testing::Mock::UnregisterCallReaction(
internal::ImplicitCast_<MockClass*>(this));
}
private:
GTEST_DISALLOW_COPY_AND_ASSIGN_($clazz);
GTEST_DISALLOW_COPY_AND_ASSIGN_(NiceMock);
};
]]
template <class MockClass>
class NaggyMock : public MockClass {
public:
NaggyMock() : MockClass() {
::testing::Mock::WarnUninterestingCalls(
internal::ImplicitCast_<MockClass*>(this));
}
// 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));
}
~NaggyMock() { // NOLINT
::testing::Mock::UnregisterCallReaction(
internal::ImplicitCast_<MockClass*>(this));
}
private:
GTEST_DISALLOW_COPY_AND_ASSIGN_(NaggyMock);
};
template <class MockClass>
class StrictMock : public MockClass {
public:
StrictMock() : MockClass() {
::testing::Mock::FailUninterestingCalls(
internal::ImplicitCast_<MockClass*>(this));
}
// 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));
}
~StrictMock() { // NOLINT
::testing::Mock::UnregisterCallReaction(
internal::ImplicitCast_<MockClass*>(this));
}
private:
GTEST_DISALLOW_COPY_AND_ASSIGN_(StrictMock);
};
// The following specializations catch some (relatively more common)
// user errors of nesting nice and strict mocks. They do NOT catch
@ -176,4 +212,4 @@ class StrictMock<StrictMock<MockClass> >;
} // namespace testing
#endif // GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_NICE_STRICT_H_
#endif // GMOCK_INCLUDE_GMOCK_GMOCK_NICE_STRICT_H_

View File

@ -61,10 +61,14 @@
#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_
#define GMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_
#include <functional>
#include <map>
#include <memory>
#include <set>
#include <sstream>
#include <string>
#include <type_traits>
#include <utility>
#include <vector>
#include "gmock/gmock-actions.h"
#include "gmock/gmock-cardinalities.h"
@ -104,9 +108,6 @@ template <typename F> class TypedExpectation;
// Helper class for testing the Expectation class template.
class ExpectationTester;
// Base class for function mockers.
template <typename F> class FunctionMockerBase;
// Protects the mock object registry (in class Mock), all function
// mockers, and all expectations.
//
@ -123,9 +124,9 @@ GTEST_API_ GTEST_DECLARE_STATIC_MUTEX_(g_gmock_mutex);
// Untyped base class for ActionResultHolder<R>.
class UntypedActionResultHolderBase;
// Abstract base class of FunctionMockerBase. This is the
// Abstract base class of FunctionMocker. This is the
// type-agnostic part of the function mocker interface. Its pure
// virtual methods are implemented by FunctionMockerBase.
// virtual methods are implemented by FunctionMocker.
class GTEST_API_ UntypedFunctionMockerBase {
public:
UntypedFunctionMockerBase();
@ -187,7 +188,6 @@ 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.
// FIXME: rename to SetAndRegisterOwner().
void RegisterOwner(const void* mock_obj)
GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
@ -218,8 +218,7 @@ class GTEST_API_ UntypedFunctionMockerBase {
protected:
typedef std::vector<const void*> UntypedOnCallSpecs;
typedef std::vector<internal::linked_ptr<ExpectationBase> >
UntypedExpectations;
using UntypedExpectations = std::vector<std::shared_ptr<ExpectationBase>>;
// Returns an Expectation object that references and co-owns exp,
// which must be an expectation on this mock function.
@ -304,11 +303,9 @@ class OnCallSpec : public UntypedOnCallSpecBase {
: UntypedOnCallSpecBase(a_file, a_line),
matchers_(matchers),
// By default, extra_matcher_ should match anything. However,
// we cannot initialize it with _ as that triggers a compiler
// bug in Symbian's C++ compiler (cannot decide between two
// overloaded constructors of Matcher<const ArgumentTuple&>).
extra_matcher_(A<const ArgumentTuple&>()) {
}
// we cannot initialize it with _ as that causes ambiguity between
// Matcher's copy and move constructor for some argument types.
extra_matcher_(A<const ArgumentTuple&>()) {}
// Implements the .With() clause.
OnCallSpec& With(const Matcher<const ArgumentTuple&>& m) {
@ -335,7 +332,7 @@ class OnCallSpec : public UntypedOnCallSpecBase {
return *this;
}
// Returns true iff the given arguments match the matchers.
// Returns true if and only if the given arguments match the matchers.
bool Matches(const ArgumentTuple& args) const {
return TupleMatches(matchers_, args) && extra_matcher_.Matches(args);
}
@ -393,18 +390,28 @@ class GTEST_API_ Mock {
GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
// Verifies all expectations on the given mock object and clears its
// default actions and expectations. Returns true iff the
// default actions and expectations. Returns true if and only if the
// verification was successful.
static bool VerifyAndClear(void* mock_obj)
GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
// Returns whether the mock was created as a naggy mock (default)
static bool IsNaggy(void* mock_obj)
GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
// Returns whether the mock was created as a nice mock
static bool IsNice(void* mock_obj)
GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
// Returns whether the mock was created as a strict mock
static bool IsStrict(void* mock_obj)
GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
private:
friend class internal::UntypedFunctionMockerBase;
// Needed for a function mocker to register itself (so that we know
// how to clear a mock object).
template <typename F>
friend class internal::FunctionMockerBase;
friend class internal::FunctionMocker;
template <typename M>
friend class NiceMock;
@ -467,7 +474,7 @@ class GTEST_API_ Mock {
// Unregisters a mock method; removes the owning mock object from
// the registry when the last mock method associated with it has
// been unregistered. This is called only in the destructor of
// FunctionMockerBase.
// FunctionMocker.
static void UnregisterLocked(internal::UntypedFunctionMockerBase* mocker)
GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex);
}; // class Mock
@ -487,12 +494,7 @@ class GTEST_API_ Mock {
// - Constness is shallow: a const Expectation object itself cannot
// be modified, but the mutable methods of the ExpectationBase
// object it references can be called via expectation_base().
// - The constructors and destructor are defined out-of-line because
// the Symbian WINSCW compiler wants to otherwise instantiate them
// when it sees this class definition, at which point it doesn't have
// ExpectationBase available yet, leading to incorrect destruction
// in the linked_ptr (or compilation errors if using a checking
// linked_ptr).
class GTEST_API_ Expectation {
public:
// Constructs a null object that doesn't reference any expectation.
@ -514,7 +516,8 @@ class GTEST_API_ Expectation {
// The compiler-generated copy ctor and operator= work exactly as
// intended, so we don't need to define our own.
// Returns true iff rhs references the same expectation as this object does.
// Returns true if and only if rhs references the same expectation as this
// object does.
bool operator==(const Expectation& rhs) const {
return expectation_base_ == rhs.expectation_base_;
}
@ -528,7 +531,7 @@ class GTEST_API_ Expectation {
friend class ::testing::internal::UntypedFunctionMockerBase;
template <typename F>
friend class ::testing::internal::FunctionMockerBase;
friend class ::testing::internal::FunctionMocker;
template <typename F>
friend class ::testing::internal::TypedExpectation;
@ -544,16 +547,15 @@ class GTEST_API_ Expectation {
typedef ::std::set<Expectation, Less> Set;
Expectation(
const internal::linked_ptr<internal::ExpectationBase>& expectation_base);
const std::shared_ptr<internal::ExpectationBase>& expectation_base);
// Returns the expectation this object references.
const internal::linked_ptr<internal::ExpectationBase>&
expectation_base() const {
const std::shared_ptr<internal::ExpectationBase>& expectation_base() const {
return expectation_base_;
}
// A linked_ptr that co-owns the expectation this handle references.
internal::linked_ptr<internal::ExpectationBase> expectation_base_;
// A shared_ptr that co-owns the expectation this handle references.
std::shared_ptr<internal::ExpectationBase> expectation_base_;
};
// A set of expectation handles. Useful in the .After() clause of
@ -597,8 +599,8 @@ class ExpectationSet {
// The compiler-generator ctor and operator= works exactly as
// intended, so we don't need to define our own.
// Returns true iff rhs contains the same set of Expectation objects
// as this does.
// Returns true if and only if rhs contains the same set of Expectation
// objects as this does.
bool operator==(const ExpectationSet& rhs) const {
return expectations_ == rhs.expectations_;
}
@ -635,11 +637,8 @@ class GTEST_API_ Sequence {
void AddExpectation(const Expectation& expectation) const;
private:
// The last expectation in this sequence. We use a linked_ptr here
// because Sequence objects are copyable and we want the copies to
// be aliases. The linked_ptr allows the copies to co-own and share
// the same Expectation object.
internal::linked_ptr<Expectation> last_expectation_;
// The last expectation in this sequence.
std::shared_ptr<Expectation> last_expectation_;
}; // class Sequence
// An object of this type causes all EXPECT_CALL() statements
@ -762,8 +761,8 @@ class GTEST_API_ ExpectationBase {
// by the subclasses to implement the .Times() clause.
void SpecifyCardinality(const Cardinality& cardinality);
// Returns true iff the user specified the cardinality explicitly
// using a .Times().
// Returns true if and only if the user specified the cardinality
// explicitly using a .Times().
bool cardinality_specified() const { return cardinality_specified_; }
// Sets the cardinality of this expectation spec.
@ -779,7 +778,7 @@ class GTEST_API_ ExpectationBase {
void RetireAllPreRequisites()
GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
// Returns true iff this expectation is retired.
// Returns true if and only if this expectation is retired.
bool is_retired() const
GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
g_gmock_mutex.AssertHeld();
@ -793,28 +792,29 @@ class GTEST_API_ ExpectationBase {
retired_ = true;
}
// Returns true iff this expectation is satisfied.
// Returns true if and only if this expectation is satisfied.
bool IsSatisfied() const
GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
g_gmock_mutex.AssertHeld();
return cardinality().IsSatisfiedByCallCount(call_count_);
}
// Returns true iff this expectation is saturated.
// Returns true if and only if this expectation is saturated.
bool IsSaturated() const
GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
g_gmock_mutex.AssertHeld();
return cardinality().IsSaturatedByCallCount(call_count_);
}
// Returns true iff this expectation is over-saturated.
// Returns true if and only if this expectation is over-saturated.
bool IsOverSaturated() const
GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
g_gmock_mutex.AssertHeld();
return cardinality().IsOverSaturatedByCallCount(call_count_);
}
// Returns true iff all pre-requisites of this expectation are satisfied.
// Returns true if and only if all pre-requisites of this expectation are
// satisfied.
bool AllPrerequisitesAreSatisfied() const
GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
@ -857,12 +857,12 @@ class GTEST_API_ ExpectationBase {
const char* file_; // The file that contains the expectation.
int line_; // The line number of the expectation.
const std::string source_text_; // The EXPECT_CALL(...) source text.
// True iff the cardinality is specified explicitly.
// True if and only if the cardinality is specified explicitly.
bool cardinality_specified_;
Cardinality cardinality_; // The cardinality of the expectation.
// The immediate pre-requisites (i.e. expectations that must be
// satisfied before this expectation can be matched) of this
// expectation. We use linked_ptr in the set because we want an
// expectation. We use std::shared_ptr in the set because we want an
// Expectation object to be co-owned by its FunctionMocker and its
// successors. This allows multiple mock objects to be deleted at
// different times.
@ -871,7 +871,7 @@ class GTEST_API_ ExpectationBase {
// This group of fields are the current state of the expectation,
// and can change as the mock function is called.
int call_count_; // How many times this expectation has been invoked.
bool retired_; // True iff this expectation has retired.
bool retired_; // True if and only if this expectation has retired.
UntypedActions untyped_actions_;
bool extra_matcher_specified_;
bool repeated_action_specified_; // True if a WillRepeatedly() was specified.
@ -891,20 +891,19 @@ 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,
TypedExpectation(FunctionMocker<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),
matchers_(m),
// By default, extra_matcher_ should match anything. However,
// we cannot initialize it with _ as that triggers a compiler
// bug in Symbian's C++ compiler (cannot decide between two
// overloaded constructors of Matcher<const ArgumentTuple&>).
// we cannot initialize it with _ as that causes ambiguity between
// Matcher's copy and move constructor for some argument types.
extra_matcher_(A<const ArgumentTuple&>()),
repeated_action_(DoDefault()) {}
virtual ~TypedExpectation() {
~TypedExpectation() override {
// Check the validity of the action count if it hasn't been done
// yet (for example, if the expectation was never used).
CheckActionCountIfNotDone();
@ -1070,7 +1069,7 @@ class TypedExpectation : public ExpectationBase {
// If this mock method has an extra matcher (i.e. .With(matcher)),
// describes it to the ostream.
virtual void MaybeDescribeExtraMatcherTo(::std::ostream* os) {
void MaybeDescribeExtraMatcherTo(::std::ostream* os) override {
if (extra_matcher_specified_) {
*os << " Expected args: ";
extra_matcher_.DescribeTo(os);
@ -1080,26 +1079,25 @@ class TypedExpectation : public ExpectationBase {
private:
template <typename Function>
friend class FunctionMockerBase;
friend class FunctionMocker;
// Returns an Expectation object that references and co-owns this
// expectation.
virtual Expectation GetHandle() {
return owner_->GetHandleOf(this);
}
Expectation GetHandle() override { return owner_->GetHandleOf(this); }
// The following methods will be called only after the EXPECT_CALL()
// statement finishes and when the current thread holds
// g_gmock_mutex.
// Returns true iff this expectation matches the given arguments.
// Returns true if and only if this expectation matches the given arguments.
bool Matches(const ArgumentTuple& args) const
GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
g_gmock_mutex.AssertHeld();
return TupleMatches(matchers_, args) && extra_matcher_.Matches(args);
}
// Returns true iff this expectation should handle the given arguments.
// Returns true if and only if this expectation should handle the given
// arguments.
bool ShouldHandleArguments(const ArgumentTuple& args) const
GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
g_gmock_mutex.AssertHeld();
@ -1159,10 +1157,9 @@ class TypedExpectation : public ExpectationBase {
}
// Returns the action that should be taken for the current invocation.
const Action<F>& GetCurrentAction(
const FunctionMockerBase<F>* mocker,
const ArgumentTuple& args) const
GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
const Action<F>& GetCurrentAction(const FunctionMocker<F>* mocker,
const ArgumentTuple& args) const
GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
g_gmock_mutex.AssertHeld();
const int count = call_count();
Assert(count >= 1, __FILE__, __LINE__,
@ -1184,9 +1181,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
@ -1196,12 +1194,11 @@ class TypedExpectation : public ExpectationBase {
// Mock does it to 'why'. This method is not const as it calls
// IncrementCallCount(). A return value of NULL means the default
// action.
const Action<F>* GetActionForArguments(
const FunctionMockerBase<F>* mocker,
const ArgumentTuple& args,
::std::ostream* what,
::std::ostream* why)
GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
const Action<F>* GetActionForArguments(const FunctionMocker<F>* mocker,
const ArgumentTuple& args,
::std::ostream* what,
::std::ostream* why)
GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
g_gmock_mutex.AssertHeld();
if (IsSaturated()) {
// We have an excessive call.
@ -1210,10 +1207,7 @@ class TypedExpectation : public ExpectationBase {
mocker->DescribeDefaultActionTo(args, what);
DescribeCallCountTo(why);
// 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();
@ -1230,7 +1224,7 @@ class TypedExpectation : public ExpectationBase {
// All the fields below won't change once the EXPECT_CALL()
// statement finishes.
FunctionMockerBase<F>* const owner_;
FunctionMocker<F>* const owner_;
ArgumentMatcherTuple matchers_;
Matcher<const ArgumentTuple&> extra_matcher_;
Action<F> repeated_action_;
@ -1262,7 +1256,7 @@ class MockSpec {
// Constructs a MockSpec object, given the function mocker object
// that the spec is associated with.
MockSpec(internal::FunctionMockerBase<F>* function_mocker,
MockSpec(internal::FunctionMocker<F>* function_mocker,
const ArgumentMatcherTuple& matchers)
: function_mocker_(function_mocker), matchers_(matchers) {}
@ -1298,7 +1292,7 @@ class MockSpec {
friend class internal::FunctionMocker;
// The function mocker that owns this spec.
internal::FunctionMockerBase<F>* const function_mocker_;
internal::FunctionMocker<F>* const function_mocker_;
// The argument matchers specified in the spec.
ArgumentMatcherTuple matchers_;
@ -1319,18 +1313,18 @@ class ReferenceOrValueWrapper {
public:
// Constructs a wrapper from the given value/reference.
explicit ReferenceOrValueWrapper(T value)
: value_(::testing::internal::move(value)) {
: value_(std::move(value)) {
}
// Unwraps and returns the underlying value/reference, exactly as
// originally passed. The behavior of calling this more than once on
// the same object is unspecified.
T Unwrap() { return ::testing::internal::move(value_); }
T Unwrap() { return std::move(value_); }
// Provides nondestructive access to the underlying value/reference.
// Always returns a const reference (more precisely,
// const RemoveReference<T>&). The behavior of calling this after
// calling Unwrap on the same object is unspecified.
// const std::add_lvalue_reference<T>::type). The behavior of calling this
// after calling Unwrap on the same object is unspecified.
const T& Peek() const {
return value_;
}
@ -1389,7 +1383,7 @@ class ActionResultHolder : public UntypedActionResultHolderBase {
}
// Prints the held value as an action's result to os.
virtual void PrintAsActionResult(::std::ostream* os) const {
void PrintAsActionResult(::std::ostream* os) const override {
*os << "\n Returns: ";
// T may be a reference type, so we don't use UniversalPrint().
UniversalPrinter<T>::Print(result_.Peek(), os);
@ -1399,28 +1393,27 @@ class ActionResultHolder : public UntypedActionResultHolderBase {
// result in a new-ed ActionResultHolder.
template <typename F>
static ActionResultHolder* PerformDefaultAction(
const FunctionMockerBase<F>* func_mocker,
typename RvalueRef<typename Function<F>::ArgumentTuple>::type args,
const FunctionMocker<F>* func_mocker,
typename Function<F>::ArgumentTuple&& args,
const std::string& call_description) {
return new ActionResultHolder(Wrapper(func_mocker->PerformDefaultAction(
internal::move(args), call_description)));
std::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,
typename RvalueRef<typename Function<F>::ArgumentTuple>::type args) {
const Action<F>& action, typename Function<F>::ArgumentTuple&& args) {
return new ActionResultHolder(
Wrapper(action.Perform(internal::move(args))));
Wrapper(action.Perform(std::move(args))));
}
private:
typedef ReferenceOrValueWrapper<T> Wrapper;
explicit ActionResultHolder(Wrapper result)
: result_(::testing::internal::move(result)) {
: result_(std::move(result)) {
}
Wrapper result_;
@ -1434,16 +1427,16 @@ class ActionResultHolder<void> : public UntypedActionResultHolderBase {
public:
void Unwrap() { }
virtual void PrintAsActionResult(::std::ostream* /* os */) const {}
void PrintAsActionResult(::std::ostream* /* os */) const override {}
// Performs the given mock function's default action and returns ownership
// of an empty ActionResultHolder*.
template <typename F>
static ActionResultHolder* PerformDefaultAction(
const FunctionMockerBase<F>* func_mocker,
typename RvalueRef<typename Function<F>::ArgumentTuple>::type args,
const FunctionMocker<F>* func_mocker,
typename Function<F>::ArgumentTuple&& args,
const std::string& call_description) {
func_mocker->PerformDefaultAction(internal::move(args), call_description);
func_mocker->PerformDefaultAction(std::move(args), call_description);
return new ActionResultHolder;
}
@ -1451,9 +1444,8 @@ class ActionResultHolder<void> : public UntypedActionResultHolderBase {
// ActionResultHolder*.
template <typename F>
static ActionResultHolder* PerformAction(
const Action<F>& action,
typename RvalueRef<typename Function<F>::ArgumentTuple>::type args) {
action.Perform(internal::move(args));
const Action<F>& action, typename Function<F>::ArgumentTuple&& args) {
action.Perform(std::move(args));
return new ActionResultHolder;
}
@ -1462,23 +1454,39 @@ class ActionResultHolder<void> : public UntypedActionResultHolderBase {
GTEST_DISALLOW_COPY_AND_ASSIGN_(ActionResultHolder);
};
// The base of the function mocker class for the given function type.
// We put the methods in this class instead of its child to avoid code
// bloat.
template <typename F>
class FunctionMockerBase : public UntypedFunctionMockerBase {
public:
typedef typename Function<F>::Result Result;
typedef typename Function<F>::ArgumentTuple ArgumentTuple;
typedef typename Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple;
class FunctionMocker;
FunctionMockerBase() {}
template <typename R, typename... Args>
class FunctionMocker<R(Args...)> final : public UntypedFunctionMockerBase {
using F = R(Args...);
public:
using Result = R;
using ArgumentTuple = std::tuple<Args...>;
using ArgumentMatcherTuple = std::tuple<Matcher<Args>...>;
FunctionMocker() {}
// 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, they should implement their own copy
// operation, for example:
//
// class MockFoo : public Foo {
// public:
// // Defines a copy constructor explicitly.
// MockFoo(const MockFoo& src) {}
// ...
// };
FunctionMocker(const FunctionMocker&) = delete;
FunctionMocker& operator=(const FunctionMocker&) = delete;
// The destructor verifies that all expectations on this mock
// function have been satisfied. If not, it will report Google Test
// non-fatal failures for the violations.
virtual ~FunctionMockerBase()
GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
~FunctionMocker() override GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
MutexLock l(&g_gmock_mutex);
VerifyAndClearExpectationsLocked();
Mock::UnregisterLocked(this);
@ -1498,7 +1506,7 @@ class FunctionMockerBase : public UntypedFunctionMockerBase {
return spec;
}
return NULL;
return nullptr;
}
// Performs the default action of this mock function on the given
@ -1508,13 +1516,12 @@ class FunctionMockerBase : public UntypedFunctionMockerBase {
// mutable state of this object, and thus can be called concurrently
// without locking.
// L = *
Result PerformDefaultAction(
typename RvalueRef<typename Function<F>::ArgumentTuple>::type args,
const std::string& call_description) const {
Result PerformDefaultAction(ArgumentTuple&& args,
const std::string& call_description) const {
const OnCallSpec<F>* const spec =
this->FindOnCallSpec(args);
if (spec != NULL) {
return spec->GetAction().Perform(internal::move(args));
if (spec != nullptr) {
return spec->GetAction().Perform(std::move(args));
}
const std::string message =
call_description +
@ -1535,11 +1542,11 @@ class FunctionMockerBase : public UntypedFunctionMockerBase {
// the error message to describe the call in the case the default
// action fails. The caller is responsible for deleting the result.
// L = *
virtual UntypedActionResultHolderBase* UntypedPerformDefaultAction(
UntypedActionResultHolderBase* UntypedPerformDefaultAction(
void* untyped_args, // must point to an ArgumentTuple
const std::string& call_description) const {
const std::string& call_description) const override {
ArgumentTuple* args = static_cast<ArgumentTuple*>(untyped_args);
return ResultHolder::PerformDefaultAction(this, internal::move(*args),
return ResultHolder::PerformDefaultAction(this, std::move(*args),
call_description);
}
@ -1547,18 +1554,18 @@ class FunctionMockerBase : public UntypedFunctionMockerBase {
// the action's result. The caller is responsible for deleting the
// result.
// L = *
virtual UntypedActionResultHolderBase* UntypedPerformAction(
const void* untyped_action, void* untyped_args) const {
UntypedActionResultHolderBase* UntypedPerformAction(
const void* untyped_action, void* untyped_args) const override {
// 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);
ArgumentTuple* args = static_cast<ArgumentTuple*>(untyped_args);
return ResultHolder::PerformAction(action, internal::move(*args));
return ResultHolder::PerformAction(action, std::move(*args));
}
// Implements UntypedFunctionMockerBase::ClearDefaultActionsLocked():
// clears the ON_CALL()s set on this mock function.
virtual void ClearDefaultActionsLocked()
void ClearDefaultActionsLocked() override
GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
g_gmock_mutex.AssertHeld();
@ -1584,26 +1591,26 @@ class FunctionMockerBase : public UntypedFunctionMockerBase {
g_gmock_mutex.Lock();
}
// Returns the result of invoking this mock function with the given
// arguments. This function can be safely called from multiple
// threads concurrently.
Result Invoke(Args... args) GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
ArgumentTuple tuple(std::forward<Args>(args)...);
std::unique_ptr<ResultHolder> holder(DownCast_<ResultHolder*>(
this->UntypedInvokeWith(static_cast<void*>(&tuple))));
return holder->Unwrap();
}
MockSpec<F> With(Matcher<Args>... m) {
return MockSpec<F>(this, ::std::make_tuple(std::move(m)...));
}
protected:
template <typename Function>
friend class MockSpec;
typedef ActionResultHolder<Result> ResultHolder;
// Returns the result of invoking this mock function with the given
// arguments. This function can be safely called from multiple
// threads concurrently.
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(untyped_args)));
return holder->Unwrap();
}
// Adds and returns a default action spec for this mock function.
OnCallSpec<F>& AddNewOnCallSpec(
const char* file, int line,
@ -1623,14 +1630,14 @@ class FunctionMockerBase : public UntypedFunctionMockerBase {
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);
const std::shared_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));
}
@ -1649,10 +1656,9 @@ class FunctionMockerBase : public UntypedFunctionMockerBase {
::std::ostream* os) const {
const OnCallSpec<F>* const spec = FindOnCallSpec(args);
if (spec == NULL) {
*os << (internal::type_equals<Result, void>::value ?
"returning directly.\n" :
"returning default value.\n");
if (spec == nullptr) {
*os << (std::is_void<Result>::value ? "returning directly.\n"
: "returning default value.\n");
} else {
*os << "taking default action specified at:\n"
<< FormatFileLocation(spec->file(), spec->line()) << "\n";
@ -1662,10 +1668,9 @@ class FunctionMockerBase : public UntypedFunctionMockerBase {
// Writes a message that the call is uninteresting (i.e. neither
// explicitly expected nor explicitly unexpected) to the given
// ostream.
virtual void UntypedDescribeUninterestingCall(
const void* untyped_args,
::std::ostream* os) const
GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
void UntypedDescribeUninterestingCall(const void* untyped_args,
::std::ostream* os) const override
GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
const ArgumentTuple& args =
*static_cast<const ArgumentTuple*>(untyped_args);
*os << "Uninteresting mock function call - ";
@ -1690,18 +1695,17 @@ class FunctionMockerBase : public UntypedFunctionMockerBase {
// section. The reason is that we have no control on what the
// action does (it can invoke an arbitrary user function or even a
// mock function) and excessive locking could cause a dead lock.
virtual const ExpectationBase* UntypedFindMatchingExpectation(
const void* untyped_args,
const void** untyped_action, bool* is_excessive,
::std::ostream* what, ::std::ostream* why)
GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
const ExpectationBase* UntypedFindMatchingExpectation(
const void* untyped_args, const void** untyped_action, bool* is_excessive,
::std::ostream* what, ::std::ostream* why) override
GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
const ArgumentTuple& args =
*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(),
@ -1709,15 +1713,15 @@ 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;
}
// Prints the given function arguments to the ostream.
virtual void UntypedPrintArgs(const void* untyped_args,
::std::ostream* os) const {
void UntypedPrintArgs(const void* untyped_args,
::std::ostream* os) const override {
const ArgumentTuple& args =
*static_cast<const ArgumentTuple*>(untyped_args);
UniversalPrint(args, os);
@ -1740,7 +1744,7 @@ class FunctionMockerBase : public UntypedFunctionMockerBase {
return exp;
}
}
return NULL;
return nullptr;
}
// Returns a message that the arguments don't match any expectation.
@ -1762,12 +1766,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";
@ -1780,36 +1784,98 @@ class FunctionMockerBase : public UntypedFunctionMockerBase {
expectation->DescribeCallCountTo(why);
}
}
// 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, they should implement their own copy
// operation, for example:
//
// class MockFoo : public Foo {
// public:
// // Defines a copy constructor explicitly.
// MockFoo(const MockFoo& src) {}
// ...
// };
GTEST_DISALLOW_COPY_AND_ASSIGN_(FunctionMockerBase);
}; // class FunctionMockerBase
}; // class FunctionMocker
GTEST_DISABLE_MSC_WARNINGS_POP_() // 4355
// Implements methods of FunctionMockerBase.
// Verifies that all expectations on this mock function have been
// satisfied. Reports one or more Google Test non-fatal failures and
// returns false if not.
// Reports an uninteresting call (whose description is in msg) in the
// manner specified by 'reaction'.
void ReportUninterestingCall(CallReaction reaction, const std::string& msg);
} // namespace internal
// A MockFunction<F> class has one mock method whose type is F. It is
// useful when you just want your test code to emit some messages and
// have Google Mock verify the right messages are sent (and perhaps at
// the right times). 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:
//
// TEST(FooTest, InvokesBarCorrectly) {
// MyMock mock;
// 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().
//
// MockFunction<F> can also be used to exercise code that accepts
// std::function<F> callbacks. To do so, use AsStdFunction() method
// to create std::function proxy forwarding to original object's Call.
// Example:
//
// TEST(FooTest, RunsCallbackWithBarArgument) {
// MockFunction<int(string)> callback;
// EXPECT_CALL(callback, Call("bar")).WillOnce(Return(1));
// Foo(callback.AsStdFunction());
// }
template <typename F>
class MockFunction;
template <typename R, typename... Args>
class MockFunction<R(Args...)> {
public:
MockFunction() {}
MockFunction(const MockFunction&) = delete;
MockFunction& operator=(const MockFunction&) = delete;
std::function<R(Args...)> AsStdFunction() {
return [this](Args... args) -> R {
return this->Call(std::forward<Args>(args)...);
};
}
// Implementation detail: the expansion of the MOCK_METHOD macro.
R Call(Args... args) {
mock_.SetOwnerAndName(this, "Call");
return mock_.Invoke(std::forward<Args>(args)...);
}
internal::MockSpec<R(Args...)> gmock_Call(Matcher<Args>... m) {
mock_.RegisterOwner(this);
return mock_.With(std::move(m)...);
}
internal::MockSpec<R(Args...)> gmock_Call(const internal::WithoutMatchers&,
R (*)(Args...)) {
return this->gmock_Call(::testing::A<Args>()...);
}
private:
internal::FunctionMocker<R(Args...)> mock_;
};
// The style guide prohibits "using" statements in a namespace scope
// inside a header file. However, the MockSpec class template is
// meant to be defined in the ::testing namespace. The following line
@ -1905,8 +1971,9 @@ GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
// 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) \
#define GMOCK_ON_CALL_IMPL_(mock_expr, Setter, call) \
((mock_expr).gmock_##call)(::testing::internal::GetWithoutMatchers(), \
nullptr) \
.Setter(__FILE__, __LINE__, #mock_expr, #call)
#define ON_CALL(obj, call) \

View File

@ -39,14 +39,14 @@
// This file implements the following syntax:
//
// ON_CALL(mock_object.Method(...))
// ON_CALL(mock_object, Method(...))
// .With(...) ?
// .WillByDefault(...);
//
// where With() is optional and WillByDefault() must appear exactly
// once.
//
// EXPECT_CALL(mock_object.Method(...))
// EXPECT_CALL(mock_object, Method(...))
// .With(...) ?
// .Times(...) ?
// .InSequence(...) *
@ -58,13 +58,14 @@
#include "gmock/gmock-actions.h"
#include "gmock/gmock-cardinalities.h"
#include "gmock/gmock-function-mocker.h"
#include "gmock/gmock-generated-actions.h"
#include "gmock/gmock-generated-function-mockers.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"
#include "gmock/gmock-nice-strict.h"
#include "gmock/internal/gmock-internal-utils.h"
namespace testing {
@ -91,6 +92,10 @@ GTEST_API_ void InitGoogleMock(int* argc, char** argv);
// UNICODE mode.
GTEST_API_ void InitGoogleMock(int* argc, wchar_t** argv);
// This overloaded version can be used on Arduino/embedded platforms where
// there is no argc/argv.
GTEST_API_ void InitGoogleMock();
} // namespace testing
#endif // GMOCK_INCLUDE_GMOCK_GMOCK_H_

View File

@ -1,287 +0,0 @@
// This file was GENERATED by command:
// pump.py gmock-generated-internal-utils.h.pump
// DO NOT EDIT BY HAND!!!
// Copyright 2007, 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.
// 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_
#include "gmock/internal/gmock-port.h"
namespace testing {
template <typename T>
class Matcher;
namespace internal {
// An IgnoredValue object can be implicitly constructed from ANY value.
// This is used in implementing the IgnoreResult(a) action.
class IgnoredValue {
public:
// This constructor template allows any value to be implicitly
// converted to IgnoredValue. The object has no data member and
// doesn't try to remember anything about the argument. We
// deliberately omit the 'explicit' keyword in order to allow the
// conversion to be implicit.
template <typename T>
IgnoredValue(const T& /* ignored */) {} // NOLINT(runtime/explicit)
};
// MatcherTuple<T>::type is a tuple type where each field is a Matcher
// for the corresponding field in tuple type T.
template <typename Tuple>
struct MatcherTuple;
template <>
struct MatcherTuple< ::testing::tuple<> > {
typedef ::testing::tuple< > type;
};
template <typename A1>
struct MatcherTuple< ::testing::tuple<A1> > {
typedef ::testing::tuple<Matcher<A1> > type;
};
template <typename A1, typename A2>
struct MatcherTuple< ::testing::tuple<A1, A2> > {
typedef ::testing::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;
};
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>, 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>,
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>,
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>,
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>,
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>,
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>,
Matcher<A5>, Matcher<A6>, Matcher<A7>, Matcher<A8>,
Matcher<A9>, Matcher<A10> >
type;
};
// Template struct Function<F>, where F must be a function type, contains
// the following typedefs:
//
// Result: the function's return type.
// ArgumentN: the type of the N-th argument, where N starts with 1.
// ArgumentTuple: the tuple type consisting of all parameters of F.
// ArgumentMatcherTuple: the tuple type consisting of Matchers for all
// parameters of F.
// MakeResultVoid: the function type obtained by substituting void
// for the return type of F.
// MakeResultIgnoredValue:
// the function type obtained by substituting Something
// for the return type of F.
template <typename F>
struct Function;
template <typename R>
struct Function<R()> {
typedef R Result;
typedef ::testing::tuple<> ArgumentTuple;
typedef typename MatcherTuple<ArgumentTuple>::type ArgumentMatcherTuple;
typedef void MakeResultVoid();
typedef IgnoredValue MakeResultIgnoredValue();
};
template <typename R, typename A1>
struct Function<R(A1)>
: Function<R()> {
typedef A1 Argument1;
typedef ::testing::tuple<A1> ArgumentTuple;
typedef typename MatcherTuple<ArgumentTuple>::type ArgumentMatcherTuple;
typedef void MakeResultVoid(A1);
typedef IgnoredValue MakeResultIgnoredValue(A1);
};
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 typename MatcherTuple<ArgumentTuple>::type ArgumentMatcherTuple;
typedef void MakeResultVoid(A1, A2);
typedef IgnoredValue MakeResultIgnoredValue(A1, A2);
};
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 typename MatcherTuple<ArgumentTuple>::type ArgumentMatcherTuple;
typedef void MakeResultVoid(A1, A2, A3);
typedef IgnoredValue MakeResultIgnoredValue(A1, A2, A3);
};
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 typename MatcherTuple<ArgumentTuple>::type ArgumentMatcherTuple;
typedef void MakeResultVoid(A1, A2, A3, A4);
typedef IgnoredValue MakeResultIgnoredValue(A1, A2, A3, A4);
};
template <typename R, typename A1, typename A2, typename A3, typename A4,
typename A5>
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 typename MatcherTuple<ArgumentTuple>::type ArgumentMatcherTuple;
typedef void MakeResultVoid(A1, A2, A3, A4, A5);
typedef IgnoredValue MakeResultIgnoredValue(A1, A2, A3, A4, A5);
};
template <typename R, typename A1, typename A2, typename A3, typename A4,
typename A5, typename A6>
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 typename MatcherTuple<ArgumentTuple>::type ArgumentMatcherTuple;
typedef void MakeResultVoid(A1, A2, A3, A4, A5, A6);
typedef IgnoredValue MakeResultIgnoredValue(A1, A2, A3, A4, A5, A6);
};
template <typename R, typename A1, typename A2, typename A3, typename A4,
typename A5, typename A6, typename A7>
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 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);
};
template <typename R, typename A1, typename A2, typename A3, typename A4,
typename A5, typename A6, typename A7, typename A8>
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 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);
};
template <typename R, typename A1, typename A2, typename A3, typename A4,
typename A5, typename A6, typename A7, typename A8, typename A9>
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 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,
A9);
};
template <typename R, typename A1, typename A2, typename A3, typename A4,
typename A5, typename A6, typename A7, typename A8, typename A9,
typename A10>
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 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,
A9, A10);
};
} // namespace internal
} // namespace testing
#endif // GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_GENERATED_INTERNAL_UTILS_H_

View File

@ -1,137 +0,0 @@
$$ -*- mode: c++; -*-
$$ 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.
// 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.
// 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_
#include "gmock/internal/gmock-port.h"
namespace testing {
template <typename T>
class Matcher;
namespace internal {
// An IgnoredValue object can be implicitly constructed from ANY value.
// This is used in implementing the IgnoreResult(a) action.
class IgnoredValue {
public:
// This constructor template allows any value to be implicitly
// converted to IgnoredValue. The object has no data member and
// doesn't try to remember anything about the argument. We
// deliberately omit the 'explicit' keyword in order to allow the
// conversion to be implicit.
template <typename T>
IgnoredValue(const T& /* ignored */) {} // NOLINT(runtime/explicit)
};
// MatcherTuple<T>::type is a tuple type where each field is a Matcher
// for the corresponding field in tuple type T.
template <typename Tuple>
struct MatcherTuple;
$range i 0..n
$for i [[
$range j 1..i
$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;
};
]]
// Template struct Function<F>, where F must be a function type, contains
// the following typedefs:
//
// Result: the function's return type.
// ArgumentN: the type of the N-th argument, where N starts with 1.
// ArgumentTuple: the tuple type consisting of all parameters of F.
// ArgumentMatcherTuple: the tuple type consisting of Matchers for all
// parameters of F.
// MakeResultVoid: the function type obtained by substituting void
// for the return type of F.
// MakeResultIgnoredValue:
// the function type obtained by substituting Something
// for the return type of F.
template <typename F>
struct Function;
template <typename R>
struct Function<R()> {
typedef R Result;
typedef ::testing::tuple<> ArgumentTuple;
typedef typename MatcherTuple<ArgumentTuple>::type ArgumentMatcherTuple;
typedef void MakeResultVoid();
typedef IgnoredValue MakeResultIgnoredValue();
};
$range i 1..n
$for i [[
$range j 1..i
$var typename_As = [[$for j [[, typename A$j]]]]
$var As = [[$for j, [[A$j]]]]
$var matcher_As = [[$for j, [[Matcher<A$j>]]]]
$range k 1..i-1
$var prev_As = [[$for k, [[A$k]]]]
template <typename R$typename_As>
struct Function<R($As)>
: Function<R($prev_As)> {
typedef A$i Argument$i;
typedef ::testing::tuple<$As> ArgumentTuple;
typedef typename MatcherTuple<ArgumentTuple>::type ArgumentMatcherTuple;
typedef void MakeResultVoid($As);
typedef IgnoredValue MakeResultIgnoredValue($As);
};
]]
} // namespace internal
} // namespace testing
#endif // GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_GENERATED_INTERNAL_UTILS_H_

View File

@ -42,11 +42,15 @@
#include <stdio.h>
#include <ostream> // NOLINT
#include <string>
#include "gmock/internal/gmock-generated-internal-utils.h"
#include <type_traits>
#include "gmock/internal/gmock-port.h"
#include "gtest/gtest.h"
namespace testing {
template <typename>
class Matcher;
namespace internal {
// Silence MSVC C4100 (unreferenced formal parameter) and
@ -92,46 +96,16 @@ inline const typename Pointer::element_type* GetRawPointer(const Pointer& p) {
template <typename Element>
inline Element* GetRawPointer(Element* p) { return p; }
// This comparator allows linked_ptr to be stored in sets.
template <typename T>
struct LinkedPtrLessThan {
bool operator()(const ::testing::internal::linked_ptr<T>& lhs,
const ::testing::internal::linked_ptr<T>& rhs) const {
return lhs.get() < rhs.get();
}
};
// Symbian compilation can be done with wchar_t being either a native
// type or a typedef. Using Google Mock with OpenC without wchar_t
// should require the definition of _STLP_NO_WCHAR_T.
//
// MSVC treats wchar_t as a native type usually, but treats it as the
// same as unsigned short when the compiler option /Zc:wchar_t- is
// specified. It defines _NATIVE_WCHAR_T_DEFINED symbol when wchar_t
// is a native type.
#if (GTEST_OS_SYMBIAN && defined(_STLP_NO_WCHAR_T)) || \
(defined(_MSC_VER) && !defined(_NATIVE_WCHAR_T_DEFINED))
#if defined(_MSC_VER) && !defined(_NATIVE_WCHAR_T_DEFINED)
// wchar_t is a typedef.
#else
# define GMOCK_WCHAR_T_IS_NATIVE_ 1
#endif
// signed wchar_t and unsigned wchar_t are NOT in the C++ standard.
// Using them is a bad practice and not portable. So DON'T use them.
//
// Still, Google Mock is designed to work even if the user uses signed
// wchar_t or unsigned wchar_t (obviously, assuming the compiler
// supports them).
//
// 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,
// or none of them. This categorization is useful for determining
@ -183,11 +157,11 @@ GMOCK_DECLARE_KIND_(long double, kFloatingPoint);
static_cast< ::testing::internal::TypeKind>( \
::testing::internal::KindOf<type>::value)
// Evaluates to true iff integer type T is signed.
// Evaluates to true if and only if integer type T is signed.
#define GMOCK_IS_SIGNED_(T) (static_cast<T>(-1) < 0)
// LosslessArithmeticConvertibleImpl<kFromKind, From, kToKind, To>::value
// is true iff arithmetic type From can be losslessly converted to
// is true if and only if arithmetic type From can be losslessly converted to
// arithmetic type To.
//
// It's the user's responsibility to ensure that both From and To are
@ -196,30 +170,30 @@ GMOCK_DECLARE_KIND_(long double, kFloatingPoint);
// From, and kToKind is the kind of To; the value is
// implementation-defined when the above pre-condition is violated.
template <TypeKind kFromKind, typename From, TypeKind kToKind, typename To>
struct LosslessArithmeticConvertibleImpl : public false_type {};
struct LosslessArithmeticConvertibleImpl : public std::false_type {};
// Converting bool to bool is lossless.
template <>
struct LosslessArithmeticConvertibleImpl<kBool, bool, kBool, bool>
: public true_type {}; // NOLINT
: public std::true_type {};
// Converting bool to any integer type is lossless.
template <typename To>
struct LosslessArithmeticConvertibleImpl<kBool, bool, kInteger, To>
: public true_type {}; // NOLINT
: public std::true_type {};
// Converting bool to any floating-point type is lossless.
template <typename To>
struct LosslessArithmeticConvertibleImpl<kBool, bool, kFloatingPoint, To>
: public true_type {}; // NOLINT
: public std::true_type {};
// Converting an integer to bool is lossy.
template <typename From>
struct LosslessArithmeticConvertibleImpl<kInteger, From, kBool, bool>
: public false_type {}; // NOLINT
: public std::false_type {};
// Converting an integer to another non-bool integer is lossless iff
// the target type's range encloses the source type's range.
// Converting an integer to another non-bool integer is lossless
// if and only if the target type's range encloses the source type's range.
template <typename From, typename To>
struct LosslessArithmeticConvertibleImpl<kInteger, From, kInteger, To>
: public bool_constant<
@ -237,27 +211,27 @@ struct LosslessArithmeticConvertibleImpl<kInteger, From, kInteger, To>
// the format of a floating-point number is implementation-defined.
template <typename From, typename To>
struct LosslessArithmeticConvertibleImpl<kInteger, From, kFloatingPoint, To>
: public false_type {}; // NOLINT
: public std::false_type {};
// Converting a floating-point to bool is lossy.
template <typename From>
struct LosslessArithmeticConvertibleImpl<kFloatingPoint, From, kBool, bool>
: public false_type {}; // NOLINT
: public std::false_type {};
// Converting a floating-point to an integer is lossy.
template <typename From, typename To>
struct LosslessArithmeticConvertibleImpl<kFloatingPoint, From, kInteger, To>
: public false_type {}; // NOLINT
: public std::false_type {};
// Converting a floating-point to another floating-point is lossless
// iff the target type is at least as big as the source type.
// if and only if the target type is at least as big as the source type.
template <typename From, typename To>
struct LosslessArithmeticConvertibleImpl<
kFloatingPoint, From, kFloatingPoint, To>
: public bool_constant<sizeof(From) <= sizeof(To)> {}; // NOLINT
// LosslessArithmeticConvertible<From, To>::value is true iff arithmetic
// type From can be losslessly converted to arithmetic type To.
// LosslessArithmeticConvertible<From, To>::value is true if and only if
// arithmetic type From can be losslessly converted to arithmetic type To.
//
// It's the user's responsibility to ensure that both From and To are
// raw (i.e. has no CV modifier, is not a pointer, and is not a
@ -331,11 +305,11 @@ const char kWarningVerbosity[] = "warning";
// No logs are printed.
const char kErrorVerbosity[] = "error";
// Returns true iff a log with the given severity is visible according
// to the --gmock_verbose flag.
// Returns true if and only if a log with the given severity is visible
// according to the --gmock_verbose flag.
GTEST_API_ bool LogIsVisible(LogSeverity severity);
// Prints the given message to stdout iff 'severity' >= the level
// Prints the given message to stdout if and only if 'severity' >= the level
// specified by the --gmock_verbose flag. If stack_frames_to_skip >=
// 0, also prints the stack trace excluding the top
// stack_frames_to_skip frames. In opt mode, any positive
@ -360,35 +334,8 @@ class WithoutMatchers {
// Internal use only: access the singleton instance of WithoutMatchers.
GTEST_API_ WithoutMatchers GetWithoutMatchers();
// FIXME: group all type utilities together.
// Type traits.
// is_reference<T>::value is non-zero iff T is a reference type.
template <typename T> struct is_reference : public false_type {};
template <typename T> struct is_reference<T&> : public true_type {};
// type_equals<T1, T2>::value is non-zero iff T1 and T2 are the same type.
template <typename T1, typename T2> struct type_equals : public false_type {};
template <typename T> struct type_equals<T, T> : public true_type {};
// remove_reference<T>::type removes the reference from type T, if any.
template <typename T> struct remove_reference { typedef T type; }; // NOLINT
template <typename T> struct remove_reference<T&> { typedef T type; }; // NOLINT
// DecayArray<T>::type turns an array type U[N] to const U* and preserves
// other types. Useful for saving a copy of a function argument.
template <typename T> struct DecayArray { typedef T type; }; // NOLINT
template <typename T, size_t N> struct DecayArray<T[N]> {
typedef const T* type;
};
// Sometimes people use arrays whose size is not available at the use site
// (e.g. extern const char kNamePrefix[]). This specialization covers that
// case.
template <typename T> struct DecayArray<T[]> {
typedef const T* type;
};
// Disable MSVC warnings for infinite recursion, since in this case the
// the recursion is unreachable.
#ifdef _MSC_VER
@ -437,9 +384,8 @@ class StlContainerView {
typedef const type& const_reference;
static const_reference ConstReference(const RawContainer& container) {
// Ensures that RawContainer is not a const type.
testing::StaticAssertTypeEq<RawContainer,
GTEST_REMOVE_CONST_(RawContainer)>();
static_assert(!std::is_const<RawContainer>::value,
"RawContainer type must not be const");
return container;
}
static type Copy(const RawContainer& container) { return container; }
@ -449,7 +395,7 @@ class StlContainerView {
template <typename Element, size_t N>
class StlContainerView<Element[N]> {
public:
typedef GTEST_REMOVE_CONST_(Element) RawElement;
typedef typename std::remove_const<Element>::type RawElement;
typedef internal::NativeArray<RawElement> type;
// NativeArray<T> can represent a native array either by value or by
// reference (selected by a constructor argument), so 'const type'
@ -459,53 +405,32 @@ class StlContainerView<Element[N]> {
typedef const type const_reference;
static const_reference ConstReference(const Element (&array)[N]) {
// Ensures that Element is not a const type.
testing::StaticAssertTypeEq<Element, RawElement>();
#if GTEST_OS_SYMBIAN
// The Nokia Symbian compiler confuses itself in template instantiation
// for this call without the cast to Element*:
// function call '[testing::internal::NativeArray<char *>].NativeArray(
// {lval} const char *[4], long, testing::internal::RelationToSource)'
// does not match
// 'testing::internal::NativeArray<char *>::NativeArray(
// char *const *, unsigned int, testing::internal::RelationToSource)'
// (instantiating: 'testing::internal::ContainsMatcherImpl
// <const char * (&)[4]>::Matches(const char * (&)[4]) const')
// (instantiating: 'testing::internal::StlContainerView<char *[4]>::
// ConstReference(const char * (&)[4])')
// (and though the N parameter type is mismatched in the above explicit
// conversion of it doesn't help - only the conversion of the array).
return type(const_cast<Element*>(&array[0]), N,
RelationToSourceReference());
#else
static_assert(std::is_same<Element, RawElement>::value,
"Element type must not be const");
return type(array, N, RelationToSourceReference());
#endif // GTEST_OS_SYMBIAN
}
static type Copy(const Element (&array)[N]) {
#if GTEST_OS_SYMBIAN
return type(const_cast<Element*>(&array[0]), N, RelationToSourceCopy());
#else
return type(array, N, RelationToSourceCopy());
#endif // GTEST_OS_SYMBIAN
}
};
// 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;
typedef typename std::remove_const<
typename internal::PointeeOf<ElementPointer>::type>::type RawElement;
typedef internal::NativeArray<RawElement> type;
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());
}
};
@ -527,29 +452,12 @@ struct RemoveConstFromKey<std::pair<const K, V> > {
typedef std::pair<K, V> type;
};
// Mapping from booleans to types. Similar to boost::bool_<kValue> and
// std::integral_constant<bool, kValue>.
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(
auto ApplyImpl(F&& f, Tuple&& args, IndexSequence<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))...);
}
@ -558,12 +466,42 @@ auto ApplyImpl(F&& f, Tuple&& args, int_pack<Idx...>) -> decltype(
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>())) {
MakeIndexSequence<std::tuple_size<Tuple>::value>())) {
return ApplyImpl(std::forward<F>(f), std::forward<Tuple>(args),
make_int_pack<std::tuple_size<Tuple>::value>());
MakeIndexSequence<std::tuple_size<Tuple>::value>());
}
#endif
// Template struct Function<F>, where F must be a function type, contains
// the following typedefs:
//
// Result: the function's return type.
// Arg<N>: the type of the N-th argument, where N starts with 0.
// ArgumentTuple: the tuple type consisting of all parameters of F.
// ArgumentMatcherTuple: the tuple type consisting of Matchers for all
// parameters of F.
// MakeResultVoid: the function type obtained by substituting void
// for the return type of F.
// MakeResultIgnoredValue:
// the function type obtained by substituting Something
// for the return type of F.
template <typename T>
struct Function;
template <typename R, typename... Args>
struct Function<R(Args...)> {
using Result = R;
static constexpr size_t ArgumentCount = sizeof...(Args);
template <size_t I>
using Arg = ElemFromList<I, typename MakeIndexSequence<sizeof...(Args)>::type,
Args...>;
using ArgumentTuple = std::tuple<Args...>;
using ArgumentMatcherTuple = std::tuple<Matcher<Args>...>;
using MakeResultVoid = void(Args...);
using MakeResultIgnoredValue = IgnoredValue(Args...);
};
template <typename R, typename... Args>
constexpr size_t Function<R(Args...)>::ArgumentCount;
#ifdef _MSC_VER
# pragma warning(pop)

View File

@ -52,14 +52,13 @@
// 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"
// For MS Visual C++, check the compiler version. At least VS 2003 is
// For MS Visual C++, check the compiler version. At least VS 2015 is
// required to compile Google Mock.
#if defined(_MSC_VER) && _MSC_VER < 1310
# error "At least Visual C++ 2003 (7.1) is required to compile Google Mock."
#if defined(_MSC_VER) && _MSC_VER < 1900
# error "At least Visual C++ 2015 (14.0) is required to compile Google Mock."
#endif
// Macro for referencing flags. This is public as we want the user to

View File

@ -0,0 +1,317 @@
#ifndef THIRD_PARTY_GOOGLETEST_GOOGLEMOCK_INCLUDE_GMOCK_PP_H_
#define THIRD_PARTY_GOOGLETEST_GOOGLEMOCK_INCLUDE_GMOCK_PP_H_
#undef GMOCK_PP_INTERNAL_USE_MSVC
#if defined(__clang__)
#define GMOCK_PP_INTERNAL_USE_MSVC 0
#elif defined(_MSC_VER)
// TODO(iserna): Also verify tradional versus comformant preprocessor.
static_assert(
_MSC_VER >= 1900,
"MSVC version not supported. There is support for MSVC 14.0 and above.");
#define GMOCK_PP_INTERNAL_USE_MSVC 1
#else
#define GMOCK_PP_INTERNAL_USE_MSVC 0
#endif
// Expands and concatenates the arguments. Constructed macros reevaluate.
#define GMOCK_PP_CAT(_1, _2) GMOCK_PP_INTERNAL_CAT(_1, _2)
// Expands and stringifies the only argument.
#define GMOCK_PP_STRINGIZE(...) GMOCK_PP_INTERNAL_STRINGIZE(__VA_ARGS__)
// Returns empty. Given a variadic number of arguments.
#define GMOCK_PP_EMPTY(...)
// Returns a comma. Given a variadic number of arguments.
#define GMOCK_PP_COMMA(...) ,
// Returns the only argument.
#define GMOCK_PP_IDENTITY(_1) _1
// MSVC preprocessor collapses __VA_ARGS__ in a single argument, we use a
// CAT-like directive to force correct evaluation. Each macro has its own.
#if GMOCK_PP_INTERNAL_USE_MSVC
// Evaluates to the number of arguments after expansion.
//
// #define PAIR x, y
//
// GMOCK_PP_NARG() => 1
// GMOCK_PP_NARG(x) => 1
// GMOCK_PP_NARG(x, y) => 2
// GMOCK_PP_NARG(PAIR) => 2
//
// Requires: the number of arguments after expansion is at most 15.
#define GMOCK_PP_NARG(...) \
GMOCK_PP_INTERNAL_NARG_CAT( \
GMOCK_PP_INTERNAL_INTERNAL_16TH(__VA_ARGS__, 15, 14, 13, 12, 11, 10, 9, \
8, 7, 6, 5, 4, 3, 2, 1), )
// Returns 1 if the expansion of arguments has an unprotected comma. Otherwise
// returns 0. Requires no more than 15 unprotected commas.
#define GMOCK_PP_HAS_COMMA(...) \
GMOCK_PP_INTERNAL_HAS_COMMA_CAT( \
GMOCK_PP_INTERNAL_INTERNAL_16TH(__VA_ARGS__, 1, 1, 1, 1, 1, 1, 1, 1, 1, \
1, 1, 1, 1, 1, 0), )
// Returns the first argument.
#define GMOCK_PP_HEAD(...) \
GMOCK_PP_INTERNAL_HEAD_CAT(GMOCK_PP_INTERNAL_HEAD(__VA_ARGS__), )
// Returns the tail. A variadic list of all arguments minus the first. Requires
// at least one argument.
#define GMOCK_PP_TAIL(...) \
GMOCK_PP_INTERNAL_TAIL_CAT(GMOCK_PP_INTERNAL_TAIL(__VA_ARGS__), )
// Calls CAT(_Macro, NARG(__VA_ARGS__))(__VA_ARGS__)
#define GMOCK_PP_VARIADIC_CALL(_Macro, ...) \
GMOCK_PP_INTERNAL_VARIADIC_CALL_CAT( \
GMOCK_PP_CAT(_Macro, GMOCK_PP_NARG(__VA_ARGS__))(__VA_ARGS__), )
#else // GMOCK_PP_INTERNAL_USE_MSVC
#define GMOCK_PP_NARG(...) \
GMOCK_PP_INTERNAL_INTERNAL_16TH(__VA_ARGS__, 15, 14, 13, 12, 11, 10, 9, 8, \
7, 6, 5, 4, 3, 2, 1)
#define GMOCK_PP_HAS_COMMA(...) \
GMOCK_PP_INTERNAL_INTERNAL_16TH(__VA_ARGS__, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, \
1, 1, 1, 1, 0)
#define GMOCK_PP_HEAD(...) GMOCK_PP_INTERNAL_HEAD(__VA_ARGS__)
#define GMOCK_PP_TAIL(...) GMOCK_PP_INTERNAL_TAIL(__VA_ARGS__)
#define GMOCK_PP_VARIADIC_CALL(_Macro, ...) \
GMOCK_PP_CAT(_Macro, GMOCK_PP_NARG(__VA_ARGS__))(__VA_ARGS__)
#endif // GMOCK_PP_INTERNAL_USE_MSVC
// If the arguments after expansion have no tokens, evaluates to `1`. Otherwise
// evaluates to `0`.
//
// Requires: * the number of arguments after expansion is at most 15.
// * If the argument is a macro, it must be able to be called with one
// argument.
//
// Implementation details:
//
// There is one case when it generates a compile error: if the argument is macro
// that cannot be called with one argument.
//
// #define M(a, b) // it doesn't matter what it expands to
//
// // Expected: expands to `0`.
// // Actual: compile error.
// GMOCK_PP_IS_EMPTY(M)
//
// There are 4 cases tested:
//
// * __VA_ARGS__ possible expansion has no unparen'd commas. Expected 0.
// * __VA_ARGS__ possible expansion is not enclosed in parenthesis. Expected 0.
// * __VA_ARGS__ possible expansion is not a macro that ()-evaluates to a comma.
// Expected 0
// * __VA_ARGS__ is empty, or has unparen'd commas, or is enclosed in
// parenthesis, or is a macro that ()-evaluates to comma. Expected 1.
//
// We trigger detection on '0001', i.e. on empty.
#define GMOCK_PP_IS_EMPTY(...) \
GMOCK_PP_INTERNAL_IS_EMPTY(GMOCK_PP_HAS_COMMA(__VA_ARGS__), \
GMOCK_PP_HAS_COMMA(GMOCK_PP_COMMA __VA_ARGS__), \
GMOCK_PP_HAS_COMMA(__VA_ARGS__()), \
GMOCK_PP_HAS_COMMA(GMOCK_PP_COMMA __VA_ARGS__()))
// Evaluates to _Then if _Cond is 1 and _Else if _Cond is 0.
#define GMOCK_PP_IF(_Cond, _Then, _Else) \
GMOCK_PP_CAT(GMOCK_PP_INTERNAL_IF_, _Cond)(_Then, _Else)
// Evaluates to the number of arguments after expansion. Identifies 'empty' as
// 0.
//
// #define PAIR x, y
//
// GMOCK_PP_NARG0() => 0
// GMOCK_PP_NARG0(x) => 1
// GMOCK_PP_NARG0(x, y) => 2
// GMOCK_PP_NARG0(PAIR) => 2
//
// Requires: * the number of arguments after expansion is at most 15.
// * If the argument is a macro, it must be able to be called with one
// argument.
#define GMOCK_PP_NARG0(...) \
GMOCK_PP_IF(GMOCK_PP_IS_EMPTY(__VA_ARGS__), 0, GMOCK_PP_NARG(__VA_ARGS__))
// Expands to 1 if the first argument starts with something in parentheses,
// otherwise to 0.
#define GMOCK_PP_IS_BEGIN_PARENS(...) \
GMOCK_PP_INTERNAL_ALTERNATE_HEAD( \
GMOCK_PP_CAT(GMOCK_PP_INTERNAL_IBP_IS_VARIADIC_R_, \
GMOCK_PP_INTERNAL_IBP_IS_VARIADIC_C __VA_ARGS__))
// Expands to 1 is there is only one argument and it is enclosed in parentheses.
#define GMOCK_PP_IS_ENCLOSED_PARENS(...) \
GMOCK_PP_IF(GMOCK_PP_IS_BEGIN_PARENS(__VA_ARGS__), \
GMOCK_PP_IS_EMPTY(GMOCK_PP_EMPTY __VA_ARGS__), 0)
// Remove the parens, requires GMOCK_PP_IS_ENCLOSED_PARENS(args) => 1.
#define GMOCK_PP_REMOVE_PARENS(...) GMOCK_PP_INTERNAL_REMOVE_PARENS __VA_ARGS__
// Expands to _Macro(0, _Data, e1) _Macro(1, _Data, e2) ... _Macro(K -1, _Data,
// eK) as many of GMOCK_INTERNAL_NARG0 _Tuple.
// Requires: * |_Macro| can be called with 3 arguments.
// * |_Tuple| expansion has no more than 15 elements.
#define GMOCK_PP_FOR_EACH(_Macro, _Data, _Tuple) \
GMOCK_PP_CAT(GMOCK_PP_INTERNAL_FOR_EACH_IMPL_, GMOCK_PP_NARG0 _Tuple) \
(0, _Macro, _Data, _Tuple)
// Expands to _Macro(0, _Data, ) _Macro(1, _Data, ) ... _Macro(K - 1, _Data, )
// Empty if _K = 0.
// Requires: * |_Macro| can be called with 3 arguments.
// * |_K| literal between 0 and 15
#define GMOCK_PP_REPEAT(_Macro, _Data, _N) \
GMOCK_PP_CAT(GMOCK_PP_INTERNAL_FOR_EACH_IMPL_, _N) \
(0, _Macro, _Data, GMOCK_PP_INTENRAL_EMPTY_TUPLE)
// Increments the argument, requires the argument to be between 0 and 15.
#define GMOCK_PP_INC(_i) GMOCK_PP_CAT(GMOCK_PP_INTERNAL_INC_, _i)
// Returns comma if _i != 0. Requires _i to be between 0 and 15.
#define GMOCK_PP_COMMA_IF(_i) GMOCK_PP_CAT(GMOCK_PP_INTERNAL_COMMA_IF_, _i)
// Internal details follow. Do not use any of these symbols outside of this
// file or we will break your code.
#define GMOCK_PP_INTENRAL_EMPTY_TUPLE (, , , , , , , , , , , , , , , )
#define GMOCK_PP_INTERNAL_CAT(_1, _2) _1##_2
#define GMOCK_PP_INTERNAL_STRINGIZE(...) #__VA_ARGS__
#define GMOCK_PP_INTERNAL_INTERNAL_16TH(_1, _2, _3, _4, _5, _6, _7, _8, _9, \
_10, _11, _12, _13, _14, _15, _16, \
...) \
_16
#define GMOCK_PP_INTERNAL_CAT_5(_1, _2, _3, _4, _5) _1##_2##_3##_4##_5
#define GMOCK_PP_INTERNAL_IS_EMPTY(_1, _2, _3, _4) \
GMOCK_PP_HAS_COMMA(GMOCK_PP_INTERNAL_CAT_5(GMOCK_PP_INTERNAL_IS_EMPTY_CASE_, \
_1, _2, _3, _4))
#define GMOCK_PP_INTERNAL_IS_EMPTY_CASE_0001 ,
#define GMOCK_PP_INTERNAL_IF_1(_Then, _Else) _Then
#define GMOCK_PP_INTERNAL_IF_0(_Then, _Else) _Else
#define GMOCK_PP_INTERNAL_HEAD(_1, ...) _1
#define GMOCK_PP_INTERNAL_TAIL(_1, ...) __VA_ARGS__
#if GMOCK_PP_INTERNAL_USE_MSVC
#define GMOCK_PP_INTERNAL_NARG_CAT(_1, _2) GMOCK_PP_INTERNAL_NARG_CAT_I(_1, _2)
#define GMOCK_PP_INTERNAL_HEAD_CAT(_1, _2) GMOCK_PP_INTERNAL_HEAD_CAT_I(_1, _2)
#define GMOCK_PP_INTERNAL_HAS_COMMA_CAT(_1, _2) \
GMOCK_PP_INTERNAL_HAS_COMMA_CAT_I(_1, _2)
#define GMOCK_PP_INTERNAL_TAIL_CAT(_1, _2) GMOCK_PP_INTERNAL_TAIL_CAT_I(_1, _2)
#define GMOCK_PP_INTERNAL_VARIADIC_CALL_CAT(_1, _2) \
GMOCK_PP_INTERNAL_VARIADIC_CALL_CAT_I(_1, _2)
#define GMOCK_PP_INTERNAL_NARG_CAT_I(_1, _2) _1##_2
#define GMOCK_PP_INTERNAL_HEAD_CAT_I(_1, _2) _1##_2
#define GMOCK_PP_INTERNAL_HAS_COMMA_CAT_I(_1, _2) _1##_2
#define GMOCK_PP_INTERNAL_TAIL_CAT_I(_1, _2) _1##_2
#define GMOCK_PP_INTERNAL_VARIADIC_CALL_CAT_I(_1, _2) _1##_2
#define GMOCK_PP_INTERNAL_ALTERNATE_HEAD(...) \
GMOCK_PP_INTERNAL_ALTERNATE_HEAD_CAT(GMOCK_PP_HEAD(__VA_ARGS__), )
#define GMOCK_PP_INTERNAL_ALTERNATE_HEAD_CAT(_1, _2) \
GMOCK_PP_INTERNAL_ALTERNATE_HEAD_CAT_I(_1, _2)
#define GMOCK_PP_INTERNAL_ALTERNATE_HEAD_CAT_I(_1, _2) _1##_2
#else // GMOCK_PP_INTERNAL_USE_MSVC
#define GMOCK_PP_INTERNAL_ALTERNATE_HEAD(...) GMOCK_PP_HEAD(__VA_ARGS__)
#endif // GMOCK_PP_INTERNAL_USE_MSVC
#define GMOCK_PP_INTERNAL_IBP_IS_VARIADIC_C(...) 1 _
#define GMOCK_PP_INTERNAL_IBP_IS_VARIADIC_R_1 1,
#define GMOCK_PP_INTERNAL_IBP_IS_VARIADIC_R_GMOCK_PP_INTERNAL_IBP_IS_VARIADIC_C \
0,
#define GMOCK_PP_INTERNAL_REMOVE_PARENS(...) __VA_ARGS__
#define GMOCK_PP_INTERNAL_INC_0 1
#define GMOCK_PP_INTERNAL_INC_1 2
#define GMOCK_PP_INTERNAL_INC_2 3
#define GMOCK_PP_INTERNAL_INC_3 4
#define GMOCK_PP_INTERNAL_INC_4 5
#define GMOCK_PP_INTERNAL_INC_5 6
#define GMOCK_PP_INTERNAL_INC_6 7
#define GMOCK_PP_INTERNAL_INC_7 8
#define GMOCK_PP_INTERNAL_INC_8 9
#define GMOCK_PP_INTERNAL_INC_9 10
#define GMOCK_PP_INTERNAL_INC_10 11
#define GMOCK_PP_INTERNAL_INC_11 12
#define GMOCK_PP_INTERNAL_INC_12 13
#define GMOCK_PP_INTERNAL_INC_13 14
#define GMOCK_PP_INTERNAL_INC_14 15
#define GMOCK_PP_INTERNAL_INC_15 16
#define GMOCK_PP_INTERNAL_COMMA_IF_0
#define GMOCK_PP_INTERNAL_COMMA_IF_1 ,
#define GMOCK_PP_INTERNAL_COMMA_IF_2 ,
#define GMOCK_PP_INTERNAL_COMMA_IF_3 ,
#define GMOCK_PP_INTERNAL_COMMA_IF_4 ,
#define GMOCK_PP_INTERNAL_COMMA_IF_5 ,
#define GMOCK_PP_INTERNAL_COMMA_IF_6 ,
#define GMOCK_PP_INTERNAL_COMMA_IF_7 ,
#define GMOCK_PP_INTERNAL_COMMA_IF_8 ,
#define GMOCK_PP_INTERNAL_COMMA_IF_9 ,
#define GMOCK_PP_INTERNAL_COMMA_IF_10 ,
#define GMOCK_PP_INTERNAL_COMMA_IF_11 ,
#define GMOCK_PP_INTERNAL_COMMA_IF_12 ,
#define GMOCK_PP_INTERNAL_COMMA_IF_13 ,
#define GMOCK_PP_INTERNAL_COMMA_IF_14 ,
#define GMOCK_PP_INTERNAL_COMMA_IF_15 ,
#define GMOCK_PP_INTERNAL_CALL_MACRO(_Macro, _i, _Data, _element) \
_Macro(_i, _Data, _element)
#define GMOCK_PP_INTERNAL_FOR_EACH_IMPL_0(_i, _Macro, _Data, _Tuple)
#define GMOCK_PP_INTERNAL_FOR_EACH_IMPL_1(_i, _Macro, _Data, _Tuple) \
GMOCK_PP_INTERNAL_CALL_MACRO(_Macro, _i, _Data, GMOCK_PP_HEAD _Tuple)
#define GMOCK_PP_INTERNAL_FOR_EACH_IMPL_2(_i, _Macro, _Data, _Tuple) \
GMOCK_PP_INTERNAL_CALL_MACRO(_Macro, _i, _Data, GMOCK_PP_HEAD _Tuple) \
GMOCK_PP_INTERNAL_FOR_EACH_IMPL_1(GMOCK_PP_INC(_i), _Macro, _Data, \
(GMOCK_PP_TAIL _Tuple))
#define GMOCK_PP_INTERNAL_FOR_EACH_IMPL_3(_i, _Macro, _Data, _Tuple) \
GMOCK_PP_INTERNAL_CALL_MACRO(_Macro, _i, _Data, GMOCK_PP_HEAD _Tuple) \
GMOCK_PP_INTERNAL_FOR_EACH_IMPL_2(GMOCK_PP_INC(_i), _Macro, _Data, \
(GMOCK_PP_TAIL _Tuple))
#define GMOCK_PP_INTERNAL_FOR_EACH_IMPL_4(_i, _Macro, _Data, _Tuple) \
GMOCK_PP_INTERNAL_CALL_MACRO(_Macro, _i, _Data, GMOCK_PP_HEAD _Tuple) \
GMOCK_PP_INTERNAL_FOR_EACH_IMPL_3(GMOCK_PP_INC(_i), _Macro, _Data, \
(GMOCK_PP_TAIL _Tuple))
#define GMOCK_PP_INTERNAL_FOR_EACH_IMPL_5(_i, _Macro, _Data, _Tuple) \
GMOCK_PP_INTERNAL_CALL_MACRO(_Macro, _i, _Data, GMOCK_PP_HEAD _Tuple) \
GMOCK_PP_INTERNAL_FOR_EACH_IMPL_4(GMOCK_PP_INC(_i), _Macro, _Data, \
(GMOCK_PP_TAIL _Tuple))
#define GMOCK_PP_INTERNAL_FOR_EACH_IMPL_6(_i, _Macro, _Data, _Tuple) \
GMOCK_PP_INTERNAL_CALL_MACRO(_Macro, _i, _Data, GMOCK_PP_HEAD _Tuple) \
GMOCK_PP_INTERNAL_FOR_EACH_IMPL_5(GMOCK_PP_INC(_i), _Macro, _Data, \
(GMOCK_PP_TAIL _Tuple))
#define GMOCK_PP_INTERNAL_FOR_EACH_IMPL_7(_i, _Macro, _Data, _Tuple) \
GMOCK_PP_INTERNAL_CALL_MACRO(_Macro, _i, _Data, GMOCK_PP_HEAD _Tuple) \
GMOCK_PP_INTERNAL_FOR_EACH_IMPL_6(GMOCK_PP_INC(_i), _Macro, _Data, \
(GMOCK_PP_TAIL _Tuple))
#define GMOCK_PP_INTERNAL_FOR_EACH_IMPL_8(_i, _Macro, _Data, _Tuple) \
GMOCK_PP_INTERNAL_CALL_MACRO(_Macro, _i, _Data, GMOCK_PP_HEAD _Tuple) \
GMOCK_PP_INTERNAL_FOR_EACH_IMPL_7(GMOCK_PP_INC(_i), _Macro, _Data, \
(GMOCK_PP_TAIL _Tuple))
#define GMOCK_PP_INTERNAL_FOR_EACH_IMPL_9(_i, _Macro, _Data, _Tuple) \
GMOCK_PP_INTERNAL_CALL_MACRO(_Macro, _i, _Data, GMOCK_PP_HEAD _Tuple) \
GMOCK_PP_INTERNAL_FOR_EACH_IMPL_8(GMOCK_PP_INC(_i), _Macro, _Data, \
(GMOCK_PP_TAIL _Tuple))
#define GMOCK_PP_INTERNAL_FOR_EACH_IMPL_10(_i, _Macro, _Data, _Tuple) \
GMOCK_PP_INTERNAL_CALL_MACRO(_Macro, _i, _Data, GMOCK_PP_HEAD _Tuple) \
GMOCK_PP_INTERNAL_FOR_EACH_IMPL_9(GMOCK_PP_INC(_i), _Macro, _Data, \
(GMOCK_PP_TAIL _Tuple))
#define GMOCK_PP_INTERNAL_FOR_EACH_IMPL_11(_i, _Macro, _Data, _Tuple) \
GMOCK_PP_INTERNAL_CALL_MACRO(_Macro, _i, _Data, GMOCK_PP_HEAD _Tuple) \
GMOCK_PP_INTERNAL_FOR_EACH_IMPL_10(GMOCK_PP_INC(_i), _Macro, _Data, \
(GMOCK_PP_TAIL _Tuple))
#define GMOCK_PP_INTERNAL_FOR_EACH_IMPL_12(_i, _Macro, _Data, _Tuple) \
GMOCK_PP_INTERNAL_CALL_MACRO(_Macro, _i, _Data, GMOCK_PP_HEAD _Tuple) \
GMOCK_PP_INTERNAL_FOR_EACH_IMPL_11(GMOCK_PP_INC(_i), _Macro, _Data, \
(GMOCK_PP_TAIL _Tuple))
#define GMOCK_PP_INTERNAL_FOR_EACH_IMPL_13(_i, _Macro, _Data, _Tuple) \
GMOCK_PP_INTERNAL_CALL_MACRO(_Macro, _i, _Data, GMOCK_PP_HEAD _Tuple) \
GMOCK_PP_INTERNAL_FOR_EACH_IMPL_12(GMOCK_PP_INC(_i), _Macro, _Data, \
(GMOCK_PP_TAIL _Tuple))
#define GMOCK_PP_INTERNAL_FOR_EACH_IMPL_14(_i, _Macro, _Data, _Tuple) \
GMOCK_PP_INTERNAL_CALL_MACRO(_Macro, _i, _Data, GMOCK_PP_HEAD _Tuple) \
GMOCK_PP_INTERNAL_FOR_EACH_IMPL_13(GMOCK_PP_INC(_i), _Macro, _Data, \
(GMOCK_PP_TAIL _Tuple))
#define GMOCK_PP_INTERNAL_FOR_EACH_IMPL_15(_i, _Macro, _Data, _Tuple) \
GMOCK_PP_INTERNAL_CALL_MACRO(_Macro, _i, _Data, GMOCK_PP_HEAD _Tuple) \
GMOCK_PP_INTERNAL_FOR_EACH_IMPL_14(GMOCK_PP_INC(_i), _Macro, _Data, \
(GMOCK_PP_TAIL _Tuple))
#endif // THIRD_PARTY_GOOGLETEST_GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_PP_H_

View File

@ -1,101 +0,0 @@
# A sample Makefile for building both Google Mock and Google Test and
# using them in user tests. This file is self-contained, so you don't
# need to use the Makefile in Google Test's source tree. Please tweak
# it to suit your environment and project. You may want to move it to
# your project's root directory.
#
# SYNOPSIS:
#
# make [all] - makes everything.
# make TARGET - makes the given target.
# make clean - removes all files generated by make.
# Please tweak the following variable definitions as needed by your
# project, except GMOCK_HEADERS and GTEST_HEADERS, which you can use
# in your own targets but shouldn't modify.
# Points to the root of Google Test, relative to where this file is.
# Remember to tweak this if you move this file, or if you want to use
# a copy of Google Test at a different location.
GTEST_DIR = ../../googletest
# Points to the root of Google Mock, relative to where this file is.
# Remember to tweak this if you move this file.
GMOCK_DIR = ..
# Where to find user code.
USER_DIR = ../test
# Flags passed to the preprocessor.
# Set Google Test and Google Mock's header directories as system
# directories, such that the compiler doesn't generate warnings in
# these headers.
CPPFLAGS += -isystem $(GTEST_DIR)/include -isystem $(GMOCK_DIR)/include
# Flags passed to the C++ compiler.
CXXFLAGS += -g -Wall -Wextra -pthread
# All tests produced by this Makefile. Remember to add new tests you
# created to the list.
TESTS = gmock_test
# All Google Test headers. Usually you shouldn't change this
# definition.
GTEST_HEADERS = $(GTEST_DIR)/include/gtest/*.h \
$(GTEST_DIR)/include/gtest/internal/*.h
# All Google Mock headers. Note that all Google Test headers are
# included here too, as they are #included by Google Mock headers.
# Usually you shouldn't change this definition.
GMOCK_HEADERS = $(GMOCK_DIR)/include/gmock/*.h \
$(GMOCK_DIR)/include/gmock/internal/*.h \
$(GTEST_HEADERS)
# House-keeping build targets.
all : $(TESTS)
clean :
rm -f $(TESTS) gmock.a gmock_main.a *.o
# Builds gmock.a and gmock_main.a. These libraries contain both
# Google Mock and Google Test. A test should link with either gmock.a
# or gmock_main.a, depending on whether it defines its own main()
# function. It's fine if your test only uses features from Google
# Test (and not Google Mock).
# Usually you shouldn't tweak such internal variables, indicated by a
# trailing _.
GTEST_SRCS_ = $(GTEST_DIR)/src/*.cc $(GTEST_DIR)/src/*.h $(GTEST_HEADERS)
GMOCK_SRCS_ = $(GMOCK_DIR)/src/*.cc $(GMOCK_HEADERS)
# For simplicity and to avoid depending on implementation details of
# Google Mock and Google Test, the dependencies specified below are
# conservative and not optimized. This is fine as Google Mock and
# Google Test compile fast and for ordinary users their source rarely
# changes.
gtest-all.o : $(GTEST_SRCS_)
$(CXX) $(CPPFLAGS) -I$(GTEST_DIR) -I$(GMOCK_DIR) $(CXXFLAGS) \
-c $(GTEST_DIR)/src/gtest-all.cc
gmock-all.o : $(GMOCK_SRCS_)
$(CXX) $(CPPFLAGS) -I$(GTEST_DIR) -I$(GMOCK_DIR) $(CXXFLAGS) \
-c $(GMOCK_DIR)/src/gmock-all.cc
gmock_main.o : $(GMOCK_SRCS_)
$(CXX) $(CPPFLAGS) -I$(GTEST_DIR) -I$(GMOCK_DIR) $(CXXFLAGS) \
-c $(GMOCK_DIR)/src/gmock_main.cc
gmock.a : gmock-all.o gtest-all.o
$(AR) $(ARFLAGS) $@ $^
gmock_main.a : gmock-all.o gtest-all.o gmock_main.o
$(AR) $(ARFLAGS) $@ $^
# Builds a sample test.
gmock_test.o : $(USER_DIR)/gmock_test.cc $(GMOCK_HEADERS)
$(CXX) $(CPPFLAGS) $(CXXFLAGS) -c $(USER_DIR)/gmock_test.cc
gmock_test : gmock_test.o gmock_main.a
$(CXX) $(CPPFLAGS) $(CXXFLAGS) -lpthread $^ -o $@

View File

@ -1,32 +0,0 @@

Microsoft Visual Studio Solution File, Format Version 9.00
# Visual Studio 2005
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "gmock", "gmock.vcproj", "{34681F0D-CE45-415D-B5F2-5C662DFE3BD5}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "gmock_test", "gmock_test.vcproj", "{F10D22F8-AC7B-4213-8720-608E7D878CD2}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "gmock_main", "gmock_main.vcproj", "{E4EF614B-30DF-4954-8C53-580A0BF6B589}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Win32 = Debug|Win32
Release|Win32 = Release|Win32
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}.Release|Win32.ActiveCfg = Release|Win32
{34681F0D-CE45-415D-B5F2-5C662DFE3BD5}.Release|Win32.Build.0 = Release|Win32
{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}.Release|Win32.ActiveCfg = Release|Win32
{F10D22F8-AC7B-4213-8720-608E7D878CD2}.Release|Win32.Build.0 = Release|Win32
{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}.Release|Win32.ActiveCfg = Release|Win32
{E4EF614B-30DF-4954-8C53-580A0BF6B589}.Release|Win32.Build.0 = Release|Win32
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal

View File

@ -1,191 +0,0 @@
<?xml version="1.0" encoding="Windows-1252"?>
<VisualStudioProject
ProjectType="Visual C++"
Version="8.00"
Name="gmock"
ProjectGUID="{34681F0D-CE45-415D-B5F2-5C662DFE3BD5}"
RootNamespace="gmock"
Keyword="Win32Proj"
>
<Platforms>
<Platform
Name="Win32"
/>
</Platforms>
<ToolFiles>
</ToolFiles>
<Configurations>
<Configuration
Name="Debug|Win32"
OutputDirectory="$(SolutionDir)$(ConfigurationName)"
IntermediateDirectory="$(OutDir)\$(ProjectName)"
ConfigurationType="4"
InheritedPropertySheets=".\gmock_config.vsprops"
CharacterSet="1"
>
<Tool
Name="VCPreBuildEventTool"
/>
<Tool
Name="VCCustomBuildTool"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCWebServiceProxyGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
/>
<Tool
Name="VCCLCompilerTool"
Optimization="0"
AdditionalIncludeDirectories="..\..\include;..\.."
PreprocessorDefinitions="WIN32;_DEBUG;_LIB"
MinimalRebuild="true"
BasicRuntimeChecks="3"
RuntimeLibrary="1"
UsePrecompiledHeader="0"
WarningLevel="3"
Detect64BitPortabilityProblems="true"
DebugInformationFormat="3"
/>
<Tool
Name="VCManagedResourceCompilerTool"
/>
<Tool
Name="VCResourceCompilerTool"
/>
<Tool
Name="VCPreLinkEventTool"
/>
<Tool
Name="VCLibrarianTool"
/>
<Tool
Name="VCALinkTool"
/>
<Tool
Name="VCXDCMakeTool"
/>
<Tool
Name="VCBscMakeTool"
/>
<Tool
Name="VCFxCopTool"
/>
<Tool
Name="VCPostBuildEventTool"
/>
</Configuration>
<Configuration
Name="Release|Win32"
OutputDirectory="$(SolutionDir)$(ConfigurationName)"
IntermediateDirectory="$(OutDir)\$(ProjectName)"
ConfigurationType="4"
InheritedPropertySheets=".\gmock_config.vsprops"
CharacterSet="1"
WholeProgramOptimization="1"
>
<Tool
Name="VCPreBuildEventTool"
/>
<Tool
Name="VCCustomBuildTool"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCWebServiceProxyGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
/>
<Tool
Name="VCCLCompilerTool"
AdditionalIncludeDirectories="..\..\include;..\.."
PreprocessorDefinitions="WIN32;NDEBUG;_LIB"
RuntimeLibrary="0"
UsePrecompiledHeader="0"
WarningLevel="3"
Detect64BitPortabilityProblems="true"
DebugInformationFormat="3"
/>
<Tool
Name="VCManagedResourceCompilerTool"
/>
<Tool
Name="VCResourceCompilerTool"
/>
<Tool
Name="VCPreLinkEventTool"
/>
<Tool
Name="VCLibrarianTool"
/>
<Tool
Name="VCALinkTool"
/>
<Tool
Name="VCXDCMakeTool"
/>
<Tool
Name="VCBscMakeTool"
/>
<Tool
Name="VCFxCopTool"
/>
<Tool
Name="VCPostBuildEventTool"
/>
</Configuration>
</Configurations>
<References>
</References>
<Files>
<Filter
Name="Source Files"
Filter="cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx"
UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}"
>
<File
RelativePath="..\..\src\gmock-all.cc"
>
</File>
<File
RelativePath="$(GTestDir)\src\gtest-all.cc"
>
<FileConfiguration
Name="Debug|Win32"
>
<Tool
Name="VCCLCompilerTool"
AdditionalIncludeDirectories="$(GTestDir)"
/>
</FileConfiguration>
<FileConfiguration
Name="Release|Win32"
>
<Tool
Name="VCCLCompilerTool"
AdditionalIncludeDirectories="$(GTestDir)"
/>
</FileConfiguration>
</File>
</Filter>
<Filter
Name="Public Header Files"
Filter="h;hpp;hxx;hm;inl;inc;xsd"
UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}"
>
</Filter>
<Filter
Name="Private Header Files"
>
</Filter>
</Files>
<Globals>
</Globals>
</VisualStudioProject>

View File

@ -1,15 +0,0 @@
<?xml version="1.0" encoding="Windows-1252"?>
<VisualStudioPropertySheet
ProjectType="Visual C++"
Version="8.00"
Name="gmock_config"
>
<Tool
Name="VCCLCompilerTool"
AdditionalIncludeDirectories="&quot;$(GTestDir)/include&quot;"
/>
<UserMacro
Name="GTestDir"
Value="../../../googletest"
/>
</VisualStudioPropertySheet>

View File

@ -1,187 +0,0 @@
<?xml version="1.0" encoding="Windows-1252"?>
<VisualStudioProject
ProjectType="Visual C++"
Version="8.00"
Name="gmock_main"
ProjectGUID="{E4EF614B-30DF-4954-8C53-580A0BF6B589}"
RootNamespace="gmock_main"
Keyword="Win32Proj"
>
<Platforms>
<Platform
Name="Win32"
/>
</Platforms>
<ToolFiles>
</ToolFiles>
<Configurations>
<Configuration
Name="Debug|Win32"
OutputDirectory="$(SolutionDir)$(ConfigurationName)"
IntermediateDirectory="$(OutDir)\$(ProjectName)"
ConfigurationType="4"
InheritedPropertySheets=".\gmock_config.vsprops"
CharacterSet="1"
>
<Tool
Name="VCPreBuildEventTool"
/>
<Tool
Name="VCCustomBuildTool"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCWebServiceProxyGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
/>
<Tool
Name="VCCLCompilerTool"
Optimization="0"
AdditionalIncludeDirectories="../../include"
PreprocessorDefinitions="WIN32;_DEBUG;_LIB"
MinimalRebuild="true"
BasicRuntimeChecks="3"
RuntimeLibrary="1"
UsePrecompiledHeader="0"
WarningLevel="3"
Detect64BitPortabilityProblems="true"
DebugInformationFormat="3"
/>
<Tool
Name="VCManagedResourceCompilerTool"
/>
<Tool
Name="VCResourceCompilerTool"
/>
<Tool
Name="VCPreLinkEventTool"
/>
<Tool
Name="VCLibrarianTool"
/>
<Tool
Name="VCALinkTool"
/>
<Tool
Name="VCXDCMakeTool"
/>
<Tool
Name="VCBscMakeTool"
/>
<Tool
Name="VCFxCopTool"
/>
<Tool
Name="VCPostBuildEventTool"
/>
</Configuration>
<Configuration
Name="Release|Win32"
OutputDirectory="$(SolutionDir)$(ConfigurationName)"
IntermediateDirectory="$(OutDir)\$(ProjectName)"
ConfigurationType="4"
InheritedPropertySheets=".\gmock_config.vsprops"
CharacterSet="1"
WholeProgramOptimization="1"
>
<Tool
Name="VCPreBuildEventTool"
/>
<Tool
Name="VCCustomBuildTool"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCWebServiceProxyGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
/>
<Tool
Name="VCCLCompilerTool"
AdditionalIncludeDirectories="../../include"
PreprocessorDefinitions="WIN32;NDEBUG;_LIB"
RuntimeLibrary="0"
UsePrecompiledHeader="0"
WarningLevel="3"
Detect64BitPortabilityProblems="true"
DebugInformationFormat="3"
/>
<Tool
Name="VCManagedResourceCompilerTool"
/>
<Tool
Name="VCResourceCompilerTool"
/>
<Tool
Name="VCPreLinkEventTool"
/>
<Tool
Name="VCLibrarianTool"
/>
<Tool
Name="VCALinkTool"
/>
<Tool
Name="VCXDCMakeTool"
/>
<Tool
Name="VCBscMakeTool"
/>
<Tool
Name="VCFxCopTool"
/>
<Tool
Name="VCPostBuildEventTool"
/>
</Configuration>
</Configurations>
<References>
<ProjectReference
ReferencedProjectIdentifier="{34681F0D-CE45-415D-B5F2-5C662DFE3BD5}"
RelativePathToProject=".\gmock.vcproj"
/>
</References>
<Files>
<Filter
Name="Source Files"
Filter="cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx"
UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}"
>
<File
RelativePath="..\..\src\gmock_main.cc"
>
<FileConfiguration
Name="Debug|Win32"
>
<Tool
Name="VCCLCompilerTool"
AdditionalIncludeDirectories="../../include"
/>
</FileConfiguration>
<FileConfiguration
Name="Release|Win32"
>
<Tool
Name="VCCLCompilerTool"
AdditionalIncludeDirectories="../../include"
/>
</FileConfiguration>
</File>
</Filter>
<Filter
Name="Header Files"
Filter="h;hpp;hxx;hm;inl;inc;xsd"
UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}"
>
</Filter>
</Files>
<Globals>
</Globals>
</VisualStudioProject>

View File

@ -1,201 +0,0 @@
<?xml version="1.0" encoding="Windows-1252"?>
<VisualStudioProject
ProjectType="Visual C++"
Version="8.00"
Name="gmock_test"
ProjectGUID="{F10D22F8-AC7B-4213-8720-608E7D878CD2}"
RootNamespace="gmock_test"
Keyword="Win32Proj"
>
<Platforms>
<Platform
Name="Win32"
/>
</Platforms>
<ToolFiles>
</ToolFiles>
<Configurations>
<Configuration
Name="Debug|Win32"
OutputDirectory="$(SolutionDir)$(ConfigurationName)"
IntermediateDirectory="$(OutDir)\$(ProjectName)"
ConfigurationType="1"
InheritedPropertySheets=".\gmock_config.vsprops"
CharacterSet="1"
>
<Tool
Name="VCPreBuildEventTool"
/>
<Tool
Name="VCCustomBuildTool"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCWebServiceProxyGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
/>
<Tool
Name="VCCLCompilerTool"
AdditionalOptions="/bigobj"
Optimization="0"
AdditionalIncludeDirectories="..\..\include;..\.."
PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE"
MinimalRebuild="true"
BasicRuntimeChecks="3"
RuntimeLibrary="1"
UsePrecompiledHeader="0"
WarningLevel="3"
Detect64BitPortabilityProblems="true"
DebugInformationFormat="3"
/>
<Tool
Name="VCManagedResourceCompilerTool"
/>
<Tool
Name="VCResourceCompilerTool"
/>
<Tool
Name="VCPreLinkEventTool"
/>
<Tool
Name="VCLinkerTool"
LinkIncremental="2"
GenerateDebugInformation="true"
SubSystem="1"
TargetMachine="1"
/>
<Tool
Name="VCALinkTool"
/>
<Tool
Name="VCManifestTool"
/>
<Tool
Name="VCXDCMakeTool"
/>
<Tool
Name="VCBscMakeTool"
/>
<Tool
Name="VCFxCopTool"
/>
<Tool
Name="VCAppVerifierTool"
/>
<Tool
Name="VCWebDeploymentTool"
/>
<Tool
Name="VCPostBuildEventTool"
/>
</Configuration>
<Configuration
Name="Release|Win32"
OutputDirectory="$(SolutionDir)$(ConfigurationName)"
IntermediateDirectory="$(OutDir)\$(ProjectName)"
ConfigurationType="1"
InheritedPropertySheets=".\gmock_config.vsprops"
CharacterSet="1"
WholeProgramOptimization="1"
>
<Tool
Name="VCPreBuildEventTool"
/>
<Tool
Name="VCCustomBuildTool"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCWebServiceProxyGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
/>
<Tool
Name="VCCLCompilerTool"
AdditionalOptions="/bigobj"
AdditionalIncludeDirectories="..\..\include;..\.."
PreprocessorDefinitions="WIN32;NDEBUG;_CONSOLE"
RuntimeLibrary="0"
UsePrecompiledHeader="0"
WarningLevel="3"
Detect64BitPortabilityProblems="true"
DebugInformationFormat="3"
/>
<Tool
Name="VCManagedResourceCompilerTool"
/>
<Tool
Name="VCResourceCompilerTool"
/>
<Tool
Name="VCPreLinkEventTool"
/>
<Tool
Name="VCLinkerTool"
LinkIncremental="1"
GenerateDebugInformation="true"
SubSystem="1"
OptimizeReferences="2"
EnableCOMDATFolding="2"
TargetMachine="1"
/>
<Tool
Name="VCALinkTool"
/>
<Tool
Name="VCManifestTool"
/>
<Tool
Name="VCXDCMakeTool"
/>
<Tool
Name="VCBscMakeTool"
/>
<Tool
Name="VCFxCopTool"
/>
<Tool
Name="VCAppVerifierTool"
/>
<Tool
Name="VCWebDeploymentTool"
/>
<Tool
Name="VCPostBuildEventTool"
/>
</Configuration>
</Configurations>
<References>
<ProjectReference
ReferencedProjectIdentifier="{E4EF614B-30DF-4954-8C53-580A0BF6B589}"
RelativePathToProject=".\gmock_main.vcproj"
/>
</References>
<Files>
<Filter
Name="Source Files"
Filter="cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx"
UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}"
>
<File
RelativePath="..\..\test\gmock_all_test.cc"
>
</File>
</Filter>
<Filter
Name="Header Files"
Filter="h;hpp;hxx;hm;inl;inc;xsd"
UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}"
>
</Filter>
</Files>
<Globals>
</Globals>
</VisualStudioProject>

View File

@ -1,46 +0,0 @@

Microsoft Visual Studio Solution File, Format Version 11.00
# Visual C++ Express 2010
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "gmock", "gmock.vcxproj", "{34681F0D-CE45-415D-B5F2-5C662DFE3BD5}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "gmock_test", "gmock_test.vcxproj", "{F10D22F8-AC7B-4213-8720-608E7D878CD2}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "gmock_main", "gmock_main.vcxproj", "{E4EF614B-30DF-4954-8C53-580A0BF6B589}"
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
EndGlobalSection
EndGlobal

View File

@ -1,145 +0,0 @@
<?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>
<RootNamespace>gmock</RootNamespace>
<Keyword>Win32Proj</Keyword>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<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">
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|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)'=='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)$(Platform)-$(Configuration)\</OutDir>
<IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(OutDir)$(ProjectName)\</IntDir>
<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;_VARIADIC_MAX=10;_DEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<MinimalRebuild>true</MinimalRebuild>
<BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
<PrecompiledHeader>
</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<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;_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>
<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" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>

View File

@ -1,19 +0,0 @@
<?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>
</PropertyGroup>
<PropertyGroup>
<_ProjectFileVersion>10.0.30319.1</_ProjectFileVersion>
</PropertyGroup>
<ItemDefinitionGroup>
<ClCompile>
<AdditionalIncludeDirectories>$(GTestDir)/include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
</ClCompile>
</ItemDefinitionGroup>
<ItemGroup>
<BuildMacro Include="GTestDir">
<Value>$(GTestDir)</Value>
</BuildMacro>
</ItemGroup>
</Project>

View File

@ -1,151 +0,0 @@
<?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>
<RootNamespace>gmock_main</RootNamespace>
<Keyword>Win32Proj</Keyword>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<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">
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|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)'=='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)$(Platform)-$(Configuration)\</OutDir>
<IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(OutDir)$(ProjectName)\</IntDir>
<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;_VARIADIC_MAX=10;_DEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<MinimalRebuild>true</MinimalRebuild>
<BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
<PrecompiledHeader>
</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<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;_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>
<WarningLevel>Level3</WarningLevel>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
</ClCompile>
</ItemDefinitionGroup>
<ItemGroup>
<ProjectReference Include="gmock.vcxproj">
<Project>{34681f0d-ce45-415d-b5f2-5c662dfe3bd5}</Project>
<CopyLocalSatelliteAssemblies>true</CopyLocalSatelliteAssemblies>
<ReferenceOutputAssembly>true</ReferenceOutputAssembly>
</ProjectReference>
</ItemGroup>
<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>

View File

@ -1,176 +0,0 @@
<?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>
<RootNamespace>gmock_test</RootNamespace>
<Keyword>Win32Proj</Keyword>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<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">
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|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)'=='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)$(Platform)-$(Configuration)\</OutDir>
<IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(OutDir)$(ProjectName)\</IntDir>
<LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</LinkIncremental>
<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;..\..;$(GTestDir);%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;_VARIADIC_MAX=10;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<MinimalRebuild>true</MinimalRebuild>
<BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
<PrecompiledHeader>
</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
</ClCompile>
<Link>
<GenerateDebugInformation>true</GenerateDebugInformation>
<SubSystem>Console</SubSystem>
<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;..\..;$(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>
<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>
<CopyLocalSatelliteAssemblies>true</CopyLocalSatelliteAssemblies>
<ReferenceOutputAssembly>true</ReferenceOutputAssembly>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<ClCompile Include="..\..\test\gmock_all_test.cc" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>

View File

@ -1,46 +0,0 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 14
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "gmock", "gmock.vcxproj", "{34681F0D-CE45-415D-B5F2-5C662DFE3BD5}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "gmock_test", "gmock_test.vcxproj", "{F10D22F8-AC7B-4213-8720-608E7D878CD2}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "gmock_main", "gmock_main.vcxproj", "{E4EF614B-30DF-4954-8C53-580A0BF6B589}"
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
EndGlobalSection
EndGlobal

View File

@ -1,145 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="14.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>
<RootNamespace>gmock</RootNamespace>
<Keyword>Win32Proj</Keyword>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>StaticLibrary</ConfigurationType>
<CharacterSet>Unicode</CharacterSet>
<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>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|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)'=='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)$(Platform)-$(Configuration)\</OutDir>
<IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(OutDir)$(ProjectName)\</IntDir>
<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>
<MinimalRebuild>true</MinimalRebuild>
<BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
<PrecompiledHeader>
</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<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>
<PreprocessorDefinitions>WIN32;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;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" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>

View File

@ -1,19 +0,0 @@
<?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>
</PropertyGroup>
<PropertyGroup>
<_ProjectFileVersion>10.0.30319.1</_ProjectFileVersion>
</PropertyGroup>
<ItemDefinitionGroup>
<ClCompile>
<AdditionalIncludeDirectories>$(GTestDir)/include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
</ClCompile>
</ItemDefinitionGroup>
<ItemGroup>
<BuildMacro Include="GTestDir">
<Value>$(GTestDir)</Value>
</BuildMacro>
</ItemGroup>
</Project>

View File

@ -1,151 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="14.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>
<RootNamespace>gmock_main</RootNamespace>
<Keyword>Win32Proj</Keyword>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>StaticLibrary</ConfigurationType>
<CharacterSet>Unicode</CharacterSet>
<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>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|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)'=='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)$(Platform)-$(Configuration)\</OutDir>
<IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(OutDir)$(ProjectName)\</IntDir>
<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>
<MinimalRebuild>true</MinimalRebuild>
<BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
<PrecompiledHeader>
</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<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>
<PreprocessorDefinitions>WIN32;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;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>
<CopyLocalSatelliteAssemblies>true</CopyLocalSatelliteAssemblies>
<ReferenceOutputAssembly>true</ReferenceOutputAssembly>
</ProjectReference>
</ItemGroup>
<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>

View File

@ -1,176 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="14.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>
<RootNamespace>gmock_test</RootNamespace>
<Keyword>Win32Proj</Keyword>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<CharacterSet>Unicode</CharacterSet>
<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>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|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)'=='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)$(Platform)-$(Configuration)\</OutDir>
<IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(OutDir)$(ProjectName)\</IntDir>
<LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</LinkIncremental>
<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;..\..;$(GTestDir);%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<MinimalRebuild>true</MinimalRebuild>
<BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
<PrecompiledHeader>
</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
</ClCompile>
<Link>
<GenerateDebugInformation>true</GenerateDebugInformation>
<SubSystem>Console</SubSystem>
<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;..\..;$(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>
<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>
<CopyLocalSatelliteAssemblies>true</CopyLocalSatelliteAssemblies>
<ReferenceOutputAssembly>true</ReferenceOutputAssembly>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<ClCompile Include="..\..\test\gmock_all_test.cc" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>

View File

@ -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
https://github.com/google/googletest/blob/master/googlemock/docs/CookBook.md for more
https://github.com/google/googletest/blob/master/googlemock/docs/cook_book.md for more
information.
"""

View File

@ -70,18 +70,18 @@ class BetweenCardinalityImpl : public CardinalityInterface {
// Conservative estimate on the lower/upper bound of the number of
// calls allowed.
virtual int ConservativeLowerBound() const { return min_; }
virtual int ConservativeUpperBound() const { return max_; }
int ConservativeLowerBound() const override { return min_; }
int ConservativeUpperBound() const override { return max_; }
virtual bool IsSatisfiedByCallCount(int call_count) const {
bool IsSatisfiedByCallCount(int call_count) const override {
return min_ <= call_count && call_count <= max_;
}
virtual bool IsSaturatedByCallCount(int call_count) const {
bool IsSaturatedByCallCount(int call_count) const override {
return call_count >= max_;
}
virtual void DescribeTo(::std::ostream* os) const;
void DescribeTo(::std::ostream* os) const override;
private:
const int min_;

View File

@ -93,8 +93,8 @@ GTEST_API_ std::string ConvertIdentifierNameToWords(const char* id_name) {
// 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 std::string& message) {
void ReportFailure(FailureType type, const char* file, int line,
const std::string& message) override {
AssertHelper(type == kFatal ?
TestPartResult::kFatalFailure :
TestPartResult::kNonFatalFailure,
@ -123,8 +123,8 @@ GTEST_API_ FailureReporterInterface* GetFailureReporter() {
// Protects global resources (stdout in particular) used by Log().
static GTEST_DEFINE_STATIC_MUTEX_(g_log_mutex);
// Returns true iff a log with the given severity is visible according
// to the --gmock_verbose flag.
// Returns true if and only if a log with the given severity is visible
// according to the --gmock_verbose flag.
GTEST_API_ bool LogIsVisible(LogSeverity severity) {
if (GMOCK_FLAG(verbose) == kInfoVerbosity) {
// Always show the log if --gmock_verbose=info.
@ -139,7 +139,7 @@ GTEST_API_ bool LogIsVisible(LogSeverity severity) {
}
}
// Prints the given message to stdout iff 'severity' >= the level
// Prints the given message to stdout if and only if 'severity' >= the level
// specified by the --gmock_verbose flag. If stack_frames_to_skip >=
// 0, also prints the stack trace excluding the top
// stack_frames_to_skip frames. In opt mode, any positive
@ -154,9 +154,6 @@ GTEST_API_ void Log(LogSeverity severity, const std::string& message,
// Ensures that logs from different threads don't interleave.
MutexLock l(&g_log_mutex);
// "using ::std::cout;" doesn't work with Symbian's STLport, where cout is a
// macro.
if (severity == kWarning) {
// Prints a GMOCK WARNING marker to make the warnings easily searchable.
std::cout << "\nGMOCK WARNING:";

View File

@ -42,116 +42,6 @@
#include <string>
namespace testing {
// Constructs a matcher that matches a const std::string& whose value is
// equal to 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 std::string& whose value is
// equal to s.
Matcher<const std::string&>::Matcher(const char* s) {
*this = Eq(std::string(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); }
#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_GLOBAL_STRING
// Constructs a matcher that matches a const ::string& whose value is
// equal to s.
Matcher<const ::string&>::Matcher(const std::string& s) {
*this = Eq(static_cast<::string>(s));
}
// Constructs a matcher that matches a const ::string& whose value is
// equal to s.
Matcher<const ::string&>::Matcher(const ::string& s) { *this = Eq(s); }
// Constructs a matcher that matches a const ::string& whose value is
// equal to s.
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 ::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);
}
#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 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));
}
// 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); }
#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*()

View File

@ -38,6 +38,7 @@
#include <stdlib.h>
#include <iostream> // NOLINT
#include <map>
#include <memory>
#include <set>
#include <string>
#include <vector>
@ -49,9 +50,9 @@
#endif
// Silence C4800 (C4800: 'int *const ': forcing value
// to bool 'true' or 'false') for MSVC 14,15
// to bool 'true' or 'false') for MSVC 15
#ifdef _MSC_VER
#if _MSC_VER <= 1900
#if _MSC_VER == 1900
# pragma warning(push)
# pragma warning(disable:4800)
#endif
@ -125,8 +126,8 @@ void ExpectationBase::RetireAllPreRequisites()
}
}
// Returns true iff all pre-requisites of this expectation have been
// satisfied.
// Returns true if and only if all pre-requisites of this expectation
// have been satisfied.
bool ExpectationBase::AllPrerequisitesAreSatisfied() const
GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
g_gmock_mutex.AssertHeld();
@ -291,17 +292,17 @@ void ReportUninterestingCall(CallReaction reaction, const std::string& msg) {
"an EXPECT_CALL() if you don't mean to enforce the call. "
"See "
"https://github.com/google/googletest/blob/master/googlemock/"
"docs/CookBook.md#"
"docs/cook_book.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() {}
@ -340,7 +341,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_;
@ -357,7 +358,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_;
@ -383,7 +384,7 @@ UntypedActionResultHolderBase* UntypedFunctionMockerBase::UntypedInvokeWith(
const CallReaction reaction =
Mock::GetReactionOnUninterestingCalls(MockObject());
// True iff we need to print this call's arguments and return
// True if and only if we need to print this call's arguments and return
// value. This definition must be kept in sync with
// the behavior of ReportUninterestingCall().
const bool need_to_report_uninteresting_call =
@ -414,8 +415,7 @@ UntypedActionResultHolderBase* UntypedFunctionMockerBase::UntypedInvokeWith(
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;
@ -425,7 +425,7 @@ UntypedActionResultHolderBase* UntypedFunctionMockerBase::UntypedInvokeWith(
::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.
@ -433,19 +433,19 @@ UntypedActionResultHolderBase* UntypedFunctionMockerBase::UntypedInvokeWith(
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.
// True if and only if we need to print the call's arguments
// and return value.
// This definition must be kept in sync with the uses of Expect()
// and Log() in this function.
const bool need_to_report_call =
!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();
@ -458,16 +458,15 @@ UntypedActionResultHolderBase* UntypedFunctionMockerBase::UntypedInvokeWith(
}
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(),
@ -568,15 +567,15 @@ 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.
const char* first_used_file;
int first_used_line;
::std::string first_used_test_case;
::std::string first_used_test_suite;
::std::string first_used_test;
bool leakable; // true iff it's OK to leak the object.
bool leakable; // true if and only if it's OK to leak the object.
FunctionMockers function_mockers; // All registered methods of the object.
};
@ -594,9 +593,6 @@ class MockObjectRegistry {
// object alive. Therefore we report any living object as test
// failure, unless the user explicitly asked us to ignore it.
~MockObjectRegistry() {
// "using ::std::cout;" doesn't work with Symbian's STLport, where cout is
// a macro.
if (!GMOCK_FLAG(catch_leaked_mocks))
return;
@ -614,8 +610,8 @@ class MockObjectRegistry {
state.first_used_line);
std::cout << " ERROR: this mock object";
if (state.first_used_test != "") {
std::cout << " (used in test " << state.first_used_test_case << "."
<< state.first_used_test << ")";
std::cout << " (used in test " << state.first_used_test_suite << "."
<< state.first_used_test << ")";
}
std::cout << " should be deleted but never is. Its address is @"
<< it->first << ".";
@ -723,7 +719,7 @@ bool Mock::VerifyAndClearExpectations(void* mock_obj)
}
// Verifies all expectations on the given mock object and clears its
// default actions and expectations. Returns true iff the
// default actions and expectations. Returns true if and only if the
// verification was successful.
bool Mock::VerifyAndClear(void* mock_obj)
GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
@ -760,6 +756,19 @@ bool Mock::VerifyAndClearExpectationsLocked(void* mock_obj)
return expectations_met;
}
bool Mock::IsNaggy(void* mock_obj)
GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
return Mock::GetReactionOnUninterestingCalls(mock_obj) == internal::kWarn;
}
bool Mock::IsNice(void* mock_obj)
GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
return Mock::GetReactionOnUninterestingCalls(mock_obj) == internal::kAllow;
}
bool Mock::IsStrict(void* mock_obj)
GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
return Mock::GetReactionOnUninterestingCalls(mock_obj) == internal::kFail;
}
// Registers a mock object and a mock method it owns.
void Mock::Register(const void* mock_obj,
internal::UntypedFunctionMockerBase* mocker)
@ -776,16 +785,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) {
// 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();
if (test_info != nullptr) {
state.first_used_test_suite = test_info->test_suite_name();
state.first_used_test = test_info->name();
}
}
@ -838,7 +844,7 @@ void Mock::ClearDefaultActionsLocked(void* mock_obj)
Expectation::Expectation() {}
Expectation::Expectation(
const internal::linked_ptr<internal::ExpectationBase>& an_expectation_base)
const std::shared_ptr<internal::ExpectationBase>& an_expectation_base)
: expectation_base_(an_expectation_base) {}
Expectation::~Expectation() {}
@ -846,7 +852,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_;
}
@ -856,7 +862,7 @@ void Sequence::AddExpectation(const Expectation& expectation) const {
// Creates the implicit sequence if there isn't one.
InSequence::InSequence() {
if (internal::g_gmock_implicit_sequence.get() == NULL) {
if (internal::g_gmock_implicit_sequence.get() == nullptr) {
internal::g_gmock_implicit_sequence.set(new Sequence);
sequence_created_ = true;
} else {
@ -869,14 +875,14 @@ InSequence::InSequence() {
InSequence::~InSequence() {
if (sequence_created_) {
delete internal::g_gmock_implicit_sequence.get();
internal::g_gmock_implicit_sequence.set(NULL);
internal::g_gmock_implicit_sequence.set(nullptr);
}
}
} // namespace testing
#ifdef _MSC_VER
#if _MSC_VER <= 1900
#if _MSC_VER == 1900
# pragma warning(pop)
#endif
#endif

View File

@ -33,12 +33,9 @@
namespace testing {
// FIXME: support using environment variables to
// control the flag values, like what Google Test does.
GMOCK_DEFINE_bool_(catch_leaked_mocks, true,
"true iff Google Mock should report leaked mock objects "
"as failures.");
"true if and only if Google Mock should report leaked "
"mock objects as failures.");
GMOCK_DEFINE_string_(verbose, internal::kWarningVerbosity,
"Controls how verbose Google Mock's output is."
@ -65,12 +62,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;
@ -83,7 +80,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;
@ -100,7 +97,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');
@ -119,7 +116,7 @@ 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;
@ -132,7 +129,7 @@ static bool ParseGoogleMockIntFlag(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;
// Sets *value to the value of the flag.
return ParseInt32(Message() << "The value of flag --" << flag,
@ -201,4 +198,16 @@ GTEST_API_ void InitGoogleMock(int* argc, wchar_t** argv) {
internal::InitGoogleMockImpl(argc, argv);
}
// This overloaded version can be used on Arduino/embedded platforms where
// there is no argc/argv.
GTEST_API_ void InitGoogleMock() {
// Since Arduino doesn't have a command line, fake out the argc/argv arguments
int argc = 1;
const auto arg0 = "dummy";
char* argv0 = const_cast<char*>(arg0);
char** argv = &argv0;
internal::InitGoogleMockImpl(&argc, argv);
}
} // namespace testing

View File

@ -32,6 +32,16 @@
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#ifdef ARDUINO
void setup() {
// Since Google Mock depends on Google Test, InitGoogleMock() is
// also responsible for initializing Google Test. Therefore there's
// no need for calling testing::InitGoogleTest() separately.
testing::InitGoogleMock();
}
void loop() { RUN_ALL_TESTS(); }
#else
// MS C++ compiler/linker has a bug on Windows (not on Windows CE), which
// 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
@ -52,3 +62,4 @@ GTEST_API_ int main(int argc, char** argv) {
testing::InitGoogleMock(&argc, argv);
return RUN_ALL_TESTS();
}
#endif

View File

@ -32,30 +32,24 @@
#
# Bazel Build for Google C++ Testing Framework(Google Test)-googlemock
load("@rules_cc//cc:defs.bzl", "cc_binary", "cc_test")
load("@rules_python//python:defs.bzl", "py_library", "py_test")
licenses(["notice"])
""" gmock own tests """
# Tests for GMock itself
cc_test(
name = "gmock_all_test",
size = "small",
srcs = glob(
include = [
"gmock-*.cc",
],
),
srcs = glob(include = ["gmock-*.cc"]),
linkopts = select({
"//:windows": [],
"//:windows_msvc": [],
"//conditions:default": [
"-pthread",
],
"//conditions:default": ["-pthread"],
}),
deps = ["//:gtest"],
)
# Py tests
# Python tests
py_library(
name = "gmock_test_utils",
testonly = 1,
@ -66,9 +60,7 @@ cc_binary(
name = "gmock_leak_test_",
testonly = 1,
srcs = ["gmock_leak_test_.cc"],
deps = [
"//:gtest_main",
],
deps = ["//:gtest_main"],
)
py_test(
@ -89,17 +81,13 @@ cc_test(
"gmock_link_test.cc",
"gmock_link_test.h",
],
deps = [
"//:gtest_main",
],
deps = ["//:gtest_main"],
)
cc_binary(
name = "gmock_output_test_",
srcs = ["gmock_output_test_.cc"],
deps = [
"//:gtest",
],
deps = ["//:gtest"],
)
py_test(
@ -110,6 +98,7 @@ py_test(
":gmock_output_test_",
":gmock_output_test_golden.txt",
],
python_version = "PY2",
deps = [":gmock_test_utils"],
)
@ -117,7 +106,5 @@ cc_test(
name = "gmock_test",
size = "small",
srcs = ["gmock_test.cc"],
deps = [
"//:gtest_main",
],
deps = ["//:gtest_main"],
)

View File

@ -33,9 +33,9 @@
// This file tests the built-in actions.
// Silence C4800 (C4800: 'int *const ': forcing value
// to bool 'true' or 'false') for MSVC 14,15
// to bool 'true' or 'false') for MSVC 15
#ifdef _MSC_VER
#if _MSC_VER <= 1900
#if _MSC_VER == 1900
# pragma warning(push)
# pragma warning(disable:4800)
#endif
@ -54,12 +54,14 @@
namespace {
// This list should be kept sorted.
using testing::_;
using testing::Action;
using testing::ActionInterface;
using testing::Assign;
using testing::ByMove;
using testing::ByRef;
using testing::DefaultValue;
using testing::DoAll;
using testing::DoDefault;
using testing::IgnoreResult;
using testing::Invoke;
@ -74,14 +76,10 @@ using testing::ReturnRefOfCopy;
using testing::SetArgPointee;
using testing::SetArgumentPointee;
using testing::Unused;
using testing::_;
using testing::get;
using testing::WithArgs;
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;
@ -89,9 +87,9 @@ using testing::SetErrnoAndReturn;
// 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,10 +105,6 @@ TEST(BuiltInDefaultValueTest, IsZeroForNumericTypes) {
EXPECT_EQ(0U, BuiltInDefaultValue<unsigned char>::Get());
EXPECT_EQ(0, BuiltInDefaultValue<signed char>::Get());
EXPECT_EQ(0, BuiltInDefaultValue<char>::Get());
#if GMOCK_HAS_SIGNED_WCHAR_T_
EXPECT_EQ(0U, BuiltInDefaultValue<unsigned wchar_t>::Get());
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());
@ -139,10 +133,6 @@ TEST(BuiltInDefaultValueTest, ExistsForNumericTypes) {
EXPECT_TRUE(BuiltInDefaultValue<unsigned char>::Exists());
EXPECT_TRUE(BuiltInDefaultValue<signed char>::Exists());
EXPECT_TRUE(BuiltInDefaultValue<char>::Exists());
#if GMOCK_HAS_SIGNED_WCHAR_T_
EXPECT_TRUE(BuiltInDefaultValue<unsigned wchar_t>::Exists());
EXPECT_TRUE(BuiltInDefaultValue<signed wchar_t>::Exists());
#endif
#if GMOCK_WCHAR_T_IS_NATIVE_
EXPECT_TRUE(BuiltInDefaultValue<wchar_t>::Exists());
#endif
@ -174,20 +164,12 @@ TEST(BuiltInDefaultValueTest, BoolExists) {
// Tests that BuiltInDefaultValue<T>::Get() returns "" when T is a
// string type.
TEST(BuiltInDefaultValueTest, IsEmptyStringForString) {
#if GTEST_HAS_GLOBAL_STRING
EXPECT_EQ("", BuiltInDefaultValue< ::string>::Get());
#endif // GTEST_HAS_GLOBAL_STRING
EXPECT_EQ("", BuiltInDefaultValue< ::std::string>::Get());
}
// Tests that BuiltInDefaultValue<T>::Exists() returns true when T is a
// string type.
TEST(BuiltInDefaultValueTest, ExistsForString) {
#if GTEST_HAS_GLOBAL_STRING
EXPECT_TRUE(BuiltInDefaultValue< ::string>::Exists());
#endif // GTEST_HAS_GLOBAL_STRING
EXPECT_TRUE(BuiltInDefaultValue< ::std::string>::Exists());
}
@ -196,7 +178,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());
}
@ -223,7 +205,6 @@ class MyNonDefaultConstructible {
int value_;
};
#if GTEST_LANG_CXX11
TEST(BuiltInDefaultValueTest, ExistsForDefaultConstructibleType) {
EXPECT_TRUE(BuiltInDefaultValue<MyDefaultConstructible>::Exists());
@ -233,7 +214,6 @@ TEST(BuiltInDefaultValueTest, IsDefaultConstructedForDefaultConstructibleType) {
EXPECT_EQ(42, BuiltInDefaultValue<MyDefaultConstructible>::Get().value());
}
#endif // GTEST_LANG_CXX11
TEST(BuiltInDefaultValueTest, DoesNotExistForNonDefaultConstructibleType) {
EXPECT_FALSE(BuiltInDefaultValue<MyNonDefaultConstructible>::Exists());
@ -303,10 +283,9 @@ 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));
});
@ -314,7 +293,6 @@ TEST(DefaultValueTest, GetWorksForMoveOnlyIfSet) {
std::unique_ptr<int> i = DefaultValue<std::unique_ptr<int>>::Get();
EXPECT_EQ(42, *i);
}
#endif // GTEST_HAS_STD_UNIQUE_PTR_
// Tests that DefaultValue<void>::Get() returns void.
TEST(DefaultValueTest, GetWorksForVoid) {
@ -382,8 +360,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;
int Perform(const std::tuple<bool, int>& args) override {
return std::get<0>(args) ? std::get<1>(args) : 0;
}
};
@ -399,8 +377,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
@ -413,8 +391,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.
@ -423,22 +401,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
@ -446,24 +424,17 @@ TEST(ActionTest, IsCopyable) {
class IsNotZero : public ActionInterface<bool(int)> { // NOLINT
public:
virtual bool Perform(const tuple<int>& arg) {
return get<0>(arg) != 0;
bool Perform(const std::tuple<int>& arg) override {
return std::get<0>(arg) != 0;
}
};
#if !GTEST_OS_SYMBIAN
// Compiling this test on Nokia's Symbian compiler fails with:
// 'Result' is not a member of class 'testing::internal::Function<int>'
// (point of instantiation: '@unnamed@gmock_actions_test_cc@::
// ActionTest_CanBeConvertedToOtherActionType_Test::TestBody()')
// with no obvious fix.
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
// The following two classes are for testing MakePolymorphicAction().
@ -475,7 +446,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
@ -490,7 +463,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
@ -509,42 +484,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
@ -563,7 +538,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));
}
@ -581,10 +556,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
@ -615,7 +590,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.";
}
@ -636,30 +611,28 @@ 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_
// Tests that ReturnNull() returns NULL for shared_ptr and unique_ptr returning
// 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_
// Tests that ReturnRef(v) works for reference types.
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.
@ -667,10 +640,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.
@ -678,12 +651,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.
@ -691,10 +664,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.
@ -705,14 +678,12 @@ class MockClass {
MOCK_METHOD1(IntFunc, int(bool flag)); // NOLINT
MOCK_METHOD0(Foo, MyNonDefaultConstructible());
#if GTEST_HAS_STD_UNIQUE_PTR_
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:
GTEST_DISALLOW_COPY_AND_ASSIGN_(MockClass);
@ -800,33 +771,31 @@ 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);
}
#if !((GTEST_GCC_VER_ && GTEST_GCC_VER_ < 40000) || GTEST_OS_SYMBIAN)
// Tests that SetArgPointee<N>() accepts a string literal.
// GCC prior to v4.0 and the Symbian compiler do not support this.
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);
}
@ -834,8 +803,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
@ -843,12 +812,11 @@ 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
}
#endif
// Tests that SetArgPointee<N>() accepts a char pointer.
TEST(SetArgPointeeTest, AcceptsCharPointer) {
@ -856,16 +824,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);
}
@ -874,8 +842,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
@ -885,7 +853,7 @@ 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
}
@ -898,14 +866,14 @@ 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);
}
@ -926,6 +894,21 @@ class VoidNullaryFunctor {
void operator()() { g_done = true; }
};
short Short(short n) { return n; } // NOLINT
char Char(char ch) { return ch; }
const char* CharPtr(const char* s) { return s; }
bool Unary(int x) { return x < 0; }
const char* Binary(const char* input, short n) { return input + n; } // NOLINT
void VoidBinary(int, char) { g_done = true; }
int Ternary(int x, char y, short z) { return x + y + z; } // NOLINT
int SumOf4(int a, int b, int c, int d) { return a + b + c + d; }
class Foo {
public:
Foo() : value_(123) {}
@ -940,16 +923,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);
}
@ -957,17 +940,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);
}
@ -976,13 +959,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.
@ -995,7 +978,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);
}
@ -1010,55 +993,155 @@ 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);
}
// 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(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.
TEST(WithArgsTest, TwoArgs) {
Action<const char*(const char* s, double x, short n)> a = // NOLINT
WithArgs<0, 2>(Invoke(Binary));
const char s[] = "Hello";
EXPECT_EQ(s + 2, a.Perform(std::make_tuple(CharPtr(s), 0.5, Short(2))));
}
struct ConcatAll {
std::string operator()() const { return {}; }
template <typename... I>
std::string operator()(const char* a, I... i) const {
return a + ConcatAll()(i...);
}
};
// Tests using WithArgs with an action that takes 10 arguments.
TEST(WithArgsTest, TenArgs) {
Action<std::string(const char*, const char*, const char*, const char*)> a =
WithArgs<0, 1, 2, 3, 2, 1, 0, 1, 2, 3>(Invoke(ConcatAll{}));
EXPECT_EQ("0123210123",
a.Perform(std::make_tuple(CharPtr("0"), CharPtr("1"), CharPtr("2"),
CharPtr("3"))));
}
// Tests using WithArgs with an action that is not Invoke().
class SubtractAction : public ActionInterface<int(int, int)> {
public:
int Perform(const std::tuple<int, int>& args) override {
return std::get<0>(args) - std::get<1>(args);
}
};
TEST(WithArgsTest, NonInvokeAction) {
Action<int(const std::string&, int, int)> a =
WithArgs<2, 1>(MakeAction(new SubtractAction));
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(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(std::make_tuple(false, 1, 10)));
}
// Tests using WithArgs with reversed argument order.
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(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(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(std::make_tuple(1.5, 'a', 3));
EXPECT_TRUE(g_done);
}
TEST(WithArgsTest, ReturnReference) {
Action<int&(int&, void*)> aa = WithArgs<0>([](int& a) -> int& { return a; });
int i = 0;
const int& res = aa.Perform(std::forward_as_tuple(i, nullptr));
EXPECT_EQ(&i, &res);
}
TEST(WithArgsTest, InnerActionWithConversion) {
Action<Derived*()> inner = [] { return nullptr; };
Action<Base*(double)> a = testing::WithoutArgs(inner);
EXPECT_EQ(nullptr, a.Perform(std::make_tuple(1.1)));
}
#if !GTEST_OS_WINDOWS_MOBILE
class SetErrnoAndReturnTest : public testing::Test {
protected:
virtual void SetUp() { errno = 0; }
virtual void TearDown() { errno = 0; }
void SetUp() override { errno = 0; }
void TearDown() override { errno = 0; }
};
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);
}
@ -1066,13 +1149,12 @@ TEST_F(SetErrnoAndReturnTest, CompatibleTypes) {
// Tests ByRef().
// Tests that ReferenceWrapper<T> is copyable.
// Tests that the result of ByRef() is copyable.
TEST(ByRefTest, IsCopyable) {
const std::string s1 = "Hi";
const std::string s2 = "Hello";
::testing::internal::ReferenceWrapper<const std::string> ref_wrapper =
ByRef(s1);
auto ref_wrapper = ByRef(s1);
const std::string& r1 = ref_wrapper;
EXPECT_EQ(&s1, &r1);
@ -1081,8 +1163,7 @@ TEST(ByRefTest, IsCopyable) {
const std::string& r2 = ref_wrapper;
EXPECT_EQ(&s2, &r2);
::testing::internal::ReferenceWrapper<const std::string> ref_wrapper1 =
ByRef(s1);
auto ref_wrapper1 = ByRef(s1);
// Copies ref_wrapper1 to ref_wrapper.
ref_wrapper = ref_wrapper1;
const std::string& r3 = ref_wrapper;
@ -1149,7 +1230,6 @@ TEST(ByRefTest, PrintsCorrectly) {
EXPECT_EQ(expected.str(), actual.str());
}
#if GTEST_HAS_STD_UNIQUE_PTR_
std::unique_ptr<int> UniquePtrSource() {
return std::unique_ptr<int>(new int(19));
@ -1262,9 +1342,7 @@ TEST(MockMethodTest, CanTakeMoveOnlyValue) {
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
@ -1298,69 +1376,64 @@ TEST(FunctorActionTest, ActionFromFunction) {
TEST(FunctorActionTest, ActionFromLambda) {
Action<int(bool, int)> a1 = [](bool b, int i) { return b ? i : 0; };
EXPECT_EQ(5, a1.Perform(make_tuple(true, 5)));
EXPECT_EQ(0, a1.Perform(make_tuple(false, 5)));
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(make_tuple(UniqueInt(5)));
a2.Perform(std::make_tuple(UniqueInt(5)));
EXPECT_EQ(5, *saved);
}
TEST(FunctorActionTest, PolymorphicFunctor) {
Action<int(int)> ai = Double();
EXPECT_EQ(2, ai.Perform(make_tuple(1)));
EXPECT_EQ(2, ai.Perform(std::make_tuple(1)));
Action<double(double)> ad = Double(); // Double? Double double!
EXPECT_EQ(3.0, ad.Perform(make_tuple(1.5)));
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(make_tuple(42)));
EXPECT_EQ(0, a2.Perform(make_tuple(42)));
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(make_tuple("")));
EXPECT_EQ(1, s2.Perform(make_tuple("hello")));
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(make_tuple("hello")));
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; };
tuple<int, double, double> dummy = make_tuple(3, 7.3, 9.44);
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(make_tuple(nullptr)));
EXPECT_EQ(1, a.Perform(std::make_tuple(nullptr)));
a = testing::WithoutArgs([]() { return 7; });
EXPECT_EQ(7, a.Perform(make_tuple(nullptr)));
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(make_tuple(nullptr, &x));
a2.Perform(std::make_tuple(nullptr, &x));
EXPECT_EQ(x, 3);
}
#endif // GTEST_LANG_CXX11
} // Unnamed namespace

View File

@ -395,18 +395,20 @@ TEST(ExactlyTest, HasCorrectBounds) {
class EvenCardinality : public CardinalityInterface {
public:
// Returns true iff call_count calls will satisfy this cardinality.
virtual bool IsSatisfiedByCallCount(int call_count) const {
// Returns true if and only if call_count calls will satisfy this
// cardinality.
bool IsSatisfiedByCallCount(int call_count) const override {
return (call_count % 2 == 0);
}
// Returns true iff call_count calls will saturate this cardinality.
virtual bool IsSaturatedByCallCount(int /* call_count */) const {
// Returns true if and only if call_count calls will saturate this
// cardinality.
bool IsSaturatedByCallCount(int /* call_count */) const override {
return false;
}
// Describes self to an ostream.
virtual void DescribeTo(::std::ostream* ss) const {
void DescribeTo(::std::ostream* ss) const override {
*ss << "called even number of times";
}
};

View File

@ -0,0 +1,16 @@
#include "gmock/gmock.h"
#include <memory>
#include <string>
#if defined(TEST_MOCK_METHOD_INVALID_CONST_SPEC)
struct Base {
MOCK_METHOD(int, F, (), (onst));
};
#else
// Sanity check - this should compile.
#endif

View File

@ -0,0 +1,43 @@
"""Negative compilation tests for Google Mock macro MOCK_METHOD."""
import os
import sys
IS_LINUX = os.name == "posix" and os.uname()[0] == "Linux"
if not IS_LINUX:
sys.stderr.write(
"WARNING: Negative compilation tests are not supported on this platform")
sys.exit(0)
# Suppresses the 'Import not at the top of the file' lint complaint.
# pylint: disable-msg=C6204
from google3.testing.pybase import fake_target_util
from google3.testing.pybase import googletest
# pylint: enable-msg=C6204
class GMockMethodNCTest(googletest.TestCase):
"""Negative compilation tests for MOCK_METHOD."""
# The class body is intentionally empty. The actual test*() methods
# will be defined at run time by a call to
# DefineNegativeCompilationTests() later.
pass
# Defines a list of test specs, where each element is a tuple
# (test name, list of regexes for matching the compiler errors).
TEST_SPECS = [
("MOCK_METHOD_INVALID_CONST_SPEC",
[r"onst cannot be recognized as a valid specification modifier"]),
]
# Define a test method in GMockNCTest for each element in TEST_SPECS.
fake_target_util.DefineNegativeCompilationTests(
GMockMethodNCTest,
"google3/third_party/googletest/googlemock/test/gmock-function-mocker_nc",
"gmock-function-mocker_nc.o", TEST_SPECS)
if __name__ == "__main__":
googletest.main()

View File

@ -0,0 +1,660 @@
// Copyright 2007, 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.
// Google Mock - a framework for writing C++ mock classes.
//
// This file tests the function mocker classes.
#include "gmock/gmock-generated-function-mockers.h"
#if GTEST_OS_WINDOWS
// MSDN says the header file to be included for STDMETHOD is BaseTyps.h but
// we are getting compiler errors if we use basetyps.h, hence including
// objbase.h for definition of STDMETHOD.
# include <objbase.h>
#endif // GTEST_OS_WINDOWS
#include <map>
#include <string>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
namespace testing {
namespace gmock_function_mocker_test {
using testing::_;
using testing::A;
using testing::An;
using testing::AnyNumber;
using testing::Const;
using testing::DoDefault;
using testing::Eq;
using testing::Lt;
using testing::MockFunction;
using testing::Ref;
using testing::Return;
using testing::ReturnRef;
using testing::TypedEq;
template<typename T>
class TemplatedCopyable {
public:
TemplatedCopyable() {}
template <typename U>
TemplatedCopyable(const U& other) {} // NOLINT
};
class FooInterface {
public:
virtual ~FooInterface() {}
virtual void VoidReturning(int x) = 0;
virtual int Nullary() = 0;
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 std::string& k) = 0;
virtual bool TakesNonConstReference(int& n) = 0; // NOLINT
virtual std::string TakesConstReference(const int& n) = 0;
virtual bool TakesConst(const int x) = 0;
virtual int OverloadedOnArgumentNumber() = 0;
virtual int OverloadedOnArgumentNumber(int n) = 0;
virtual int OverloadedOnArgumentType(int n) = 0;
virtual char OverloadedOnArgumentType(char c) = 0;
virtual int OverloadedOnConstness() = 0;
virtual char OverloadedOnConstness() const = 0;
virtual int TypeWithHole(int (*func)()) = 0;
virtual int TypeWithComma(const std::map<int, std::string>& a_map) = 0;
virtual int TypeWithTemplatedCopyCtor(const TemplatedCopyable<int>&) = 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 std::string& k) = 0;
STDMETHOD_(char, CTConst)(int x) const = 0;
#endif // GTEST_OS_WINDOWS
};
// Const qualifiers on arguments were once (incorrectly) considered
// significant in determining whether two virtual functions had the same
// signature. This was fixed in Visual Studio 2008. However, the compiler
// still emits a warning that alerts about this change in behavior.
#ifdef _MSC_VER
# pragma warning(push)
# pragma warning(disable : 4373)
#endif
class MockFoo : public FooInterface {
public:
MockFoo() {}
// Makes sure that a mock function parameter can be named.
MOCK_METHOD(void, VoidReturning, (int n)); // NOLINT
MOCK_METHOD(int, Nullary, ()); // NOLINT
// Makes sure that a mock function parameter can be unnamed.
MOCK_METHOD(bool, Unary, (int)); // NOLINT
MOCK_METHOD(long, Binary, (short, int)); // NOLINT
MOCK_METHOD(int, Decimal,
(bool, char, short, int, long, float, // NOLINT
double, unsigned, char*, const std::string& str),
(override));
MOCK_METHOD(bool, TakesNonConstReference, (int&)); // NOLINT
MOCK_METHOD(std::string, TakesConstReference, (const int&));
MOCK_METHOD(bool, TakesConst, (const int)); // NOLINT
// Tests that the function return type can contain unprotected comma.
MOCK_METHOD((std::map<int, std::string>), ReturnTypeWithComma, (), ());
MOCK_METHOD((std::map<int, std::string>), ReturnTypeWithComma, (int),
(const)); // NOLINT
MOCK_METHOD(int, OverloadedOnArgumentNumber, ()); // NOLINT
MOCK_METHOD(int, OverloadedOnArgumentNumber, (int)); // NOLINT
MOCK_METHOD(int, OverloadedOnArgumentType, (int)); // NOLINT
MOCK_METHOD(char, OverloadedOnArgumentType, (char)); // NOLINT
MOCK_METHOD(int, OverloadedOnConstness, (), (override)); // NOLINT
MOCK_METHOD(char, OverloadedOnConstness, (), (override, const)); // NOLINT
MOCK_METHOD(int, TypeWithHole, (int (*)()), ()); // NOLINT
MOCK_METHOD(int, TypeWithComma, ((const std::map<int, std::string>&)));
MOCK_METHOD(int, TypeWithTemplatedCopyCtor,
(const TemplatedCopyable<int>&)); // NOLINT
#if GTEST_OS_WINDOWS
MOCK_METHOD(int, CTNullary, (), (Calltype(STDMETHODCALLTYPE)));
MOCK_METHOD(bool, CTUnary, (int), (Calltype(STDMETHODCALLTYPE)));
MOCK_METHOD(int, CTDecimal,
(bool b, char c, short d, int e, long f, float g, double h,
unsigned i, char* j, const std::string& k),
(Calltype(STDMETHODCALLTYPE)));
MOCK_METHOD(char, CTConst, (int), (const, Calltype(STDMETHODCALLTYPE)));
MOCK_METHOD((std::map<int, std::string>), CTReturnTypeWithComma, (),
(Calltype(STDMETHODCALLTYPE)));
#endif // GTEST_OS_WINDOWS
private:
GTEST_DISALLOW_COPY_AND_ASSIGN_(MockFoo);
};
#ifdef _MSC_VER
# pragma warning(pop)
#endif
class MockMethodFunctionMockerTest : public testing::Test {
protected:
MockMethodFunctionMockerTest() : foo_(&mock_foo_) {}
FooInterface* const foo_;
MockFoo mock_foo_;
};
// Tests mocking a void-returning function.
TEST_F(MockMethodFunctionMockerTest, MocksVoidFunction) {
EXPECT_CALL(mock_foo_, VoidReturning(Lt(100)));
foo_->VoidReturning(0);
}
// Tests mocking a nullary function.
TEST_F(MockMethodFunctionMockerTest, MocksNullaryFunction) {
EXPECT_CALL(mock_foo_, Nullary())
.WillOnce(DoDefault())
.WillOnce(Return(1));
EXPECT_EQ(0, foo_->Nullary());
EXPECT_EQ(1, foo_->Nullary());
}
// Tests mocking a unary function.
TEST_F(MockMethodFunctionMockerTest, MocksUnaryFunction) {
EXPECT_CALL(mock_foo_, Unary(Eq(2)))
.Times(2)
.WillOnce(Return(true));
EXPECT_TRUE(foo_->Unary(2));
EXPECT_FALSE(foo_->Unary(2));
}
// Tests mocking a binary function.
TEST_F(MockMethodFunctionMockerTest, MocksBinaryFunction) {
EXPECT_CALL(mock_foo_, Binary(2, _))
.WillOnce(Return(3));
EXPECT_EQ(3, foo_->Binary(2, 1));
}
// Tests mocking a decimal function.
TEST_F(MockMethodFunctionMockerTest, MocksDecimalFunction) {
EXPECT_CALL(mock_foo_, Decimal(true, 'a', 0, 0, 1L, A<float>(),
Lt(100), 5U, NULL, "hi"))
.WillOnce(Return(5));
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.
TEST_F(MockMethodFunctionMockerTest,
MocksFunctionWithNonConstReferenceArgument) {
int a = 0;
EXPECT_CALL(mock_foo_, TakesNonConstReference(Ref(a)))
.WillOnce(Return(true));
EXPECT_TRUE(foo_->TakesNonConstReference(a));
}
// Tests mocking a function that takes a const reference.
TEST_F(MockMethodFunctionMockerTest, MocksFunctionWithConstReferenceArgument) {
int a = 0;
EXPECT_CALL(mock_foo_, TakesConstReference(Ref(a)))
.WillOnce(Return("Hello"));
EXPECT_EQ("Hello", foo_->TakesConstReference(a));
}
// Tests mocking a function that takes a const variable.
TEST_F(MockMethodFunctionMockerTest, MocksFunctionWithConstArgument) {
EXPECT_CALL(mock_foo_, TakesConst(Lt(10)))
.WillOnce(DoDefault());
EXPECT_FALSE(foo_->TakesConst(5));
}
// Tests mocking functions overloaded on the number of arguments.
TEST_F(MockMethodFunctionMockerTest, MocksFunctionsOverloadedOnArgumentNumber) {
EXPECT_CALL(mock_foo_, OverloadedOnArgumentNumber())
.WillOnce(Return(1));
EXPECT_CALL(mock_foo_, OverloadedOnArgumentNumber(_))
.WillOnce(Return(2));
EXPECT_EQ(2, foo_->OverloadedOnArgumentNumber(1));
EXPECT_EQ(1, foo_->OverloadedOnArgumentNumber());
}
// Tests mocking functions overloaded on the types of argument.
TEST_F(MockMethodFunctionMockerTest, MocksFunctionsOverloadedOnArgumentType) {
EXPECT_CALL(mock_foo_, OverloadedOnArgumentType(An<int>()))
.WillOnce(Return(1));
EXPECT_CALL(mock_foo_, OverloadedOnArgumentType(TypedEq<char>('a')))
.WillOnce(Return('b'));
EXPECT_EQ(1, foo_->OverloadedOnArgumentType(0));
EXPECT_EQ('b', foo_->OverloadedOnArgumentType('a'));
}
// Tests mocking functions overloaded on the const-ness of this object.
TEST_F(MockMethodFunctionMockerTest,
MocksFunctionsOverloadedOnConstnessOfThis) {
EXPECT_CALL(mock_foo_, OverloadedOnConstness());
EXPECT_CALL(Const(mock_foo_), OverloadedOnConstness())
.WillOnce(Return('a'));
EXPECT_EQ(0, foo_->OverloadedOnConstness());
EXPECT_EQ('a', Const(*foo_).OverloadedOnConstness());
}
TEST_F(MockMethodFunctionMockerTest, MocksReturnTypeWithComma) {
const std::map<int, std::string> a_map;
EXPECT_CALL(mock_foo_, ReturnTypeWithComma())
.WillOnce(Return(a_map));
EXPECT_CALL(mock_foo_, ReturnTypeWithComma(42))
.WillOnce(Return(a_map));
EXPECT_EQ(a_map, mock_foo_.ReturnTypeWithComma());
EXPECT_EQ(a_map, mock_foo_.ReturnTypeWithComma(42));
}
TEST_F(MockMethodFunctionMockerTest, MocksTypeWithTemplatedCopyCtor) {
EXPECT_CALL(mock_foo_, TypeWithTemplatedCopyCtor(_)).WillOnce(Return(true));
EXPECT_TRUE(foo_->TypeWithTemplatedCopyCtor(TemplatedCopyable<int>()));
}
#if GTEST_OS_WINDOWS
// Tests mocking a nullary function with calltype.
TEST_F(MockMethodFunctionMockerTest, MocksNullaryFunctionWithCallType) {
EXPECT_CALL(mock_foo_, CTNullary())
.WillOnce(Return(-1))
.WillOnce(Return(0));
EXPECT_EQ(-1, foo_->CTNullary());
EXPECT_EQ(0, foo_->CTNullary());
}
// Tests mocking a unary function with calltype.
TEST_F(MockMethodFunctionMockerTest, MocksUnaryFunctionWithCallType) {
EXPECT_CALL(mock_foo_, CTUnary(Eq(2)))
.Times(2)
.WillOnce(Return(true))
.WillOnce(Return(false));
EXPECT_TRUE(foo_->CTUnary(2));
EXPECT_FALSE(foo_->CTUnary(2));
}
// Tests mocking a decimal function with calltype.
TEST_F(MockMethodFunctionMockerTest, MocksDecimalFunctionWithCallType) {
EXPECT_CALL(mock_foo_, CTDecimal(true, 'a', 0, 0, 1L, A<float>(),
Lt(100), 5U, NULL, "hi"))
.WillOnce(Return(10));
EXPECT_EQ(10, foo_->CTDecimal(true, 'a', 0, 0, 1, 0, 0, 5, NULL, "hi"));
}
// Tests mocking functions overloaded on the const-ness of this object.
TEST_F(MockMethodFunctionMockerTest, MocksFunctionsConstFunctionWithCallType) {
EXPECT_CALL(Const(mock_foo_), CTConst(_))
.WillOnce(Return('a'));
EXPECT_EQ('a', Const(*foo_).CTConst(0));
}
TEST_F(MockMethodFunctionMockerTest, MocksReturnTypeWithCommaAndCallType) {
const std::map<int, std::string> a_map;
EXPECT_CALL(mock_foo_, CTReturnTypeWithComma())
.WillOnce(Return(a_map));
EXPECT_EQ(a_map, mock_foo_.CTReturnTypeWithComma());
}
#endif // GTEST_OS_WINDOWS
class MockB {
public:
MockB() {}
MOCK_METHOD(void, DoB, ());
private:
GTEST_DISALLOW_COPY_AND_ASSIGN_(MockB);
};
// Tests that functions with no EXPECT_CALL() rules can be called any
// number of times.
TEST(MockMethodExpectCallTest, UnmentionedFunctionCanBeCalledAnyNumberOfTimes) {
{
MockB b;
}
{
MockB b;
b.DoB();
}
{
MockB b;
b.DoB();
b.DoB();
}
}
// Tests mocking template interfaces.
template <typename T>
class StackInterface {
public:
virtual ~StackInterface() {}
// Template parameter appears in function parameter.
virtual void Push(const T& value) = 0;
virtual void Pop() = 0;
virtual int GetSize() const = 0;
// Template parameter appears in function return type.
virtual const T& GetTop() const = 0;
};
template <typename T>
class MockStack : public StackInterface<T> {
public:
MockStack() {}
MOCK_METHOD(void, Push, (const T& elem), ());
MOCK_METHOD(void, Pop, (), (final));
MOCK_METHOD(int, GetSize, (), (const, override));
MOCK_METHOD(const T&, GetTop, (), (const));
// Tests that the function return type can contain unprotected comma.
MOCK_METHOD((std::map<int, int>), ReturnTypeWithComma, (), ());
MOCK_METHOD((std::map<int, int>), ReturnTypeWithComma, (int), (const));
private:
GTEST_DISALLOW_COPY_AND_ASSIGN_(MockStack);
};
// Tests that template mock works.
TEST(MockMethodTemplateMockTest, Works) {
MockStack<int> mock;
EXPECT_CALL(mock, GetSize())
.WillOnce(Return(0))
.WillOnce(Return(1))
.WillOnce(Return(0));
EXPECT_CALL(mock, Push(_));
int n = 5;
EXPECT_CALL(mock, GetTop())
.WillOnce(ReturnRef(n));
EXPECT_CALL(mock, Pop())
.Times(AnyNumber());
EXPECT_EQ(0, mock.GetSize());
mock.Push(5);
EXPECT_EQ(1, mock.GetSize());
EXPECT_EQ(5, mock.GetTop());
mock.Pop();
EXPECT_EQ(0, mock.GetSize());
}
TEST(MockMethodTemplateMockTest, MethodWithCommaInReturnTypeWorks) {
MockStack<int> mock;
const std::map<int, int> a_map;
EXPECT_CALL(mock, ReturnTypeWithComma())
.WillOnce(Return(a_map));
EXPECT_CALL(mock, ReturnTypeWithComma(1))
.WillOnce(Return(a_map));
EXPECT_EQ(a_map, mock.ReturnTypeWithComma());
EXPECT_EQ(a_map, mock.ReturnTypeWithComma(1));
}
#if GTEST_OS_WINDOWS
// Tests mocking template interfaces with calltype.
template <typename T>
class StackInterfaceWithCallType {
public:
virtual ~StackInterfaceWithCallType() {}
// Template parameter appears in function parameter.
STDMETHOD_(void, Push)(const T& value) = 0;
STDMETHOD_(void, Pop)() = 0;
STDMETHOD_(int, GetSize)() const = 0;
// Template parameter appears in function return type.
STDMETHOD_(const T&, GetTop)() const = 0;
};
template <typename T>
class MockStackWithCallType : public StackInterfaceWithCallType<T> {
public:
MockStackWithCallType() {}
MOCK_METHOD(void, Push, (const T& elem),
(Calltype(STDMETHODCALLTYPE), override));
MOCK_METHOD(void, Pop, (), (Calltype(STDMETHODCALLTYPE), override));
MOCK_METHOD(int, GetSize, (), (Calltype(STDMETHODCALLTYPE), override, const));
MOCK_METHOD(const T&, GetTop, (),
(Calltype(STDMETHODCALLTYPE), override, const));
private:
GTEST_DISALLOW_COPY_AND_ASSIGN_(MockStackWithCallType);
};
// Tests that template mock with calltype works.
TEST(MockMethodTemplateMockTestWithCallType, Works) {
MockStackWithCallType<int> mock;
EXPECT_CALL(mock, GetSize())
.WillOnce(Return(0))
.WillOnce(Return(1))
.WillOnce(Return(0));
EXPECT_CALL(mock, Push(_));
int n = 5;
EXPECT_CALL(mock, GetTop())
.WillOnce(ReturnRef(n));
EXPECT_CALL(mock, Pop())
.Times(AnyNumber());
EXPECT_EQ(0, mock.GetSize());
mock.Push(5);
EXPECT_EQ(1, mock.GetSize());
EXPECT_EQ(5, mock.GetTop());
mock.Pop();
EXPECT_EQ(0, mock.GetSize());
}
#endif // GTEST_OS_WINDOWS
#define MY_MOCK_METHODS1_ \
MOCK_METHOD(void, Overloaded, ()); \
MOCK_METHOD(int, Overloaded, (int), (const)); \
MOCK_METHOD(bool, Overloaded, (bool f, int n))
class MockOverloadedOnArgNumber {
public:
MockOverloadedOnArgNumber() {}
MY_MOCK_METHODS1_;
private:
GTEST_DISALLOW_COPY_AND_ASSIGN_(MockOverloadedOnArgNumber);
};
TEST(MockMethodOverloadedMockMethodTest, CanOverloadOnArgNumberInMacroBody) {
MockOverloadedOnArgNumber mock;
EXPECT_CALL(mock, Overloaded());
EXPECT_CALL(mock, Overloaded(1)).WillOnce(Return(2));
EXPECT_CALL(mock, Overloaded(true, 1)).WillOnce(Return(true));
mock.Overloaded();
EXPECT_EQ(2, mock.Overloaded(1));
EXPECT_TRUE(mock.Overloaded(true, 1));
}
#define MY_MOCK_METHODS2_ \
MOCK_CONST_METHOD1(Overloaded, int(int n)); \
MOCK_METHOD1(Overloaded, int(int n))
class MockOverloadedOnConstness {
public:
MockOverloadedOnConstness() {}
MY_MOCK_METHODS2_;
private:
GTEST_DISALLOW_COPY_AND_ASSIGN_(MockOverloadedOnConstness);
};
TEST(MockMethodOverloadedMockMethodTest, CanOverloadOnConstnessInMacroBody) {
MockOverloadedOnConstness mock;
const MockOverloadedOnConstness* const_mock = &mock;
EXPECT_CALL(mock, Overloaded(1)).WillOnce(Return(2));
EXPECT_CALL(*const_mock, Overloaded(1)).WillOnce(Return(3));
EXPECT_EQ(2, mock.Overloaded(1));
EXPECT_EQ(3, const_mock->Overloaded(1));
}
TEST(MockMethodMockFunctionTest, WorksForVoidNullary) {
MockFunction<void()> foo;
EXPECT_CALL(foo, Call());
foo.Call();
}
TEST(MockMethodMockFunctionTest, WorksForNonVoidNullary) {
MockFunction<int()> foo;
EXPECT_CALL(foo, Call())
.WillOnce(Return(1))
.WillOnce(Return(2));
EXPECT_EQ(1, foo.Call());
EXPECT_EQ(2, foo.Call());
}
TEST(MockMethodMockFunctionTest, WorksForVoidUnary) {
MockFunction<void(int)> foo;
EXPECT_CALL(foo, Call(1));
foo.Call(1);
}
TEST(MockMethodMockFunctionTest, WorksForNonVoidBinary) {
MockFunction<int(bool, int)> foo;
EXPECT_CALL(foo, Call(false, 42))
.WillOnce(Return(1))
.WillOnce(Return(2));
EXPECT_CALL(foo, Call(true, Ge(100)))
.WillOnce(Return(3));
EXPECT_EQ(1, foo.Call(false, 42));
EXPECT_EQ(2, foo.Call(false, 42));
EXPECT_EQ(3, foo.Call(true, 120));
}
TEST(MockMethodMockFunctionTest, WorksFor10Arguments) {
MockFunction<int(bool a0, char a1, int a2, int a3, int a4,
int a5, int a6, char a7, int a8, bool a9)> foo;
EXPECT_CALL(foo, Call(_, 'a', _, _, _, _, _, _, _, _))
.WillOnce(Return(1))
.WillOnce(Return(2));
EXPECT_EQ(1, foo.Call(false, 'a', 0, 0, 0, 0, 0, 'b', 0, true));
EXPECT_EQ(2, foo.Call(true, 'a', 0, 0, 0, 0, 0, 'b', 1, false));
}
TEST(MockMethodMockFunctionTest, AsStdFunction) {
MockFunction<int(int)> foo;
auto call = [](const std::function<int(int)> &f, int i) {
return f(i);
};
EXPECT_CALL(foo, Call(1)).WillOnce(Return(-1));
EXPECT_CALL(foo, Call(2)).WillOnce(Return(-2));
EXPECT_EQ(-1, call(foo.AsStdFunction(), 1));
EXPECT_EQ(-2, call(foo.AsStdFunction(), 2));
}
TEST(MockMethodMockFunctionTest, AsStdFunctionReturnsReference) {
MockFunction<int&()> foo;
int value = 1;
EXPECT_CALL(foo, Call()).WillOnce(ReturnRef(value));
int& ref = foo.AsStdFunction()();
EXPECT_EQ(1, ref);
value = 2;
EXPECT_EQ(2, ref);
}
TEST(MockMethodMockFunctionTest, 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));
}
struct MockMethodSizes0 {
MOCK_METHOD(void, func, ());
};
struct MockMethodSizes1 {
MOCK_METHOD(void, func, (int));
};
struct MockMethodSizes2 {
MOCK_METHOD(void, func, (int, int));
};
struct MockMethodSizes3 {
MOCK_METHOD(void, func, (int, int, int));
};
struct MockMethodSizes4 {
MOCK_METHOD(void, func, (int, int, int, int));
};
TEST(MockMethodMockFunctionTest, 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_function_mocker_test
} // namespace testing

View File

@ -35,6 +35,7 @@
#include "gmock/gmock-generated-actions.h"
#include <functional>
#include <memory>
#include <sstream>
#include <string>
#include "gmock/gmock.h"
@ -45,10 +46,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;
@ -60,7 +57,6 @@ using testing::ReturnNew;
using testing::SetArgPointee;
using testing::StaticAssertTypeEq;
using testing::Unused;
using testing::WithArgs;
// For suppressing compiler warnings on conversion possibly losing precision.
inline short Short(short n) { return n; } // NOLINT
@ -69,43 +65,19 @@ inline char Char(char ch) { return ch; }
// Sample functions and functors for testing various actions.
int Nullary() { return 1; }
class NullaryFunctor {
public:
int operator()() { return 2; }
};
bool g_done = false;
bool Unary(int x) { return x < 0; }
const char* Plus1(const char* s) { return s + 1; }
bool ByConstRef(const std::string& s) { return s == "Hi"; }
const double g_double = 0;
bool ReferencesGlobalDouble(const double& x) { return &x == &g_double; }
std::string ByNonConstRef(std::string& s) { return s += "+"; } // NOLINT
struct UnaryFunctor {
int operator()(bool x) { return x ? 1 : -1; }
};
const char* Binary(const char* input, short n) { return input + n; } // NOLINT
void VoidBinary(int, char) { g_done = true; }
int Ternary(int x, char y, short z) { return x + y + z; } // NOLINT
void VoidTernary(int, char, bool) { g_done = true; }
int SumOf4(int a, int b, int c, int d) { return a + b + c + d; }
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; }
struct SumOf5Functor {
@ -168,41 +140,41 @@ 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.
@ -211,7 +183,7 @@ TEST(InvokeArgumentTest, Function7) {
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)));
EXPECT_EQ("1234567", a.Perform(std::make_tuple(&Concat7)));
}
// Tests using InvokeArgument with a 8-ary function.
@ -220,7 +192,7 @@ TEST(InvokeArgumentTest, Function8) {
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)));
EXPECT_EQ("12345678", a.Perform(std::make_tuple(&Concat8)));
}
// Tests using InvokeArgument with a 9-ary function.
@ -229,7 +201,7 @@ TEST(InvokeArgumentTest, Function9) {
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)));
EXPECT_EQ("123456789", a.Perform(std::make_tuple(&Concat9)));
}
// Tests using InvokeArgument with a 10-ary function.
@ -238,14 +210,14 @@ TEST(InvokeArgumentTest, Function10) {
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)));
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*
@ -253,7 +225,7 @@ 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.
@ -263,7 +235,7 @@ TEST(InvokeArgumentTest, ByConstReferenceFunction) {
// 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
@ -272,148 +244,11 @@ 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)));
}
// 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)));
}
// Tests using WithArgs with an action that takes 2 arguments.
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))));
}
// 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))));
}
// Tests using WithArgs with an action that takes 4 arguments.
TEST(WithArgsTest, FourArgs) {
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(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<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"))));
}
// Tests using WithArgs with an action that takes 6 arguments.
TEST(WithArgsTest, SixArgs) {
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"))));
}
// Tests using WithArgs with an action that takes 7 arguments.
TEST(WithArgsTest, SevenArgs) {
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"))));
}
// Tests using WithArgs with an action that takes 8 arguments.
TEST(WithArgsTest, EightArgs) {
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"))));
}
// Tests using WithArgs with an action that takes 9 arguments.
TEST(WithArgsTest, NineArgs) {
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"))));
}
// Tests using WithArgs with an action that takes 10 arguments.
TEST(WithArgsTest, TenArgs) {
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"))));
}
// 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);
}
};
TEST(WithArgsTest, NonInvokeAction) {
Action<int(const std::string&, int, int)> a = // NOLINT
WithArgs<2, 1>(MakeAction(new SubstractAction));
tuple<std::string, int, int> dummy = 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))));
}
// 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)));
}
// Tests using WithArgs with reversed argument order.
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))));
}
// 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))));
}
// 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));
EXPECT_TRUE(g_done);
EXPECT_FALSE(a.Perform(std::make_tuple(&ReferencesGlobalDouble)));
}
// Tests DoAll(a1, a2).
@ -421,7 +256,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);
}
@ -431,7 +266,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);
}
@ -445,7 +280,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);
@ -461,7 +296,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);
@ -479,7 +314,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);
@ -499,7 +334,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);
@ -522,7 +357,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);
@ -547,7 +382,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);
@ -575,7 +410,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);
@ -592,11 +428,12 @@ TEST(DoAllTest, TenActions) {
// the macro definition, as the warnings are generated when the macro
// is expanded and macro expansion cannot contain #pragma. Therefore
// we suppress them here.
// Also suppress C4503 decorated name length exceeded, name was truncated
#ifdef _MSC_VER
# pragma warning(push)
# pragma warning(disable:4100)
# pragma warning(disable:4503)
#endif
// Tests the ACTION*() macro family.
// Tests that ACTION() can define an action that doesn't reference the
@ -605,10 +442,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.
@ -617,7 +454,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);
}
@ -632,22 +469,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
@ -662,8 +499,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
@ -676,8 +513,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.
@ -689,7 +526,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.
@ -701,7 +538,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.
@ -711,7 +548,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
@ -720,11 +557,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.
@ -732,7 +569,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
@ -745,7 +582,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
@ -753,7 +590,7 @@ TEST(ActionPMacroTest, CanReferenceArgumentAndParameterTypes) {
TEST(ActionPMacroTest, WorksInCompatibleMockFunction) {
Action<std::string(const std::string& s)> a1 = Plus("tail");
const std::string re = "re";
tuple<const std::string> dummy = make_tuple(re);
std::tuple<const std::string> dummy = std::make_tuple(re);
EXPECT_EQ("retail", a1.Perform(dummy));
}
@ -774,16 +611,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,11 +629,11 @@ 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";
tuple<const std::string> dummy = make_tuple(re);
std::tuple<const std::string> dummy = std::make_tuple(re);
EXPECT_EQ("retail->", a2.Perform(dummy));
}
@ -804,14 +641,14 @@ 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) {
@ -820,7 +657,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) {
@ -829,7 +666,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) {
@ -838,7 +675,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) {
@ -847,7 +685,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) {
@ -859,7 +698,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.
@ -876,8 +715,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
@ -926,10 +765,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*.
@ -987,7 +826,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));
@ -1014,7 +853,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;
}
@ -1028,7 +867,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;
}
@ -1036,7 +875,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;
}
@ -1044,7 +883,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;
}
@ -1064,7 +903,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;
}
@ -1078,7 +917,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;
}
@ -1091,7 +930,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;
}
@ -1100,7 +939,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.
@ -1117,7 +956,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.
}
@ -1130,9 +969,9 @@ 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());
const Action<std::shared_ptr<int>()> a =
ReturnSmartPointer<std::shared_ptr>(42);
std::shared_ptr<int> p = a.Perform(std::make_tuple());
EXPECT_EQ(42, *p);
}
@ -1162,12 +1001,11 @@ ACTION_TEMPLATE(ReturnGiant,
}
TEST(ActionTemplateTest, WorksFor10TemplateParameters) {
using ::testing::internal::linked_ptr;
typedef GiantTemplate<linked_ptr<int>, bool, double, 5,
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());
using Giant = GiantTemplate<std::shared_ptr<int>, bool, double, 5, true, 6,
char, unsigned, int>;
const Action<Giant()> a = ReturnGiant<int, bool, double, 5, true, 6, char,
unsigned, int, std::shared_ptr>(42);
Giant giant = a.Perform(std::make_tuple());
EXPECT_EQ(42, giant.value);
}
@ -1180,7 +1018,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
@ -1214,16 +1052,13 @@ 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
# pragma warning(pop)
#endif
} // namespace gmock_generated_actions_test
} // namespace testing

View File

@ -46,13 +46,6 @@
#include "gmock/gmock.h"
#include "gtest/gtest.h"
// There is a bug in MSVC (fixed in VS 2008) that prevents creating a
// mock for a function with const arguments, so we don't test such
// cases for MSVC versions older than 2008.
#if !GTEST_OS_WINDOWS || (_MSC_VER >= 1500)
# define GMOCK_ALLOWS_CONST_PARAM_FUNCTIONS
#endif // !GTEST_OS_WINDOWS || (_MSC_VER >= 1500)
namespace testing {
namespace gmock_generated_function_mockers_test {
@ -70,6 +63,15 @@ using testing::Return;
using testing::ReturnRef;
using testing::TypedEq;
template<typename T>
class TemplatedCopyable {
public:
TemplatedCopyable() {}
template <typename U>
TemplatedCopyable(const U& other) {} // NOLINT
};
class FooInterface {
public:
virtual ~FooInterface() {}
@ -85,9 +87,7 @@ class FooInterface {
virtual bool TakesNonConstReference(int& n) = 0; // NOLINT
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
virtual int OverloadedOnArgumentNumber() = 0;
virtual int OverloadedOnArgumentNumber(int n) = 0;
@ -100,6 +100,8 @@ class FooInterface {
virtual int TypeWithHole(int (*func)()) = 0;
virtual int TypeWithComma(const std::map<int, std::string>& a_map) = 0;
virtual int TypeWithTemplatedCopyCtor(
const TemplatedCopyable<int>& a_vector) = 0;
#if GTEST_OS_WINDOWS
STDMETHOD_(int, CTNullary)() = 0;
@ -136,10 +138,7 @@ class MockFoo : public FooInterface {
MOCK_METHOD1(TakesNonConstReference, bool(int&)); // NOLINT
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, std::string>());
@ -158,6 +157,8 @@ class MockFoo : public FooInterface {
MOCK_METHOD1(TypeWithHole, int(int (*)())); // NOLINT
MOCK_METHOD1(TypeWithComma,
int(const std::map<int, std::string>&)); // NOLINT
MOCK_METHOD1(TypeWithTemplatedCopyCtor,
int(const TemplatedCopyable<int>&)); // NOLINT
#if GTEST_OS_WINDOWS
MOCK_METHOD0_WITH_CALLTYPE(STDMETHODCALLTYPE, CTNullary, int());
@ -224,11 +225,11 @@ TEST_F(FunctionMockerTest, MocksBinaryFunction) {
// Tests mocking a decimal function.
TEST_F(FunctionMockerTest, MocksDecimalFunction) {
EXPECT_CALL(mock_foo_, Decimal(true, 'a', 0, 0, 1L, A<float>(),
Lt(100), 5U, NULL, "hi"))
EXPECT_CALL(mock_foo_, Decimal(true, 'a', 0, 0, 1L, A<float>(), Lt(100), 5U,
nullptr, "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.
@ -249,7 +250,6 @@ TEST_F(FunctionMockerTest, MocksFunctionWithConstReferenceArgument) {
EXPECT_EQ("Hello", foo_->TakesConstReference(a));
}
#ifdef GMOCK_ALLOWS_CONST_PARAM_FUNCTIONS
// Tests mocking a function that takes a const variable.
TEST_F(FunctionMockerTest, MocksFunctionWithConstArgument) {
EXPECT_CALL(mock_foo_, TakesConst(Lt(10)))
@ -257,7 +257,6 @@ TEST_F(FunctionMockerTest, MocksFunctionWithConstArgument) {
EXPECT_FALSE(foo_->TakesConst(5));
}
#endif // GMOCK_ALLOWS_CONST_PARAM_FUNCTIONS
// Tests mocking functions overloaded on the number of arguments.
TEST_F(FunctionMockerTest, MocksFunctionsOverloadedOnArgumentNumber) {
@ -302,6 +301,11 @@ TEST_F(FunctionMockerTest, MocksReturnTypeWithComma) {
EXPECT_EQ(a_map, mock_foo_.ReturnTypeWithComma(42));
}
TEST_F(FunctionMockerTest, MocksTypeWithTemplatedCopyCtor) {
EXPECT_CALL(mock_foo_, TypeWithTemplatedCopyCtor(_)).WillOnce(Return(true));
EXPECT_TRUE(foo_->TypeWithTemplatedCopyCtor(TemplatedCopyable<int>()));
}
#if GTEST_OS_WINDOWS
// Tests mocking a nullary function with calltype.
TEST_F(FunctionMockerTest, MocksNullaryFunctionWithCallType) {
@ -326,11 +330,11 @@ TEST_F(FunctionMockerTest, MocksUnaryFunctionWithCallType) {
// Tests mocking a decimal function with calltype.
TEST_F(FunctionMockerTest, MocksDecimalFunctionWithCallType) {
EXPECT_CALL(mock_foo_, CTDecimal(true, 'a', 0, 0, 1L, A<float>(),
Lt(100), 5U, NULL, "hi"))
EXPECT_CALL(mock_foo_, CTDecimal(true, 'a', 0, 0, 1L, A<float>(), Lt(100), 5U,
nullptr, "hi"))
.WillOnce(Return(10));
EXPECT_EQ(10, foo_->CTDecimal(true, 'a', 0, 0, 1, 0, 0, 5, NULL, "hi"));
EXPECT_EQ(10, foo_->CTDecimal(true, 'a', 0, 0, 1, 0, 0, 5, nullptr, "hi"));
}
// Tests mocking functions overloaded on the const-ness of this object.
@ -531,7 +535,7 @@ TEST(OverloadedMockMethodTest, CanOverloadOnArgNumberInMacroBody) {
#define MY_MOCK_METHODS2_ \
MOCK_CONST_METHOD1(Overloaded, int(int n)); \
MOCK_METHOD1(Overloaded, int(int n));
MOCK_METHOD1(Overloaded, int(int n))
class MockOverloadedOnConstness {
public:
@ -596,7 +600,6 @@ TEST(MockFunctionTest, WorksFor10Arguments) {
EXPECT_EQ(2, foo.Call(true, 'a', 0, 0, 0, 0, 0, 'b', 1, false));
}
#if GTEST_HAS_STD_FUNCTION_
TEST(MockFunctionTest, AsStdFunction) {
MockFunction<int(int)> foo;
auto call = [](const std::function<int(int)> &f, int i) {
@ -617,7 +620,17 @@ TEST(MockFunctionTest, AsStdFunctionReturnsReference) {
value = 2;
EXPECT_EQ(2, ref);
}
#endif // GTEST_HAS_STD_FUNCTION_
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));
}
struct MockMethodSizes0 {
MOCK_METHOD0(func, void());

View File

@ -1,128 +0,0 @@
// Copyright 2007, 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.
// Google Mock - a framework for writing C++ mock classes.
//
// This file tests the internal utilities.
#include "gmock/internal/gmock-generated-internal-utils.h"
#include "gmock/internal/gmock-internal-utils.h"
#include "gtest/gtest.h"
namespace {
using ::testing::tuple;
using ::testing::Matcher;
using ::testing::internal::CompileAssertTypesEqual;
using ::testing::internal::MatcherTuple;
using ::testing::internal::Function;
using ::testing::internal::IgnoredValue;
// Tests the MatcherTuple template struct.
TEST(MatcherTupleTest, ForSize0) {
CompileAssertTypesEqual<tuple<>, MatcherTuple<tuple<> >::type>();
}
TEST(MatcherTupleTest, ForSize1) {
CompileAssertTypesEqual<tuple<Matcher<int> >,
MatcherTuple<tuple<int> >::type>();
}
TEST(MatcherTupleTest, ForSize2) {
CompileAssertTypesEqual<tuple<Matcher<int>, Matcher<char> >,
MatcherTuple<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>();
}
// Tests the Function template struct.
TEST(FunctionTest, Nullary) {
typedef Function<int()> F; // NOLINT
CompileAssertTypesEqual<int, F::Result>();
CompileAssertTypesEqual<tuple<>, F::ArgumentTuple>();
CompileAssertTypesEqual<tuple<>, F::ArgumentMatcherTuple>();
CompileAssertTypesEqual<void(), F::MakeResultVoid>();
CompileAssertTypesEqual<IgnoredValue(), F::MakeResultIgnoredValue>();
}
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<void(bool), F::MakeResultVoid>(); // NOLINT
CompileAssertTypesEqual<IgnoredValue(bool), // NOLINT
F::MakeResultIgnoredValue>();
}
TEST(FunctionTest, Binary) {
typedef Function<int(bool, const long&)> F; // NOLINT
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<void(bool, const long&), F::MakeResultVoid>(); // NOLINT
CompileAssertTypesEqual<IgnoredValue(bool, const long&), // NOLINT
F::MakeResultIgnoredValue>();
}
TEST(FunctionTest, LongArgumentList) {
typedef Function<char(bool, int, char*, int&, const long&)> F; // NOLINT
CompileAssertTypesEqual<char, F::Result>();
CompileAssertTypesEqual<bool, F::Argument1>();
CompileAssertTypesEqual<int, F::Argument2>();
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<void(bool, int, char*, int&, const long&), // NOLINT
F::MakeResultVoid>();
CompileAssertTypesEqual<
IgnoredValue(bool, int, char*, int&, const long&), // NOLINT
F::MakeResultIgnoredValue>();
}
} // Unnamed namespace

View File

@ -62,12 +62,11 @@ 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::AllOfArray;
using testing::AnyOf;
using testing::AnyOfArray;
using testing::Args;
using testing::Contains;
using testing::ElementsAre;
@ -115,164 +114,16 @@ std::string Explain(const MatcherType& m, const Value& x) {
return ss.str();
}
// 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<>()))));
}
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)))));
}
TEST(ArgsTest, AcceptsTwoTemplateArgs) {
const tuple<short, int, long> t(4, 5, 6L); // NOLINT
EXPECT_THAT(t, (Args<0, 1>(Lt())));
EXPECT_THAT(t, (Args<1, 2>(Lt())));
EXPECT_THAT(t, Not(Args<0, 2>(Gt())));
}
TEST(ArgsTest, AcceptsRepeatedTemplateArgs) {
const 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
EXPECT_THAT(t, (Args<2, 0>(Gt())));
EXPECT_THAT(t, Not(Args<2, 1>(Lt())));
}
// The MATCHER*() macros trigger warning C4100 (unreferenced formal
// parameter) in MSVC with -W4. Unfortunately they cannot be fixed in
// the macro definition, as the warnings are generated when the macro
// is expanded and macro expansion cannot contain #pragma. Therefore
// we suppress them here.
#ifdef _MSC_VER
# pragma warning(push)
# pragma warning(disable:4100)
#endif
MATCHER(SumIsZero, "") {
return get<0>(arg) + get<1>(arg) + 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())));
}
TEST(ArgsTest, CanBeNested) {
const 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;
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;
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)));
}
// Validates that arg is printed as str.
MATCHER_P(PrintsAs, str, "") {
return testing::PrintToString(arg) == str;
}
TEST(ArgsTest, AcceptsTenTemplateArgs) {
EXPECT_THAT(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),
Not(Args<9, 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());
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 =
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",
Describe(m));
}
TEST(ArgsTest, DescribesNegationCorrectly) {
const Matcher<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());
EXPECT_EQ("whose fields (#1, #2) are (42, 42)",
Explain(m, make_tuple(false, 42, 42)));
EXPECT_EQ("whose fields (#1, #2) are (42, 43)",
Explain(m, make_tuple(false, 42, 43)));
}
// For testing Args<>'s explanation.
class LessThanMatcher : public MatcherInterface<tuple<char, int> > {
public:
virtual void DescribeTo(::std::ostream* os) const {}
virtual bool MatchAndExplain(tuple<char, int> value,
MatchResultListener* listener) const {
const int diff = get<0>(value) - get<1>(value);
if (diff > 0) {
*listener << "where the first value is " << diff
<< " more than the second";
}
return diff < 0;
}
};
Matcher<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)));
EXPECT_EQ("whose fields (#0, #2) are ('\\0', 43)",
Explain(m, make_tuple('\0', 42, 43)));
}
// For testing ExplainMatchResultTo().
class GreaterThanMatcher : public MatcherInterface<int> {
public:
explicit GreaterThanMatcher(int rhs) : rhs_(rhs) {}
virtual void DescribeTo(::std::ostream* os) const {
void DescribeTo(::std::ostream* os) const override {
*os << "is greater than " << rhs_;
}
virtual bool MatchAndExplain(int lhs,
MatchResultListener* listener) const {
bool MatchAndExplain(int lhs, MatchResultListener* listener) const override {
const int diff = lhs - rhs_;
if (diff > 0) {
*listener << "which is " << diff << " more than " << rhs_;
@ -517,7 +368,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)));
@ -571,8 +422,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 };
@ -640,7 +491,6 @@ TEST(ElementsAreArrayTest, CanBeCreatedWithVector) {
EXPECT_THAT(test_vector, Not(ElementsAreArray(expected)));
}
#if GTEST_HAS_STD_INITIALIZER_LIST_
TEST(ElementsAreArrayTest, TakesInitializerList) {
const int a[5] = { 1, 2, 3, 4, 5 };
@ -676,7 +526,6 @@ TEST(ElementsAreArrayTest,
{ Eq(1), Ne(-2), Ge(3), Le(4), Eq(6) })));
}
#endif // GTEST_HAS_STD_INITIALIZER_LIST_
TEST(ElementsAreArrayTest, CanBeCreatedWithMatcherVector) {
const int a[] = { 1, 2, 3 };
@ -697,7 +546,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));
}
@ -770,7 +619,7 @@ MATCHER_P2(EqSumOf, x, y, std::string(negation ? "doesn't equal" : "equals") +
} 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;
@ -1235,8 +1084,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) {
@ -1247,6 +1096,146 @@ TEST(ContainsTest, WorksForTwoDimensionalNativeArray) {
EXPECT_THAT(a, Contains(Not(Contains(5))));
}
TEST(AllOfArrayTest, BasicForms) {
// Iterator
std::vector<int> v0{};
std::vector<int> v1{1};
std::vector<int> v2{2, 3};
std::vector<int> v3{4, 4, 4};
EXPECT_THAT(0, AllOfArray(v0.begin(), v0.end()));
EXPECT_THAT(1, AllOfArray(v1.begin(), v1.end()));
EXPECT_THAT(2, Not(AllOfArray(v1.begin(), v1.end())));
EXPECT_THAT(3, Not(AllOfArray(v2.begin(), v2.end())));
EXPECT_THAT(4, AllOfArray(v3.begin(), v3.end()));
// Pointer + size
int ar[6] = {1, 2, 3, 4, 4, 4};
EXPECT_THAT(0, AllOfArray(ar, 0));
EXPECT_THAT(1, AllOfArray(ar, 1));
EXPECT_THAT(2, Not(AllOfArray(ar, 1)));
EXPECT_THAT(3, Not(AllOfArray(ar + 1, 3)));
EXPECT_THAT(4, AllOfArray(ar + 3, 3));
// Array
// int ar0[0]; Not usable
int ar1[1] = {1};
int ar2[2] = {2, 3};
int ar3[3] = {4, 4, 4};
// EXPECT_THAT(0, Not(AllOfArray(ar0))); // Cannot work
EXPECT_THAT(1, AllOfArray(ar1));
EXPECT_THAT(2, Not(AllOfArray(ar1)));
EXPECT_THAT(3, Not(AllOfArray(ar2)));
EXPECT_THAT(4, AllOfArray(ar3));
// Container
EXPECT_THAT(0, AllOfArray(v0));
EXPECT_THAT(1, AllOfArray(v1));
EXPECT_THAT(2, Not(AllOfArray(v1)));
EXPECT_THAT(3, Not(AllOfArray(v2)));
EXPECT_THAT(4, AllOfArray(v3));
// Initializer
EXPECT_THAT(0, AllOfArray<int>({})); // Requires template arg.
EXPECT_THAT(1, AllOfArray({1}));
EXPECT_THAT(2, Not(AllOfArray({1})));
EXPECT_THAT(3, Not(AllOfArray({2, 3})));
EXPECT_THAT(4, AllOfArray({4, 4, 4}));
}
TEST(AllOfArrayTest, Matchers) {
// vector
std::vector<Matcher<int>> matchers{Ge(1), Lt(2)};
EXPECT_THAT(0, Not(AllOfArray(matchers)));
EXPECT_THAT(1, AllOfArray(matchers));
EXPECT_THAT(2, Not(AllOfArray(matchers)));
// initializer_list
EXPECT_THAT(0, Not(AllOfArray({Ge(0), Ge(1)})));
EXPECT_THAT(1, AllOfArray({Ge(0), Ge(1)}));
}
TEST(AnyOfArrayTest, BasicForms) {
// Iterator
std::vector<int> v0{};
std::vector<int> v1{1};
std::vector<int> v2{2, 3};
EXPECT_THAT(0, Not(AnyOfArray(v0.begin(), v0.end())));
EXPECT_THAT(1, AnyOfArray(v1.begin(), v1.end()));
EXPECT_THAT(2, Not(AnyOfArray(v1.begin(), v1.end())));
EXPECT_THAT(3, AnyOfArray(v2.begin(), v2.end()));
EXPECT_THAT(4, Not(AnyOfArray(v2.begin(), v2.end())));
// Pointer + size
int ar[3] = {1, 2, 3};
EXPECT_THAT(0, Not(AnyOfArray(ar, 0)));
EXPECT_THAT(1, AnyOfArray(ar, 1));
EXPECT_THAT(2, Not(AnyOfArray(ar, 1)));
EXPECT_THAT(3, AnyOfArray(ar + 1, 2));
EXPECT_THAT(4, Not(AnyOfArray(ar + 1, 2)));
// Array
// int ar0[0]; Not usable
int ar1[1] = {1};
int ar2[2] = {2, 3};
// EXPECT_THAT(0, Not(AnyOfArray(ar0))); // Cannot work
EXPECT_THAT(1, AnyOfArray(ar1));
EXPECT_THAT(2, Not(AnyOfArray(ar1)));
EXPECT_THAT(3, AnyOfArray(ar2));
EXPECT_THAT(4, Not(AnyOfArray(ar2)));
// Container
EXPECT_THAT(0, Not(AnyOfArray(v0)));
EXPECT_THAT(1, AnyOfArray(v1));
EXPECT_THAT(2, Not(AnyOfArray(v1)));
EXPECT_THAT(3, AnyOfArray(v2));
EXPECT_THAT(4, Not(AnyOfArray(v2)));
// Initializer
EXPECT_THAT(0, Not(AnyOfArray<int>({}))); // Requires template arg.
EXPECT_THAT(1, AnyOfArray({1}));
EXPECT_THAT(2, Not(AnyOfArray({1})));
EXPECT_THAT(3, AnyOfArray({2, 3}));
EXPECT_THAT(4, Not(AnyOfArray({2, 3})));
}
TEST(AnyOfArrayTest, Matchers) {
// We negate test AllOfArrayTest.Matchers.
// vector
std::vector<Matcher<int>> matchers{Lt(1), Ge(2)};
EXPECT_THAT(0, AnyOfArray(matchers));
EXPECT_THAT(1, Not(AnyOfArray(matchers)));
EXPECT_THAT(2, AnyOfArray(matchers));
// initializer_list
EXPECT_THAT(0, AnyOfArray({Lt(0), Lt(1)}));
EXPECT_THAT(1, Not(AllOfArray({Lt(0), Lt(1)})));
}
TEST(AnyOfArrayTest, ExplainsMatchResultCorrectly) {
// AnyOfArray and AllOfArry use the same underlying template-template,
// thus it is sufficient to test one here.
const std::vector<int> v0{};
const std::vector<int> v1{1};
const std::vector<int> v2{2, 3};
const Matcher<int> m0 = AnyOfArray(v0);
const Matcher<int> m1 = AnyOfArray(v1);
const Matcher<int> m2 = AnyOfArray(v2);
EXPECT_EQ("", Explain(m0, 0));
EXPECT_EQ("", Explain(m1, 1));
EXPECT_EQ("", Explain(m1, 2));
EXPECT_EQ("", Explain(m2, 3));
EXPECT_EQ("", Explain(m2, 4));
EXPECT_EQ("()", Describe(m0));
EXPECT_EQ("(is equal to 1)", Describe(m1));
EXPECT_EQ("(is equal to 2) or (is equal to 3)", Describe(m2));
EXPECT_EQ("()", DescribeNegation(m0));
EXPECT_EQ("(isn't equal to 1)", DescribeNegation(m1));
EXPECT_EQ("(isn't equal to 2) and (isn't equal to 3)", DescribeNegation(m2));
// Explain with matchers
const Matcher<int> g1 = AnyOfArray({GreaterThan(1)});
const Matcher<int> g2 = AnyOfArray({GreaterThan(1), GreaterThan(2)});
// Explains the first positiv match and all prior negative matches...
EXPECT_EQ("which is 1 less than 1", Explain(g1, 0));
EXPECT_EQ("which is the same as 1", Explain(g1, 1));
EXPECT_EQ("which is 1 more than 1", Explain(g1, 2));
EXPECT_EQ("which is 1 less than 1, and which is 2 less than 2",
Explain(g2, 0));
EXPECT_EQ("which is the same as 1, and which is 1 less than 2",
Explain(g2, 1));
EXPECT_EQ("which is 1 more than 1", // Only the first
Explain(g2, 2));
}
TEST(AllOfTest, HugeMatcher) {
// Verify that using AllOf with many arguments doesn't cause
// the compiler to exceed template instantiation depth limit.
@ -1273,7 +1262,7 @@ namespace adl_test {
MATCHER(M, "") { return true; }
template <typename T1, typename T2>
bool AllOf(const T1& t1, const T2& t2) { return true; }
bool AllOf(const T1& /*t1*/, const T2& /*t2*/) { return true; }
TEST(AllOfTest, DoesNotCallAllOfUnqualified) {
EXPECT_THAT(42, testing::AllOf(
@ -1290,11 +1279,6 @@ TEST(AnyOfTest, DoesNotCallAnyOfUnqualified) {
} // namespace adl_test
#ifdef _MSC_VER
# pragma warning(pop)
#endif
#if GTEST_LANG_CXX11
TEST(AllOfTest, WorksOnMoveOnlyType) {
std::unique_ptr<int> p(new int(3));
@ -1332,7 +1316,6 @@ TEST(MatcherPMacroTest, WorksOnMoveOnlyType) {
EXPECT_THAT(p, Not(UniquePointee(2)));
}
#endif // GTEST_LASNG_CXX11
} // namespace

View File

@ -33,16 +33,20 @@
// This file tests the internal utilities.
#include "gmock/internal/gmock-internal-utils.h"
#include <stdlib.h>
#include <map>
#include <memory>
#include <string>
#include <sstream>
#include <string>
#include <type_traits>
#include <vector>
#include "gmock/gmock.h"
#include "gmock/internal/gmock-port.h"
#include "gtest/gtest.h"
#include "gtest/gtest-spi.h"
#include "gtest/gtest.h"
// Indicates that this translation unit is part of Google Test's
// implementation. It must come before gtest-internal-inl.h is
@ -57,8 +61,6 @@
# include <sys/types.h> // For ssize_t. NOLINT
#endif
class ProtocolMessage;
namespace proto2 {
class Message;
} // namespace proto2
@ -123,44 +125,31 @@ TEST(ConvertIdentifierNameToWordsTest, WorksWhenNameIsMixture) {
}
TEST(PointeeOfTest, WorksForSmartPointers) {
CompileAssertTypesEqual<const char,
PointeeOf<internal::linked_ptr<const char> >::type>();
#if GTEST_HAS_STD_UNIQUE_PTR_
CompileAssertTypesEqual<int, PointeeOf<std::unique_ptr<int> >::type>();
#endif // GTEST_HAS_STD_UNIQUE_PTR_
#if GTEST_HAS_STD_SHARED_PTR_
CompileAssertTypesEqual<std::string,
PointeeOf<std::shared_ptr<std::string> >::type>();
#endif // GTEST_HAS_STD_SHARED_PTR_
EXPECT_TRUE(
(std::is_same<int, PointeeOf<std::unique_ptr<int>>::type>::value));
EXPECT_TRUE(
(std::is_same<std::string,
PointeeOf<std::shared_ptr<std::string>>::type>::value));
}
TEST(PointeeOfTest, WorksForRawPointers) {
CompileAssertTypesEqual<int, PointeeOf<int*>::type>();
CompileAssertTypesEqual<const char, PointeeOf<const char*>::type>();
CompileAssertTypesEqual<void, PointeeOf<void*>::type>();
EXPECT_TRUE((std::is_same<int, PointeeOf<int*>::type>::value));
EXPECT_TRUE((std::is_same<const char, PointeeOf<const char*>::type>::value));
EXPECT_TRUE((std::is_void<PointeeOf<void*>::type>::value));
}
TEST(GetRawPointerTest, WorksForSmartPointers) {
#if GTEST_HAS_STD_UNIQUE_PTR_
const char* const raw_p1 = new const char('a'); // NOLINT
const std::unique_ptr<const char> p1(raw_p1);
EXPECT_EQ(raw_p1, GetRawPointer(p1));
#endif // GTEST_HAS_STD_UNIQUE_PTR_
#if GTEST_HAS_STD_SHARED_PTR_
double* const raw_p2 = new double(2.5); // NOLINT
const std::shared_ptr<double> p2(raw_p2);
EXPECT_EQ(raw_p2, GetRawPointer(p2));
#endif // GTEST_HAS_STD_SHARED_PTR_
const char* const raw_p4 = new const char('a'); // NOLINT
const internal::linked_ptr<const char> p4(raw_p4);
EXPECT_EQ(raw_p4, GetRawPointer(p4));
}
TEST(GetRawPointerTest, WorksForRawPointers) {
int* p = NULL;
// Don't use EXPECT_EQ as no NULL-testing magic on Symbian.
EXPECT_TRUE(NULL == GetRawPointer(p));
int* p = nullptr;
EXPECT_TRUE(nullptr == GetRawPointer(p));
int n = 1;
EXPECT_EQ(&n, GetRawPointer(&n));
}
@ -308,26 +297,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));
@ -337,10 +323,11 @@ TEST(TupleMatchesTest, WorksForSize2) {
}
TEST(TupleMatchesTest, WorksForSize5) {
tuple<Matcher<int>, Matcher<char>, Matcher<bool>, Matcher<long>, // NOLINT
Matcher<std::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, std::string> // NOLINT
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");
@ -387,11 +374,9 @@ TEST(ExpectTest, FailsNonfatallyOnFalse) {
class LogIsVisibleTest : public ::testing::Test {
protected:
virtual void SetUp() {
original_verbose_ = GMOCK_FLAG(verbose);
}
void SetUp() override { original_verbose_ = GMOCK_FLAG(verbose); }
virtual void TearDown() { GMOCK_FLAG(verbose) = original_verbose_; }
void TearDown() override { GMOCK_FLAG(verbose) = original_verbose_; }
std::string original_verbose_;
};
@ -450,11 +435,11 @@ TEST(LogTest, NoStackTraceWhenStackFramesToSkipIsNegative) {
}
struct MockStackTraceGetter : testing::internal::OsStackTraceGetterInterface {
virtual std::string CurrentStackTrace(int max_depth, int skip_count) {
std::string CurrentStackTrace(int max_depth, int skip_count) override {
return (testing::Message() << max_depth << "::" << skip_count << "\n")
.GetString();
}
virtual void UponLeavingGTest() {}
void UponLeavingGTest() override {}
};
// Tests that in opt mode, a positive stack_frames_to_skip argument is
@ -492,7 +477,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
@ -523,45 +508,6 @@ TEST(LogTest, OnlyWarningsArePrintedWhenVerbosityIsInvalid) {
TestLogWithSeverity("invalid", kWarning, true);
}
#endif // GTEST_HAS_STREAM_REDIRECTION
TEST(TypeTraitsTest, true_type) {
EXPECT_TRUE(true_type::value);
}
TEST(TypeTraitsTest, false_type) {
EXPECT_FALSE(false_type::value);
}
TEST(TypeTraitsTest, is_reference) {
EXPECT_FALSE(is_reference<int>::value);
EXPECT_FALSE(is_reference<char*>::value);
EXPECT_TRUE(is_reference<const int&>::value);
}
TEST(TypeTraitsTest, is_pointer) {
EXPECT_FALSE(is_pointer<int>::value);
EXPECT_FALSE(is_pointer<char&>::value);
EXPECT_TRUE(is_pointer<const int*>::value);
}
TEST(TypeTraitsTest, type_equals) {
EXPECT_FALSE((type_equals<int, const int>::value));
EXPECT_FALSE((type_equals<int, int&>::value));
EXPECT_FALSE((type_equals<int, double>::value));
EXPECT_TRUE((type_equals<char, char>::value));
}
TEST(TypeTraitsTest, remove_reference) {
EXPECT_TRUE((type_equals<char, remove_reference<char&>::type>::value));
EXPECT_TRUE((type_equals<const int,
remove_reference<const int&>::type>::value));
EXPECT_TRUE((type_equals<int, remove_reference<int>::type>::value));
EXPECT_TRUE((type_equals<double*, remove_reference<double*>::type>::value));
}
#if GTEST_HAS_STREAM_REDIRECTION
// Verifies that Log() behaves correctly for the given verbosity level
// and log severity.
std::string GrabOutput(void(*logger)(), const char* verbosity) {
@ -583,7 +529,7 @@ void ExpectCallLogger() {
DummyMock mock;
EXPECT_CALL(mock, TestMethod());
mock.TestMethod();
};
}
// Verifies that EXPECT_CALL logs if the --gmock_verbose flag is set to "info".
TEST(ExpectCallTest, LogsWhenVerbosityIsInfo) {
@ -606,7 +552,7 @@ TEST(ExpectCallTest, DoesNotLogWhenVerbosityIsError) {
void OnCallLogger() {
DummyMock mock;
ON_CALL(mock, TestMethod());
};
}
// Verifies that ON_CALL logs if the --gmock_verbose flag is set to "info".
TEST(OnCallTest, LogsWhenVerbosityIsInfo) {
@ -686,22 +632,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<std::shared_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]);
@ -712,6 +661,73 @@ TEST(StlContainerViewTest, WorksForDynamicNativeArray) {
EXPECT_EQ(0, a3.begin()[0]);
}
// Tests the Function template struct.
TEST(FunctionTest, Nullary) {
typedef Function<int()> F; // NOLINT
EXPECT_EQ(0u, F::ArgumentCount);
EXPECT_TRUE((std::is_same<int, F::Result>::value));
EXPECT_TRUE((std::is_same<std::tuple<>, F::ArgumentTuple>::value));
EXPECT_TRUE((std::is_same<std::tuple<>, F::ArgumentMatcherTuple>::value));
EXPECT_TRUE((std::is_same<void(), F::MakeResultVoid>::value));
EXPECT_TRUE((std::is_same<IgnoredValue(), F::MakeResultIgnoredValue>::value));
}
TEST(FunctionTest, Unary) {
typedef Function<int(bool)> F; // NOLINT
EXPECT_EQ(1u, F::ArgumentCount);
EXPECT_TRUE((std::is_same<int, F::Result>::value));
EXPECT_TRUE((std::is_same<bool, F::Arg<0>::type>::value));
EXPECT_TRUE((std::is_same<std::tuple<bool>, F::ArgumentTuple>::value));
EXPECT_TRUE((
std::is_same<std::tuple<Matcher<bool>>, F::ArgumentMatcherTuple>::value));
EXPECT_TRUE((std::is_same<void(bool), F::MakeResultVoid>::value)); // NOLINT
EXPECT_TRUE((std::is_same<IgnoredValue(bool), // NOLINT
F::MakeResultIgnoredValue>::value));
}
TEST(FunctionTest, Binary) {
typedef Function<int(bool, const long&)> F; // NOLINT
EXPECT_EQ(2u, F::ArgumentCount);
EXPECT_TRUE((std::is_same<int, F::Result>::value));
EXPECT_TRUE((std::is_same<bool, F::Arg<0>::type>::value));
EXPECT_TRUE((std::is_same<const long&, F::Arg<1>::type>::value)); // NOLINT
EXPECT_TRUE((std::is_same<std::tuple<bool, const long&>, // NOLINT
F::ArgumentTuple>::value));
EXPECT_TRUE(
(std::is_same<std::tuple<Matcher<bool>, Matcher<const long&>>, // NOLINT
F::ArgumentMatcherTuple>::value));
EXPECT_TRUE((std::is_same<void(bool, const long&), // NOLINT
F::MakeResultVoid>::value));
EXPECT_TRUE((std::is_same<IgnoredValue(bool, const long&), // NOLINT
F::MakeResultIgnoredValue>::value));
}
TEST(FunctionTest, LongArgumentList) {
typedef Function<char(bool, int, char*, int&, const long&)> F; // NOLINT
EXPECT_EQ(5u, F::ArgumentCount);
EXPECT_TRUE((std::is_same<char, F::Result>::value));
EXPECT_TRUE((std::is_same<bool, F::Arg<0>::type>::value));
EXPECT_TRUE((std::is_same<int, F::Arg<1>::type>::value));
EXPECT_TRUE((std::is_same<char*, F::Arg<2>::type>::value));
EXPECT_TRUE((std::is_same<int&, F::Arg<3>::type>::value));
EXPECT_TRUE((std::is_same<const long&, F::Arg<4>::type>::value)); // NOLINT
EXPECT_TRUE(
(std::is_same<std::tuple<bool, int, char*, int&, const long&>, // NOLINT
F::ArgumentTuple>::value));
EXPECT_TRUE(
(std::is_same<
std::tuple<Matcher<bool>, Matcher<int>, Matcher<char*>, Matcher<int&>,
Matcher<const long&>>, // NOLINT
F::ArgumentMatcherTuple>::value));
EXPECT_TRUE(
(std::is_same<void(bool, int, char*, int&, const long&), // NOLINT
F::MakeResultVoid>::value));
EXPECT_TRUE((
std::is_same<IgnoredValue(bool, int, char*, int&, const long&), // NOLINT
F::MakeResultIgnoredValue>::value));
}
} // namespace
} // namespace internal
} // namespace testing

File diff suppressed because it is too large Load Diff

View File

@ -35,21 +35,17 @@
#include "gmock/gmock-more-actions.h"
#include <functional>
#include <memory>
#include <sstream>
#include <string>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "gtest/internal/gtest-linked_ptr.h"
namespace testing {
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;
@ -61,11 +57,9 @@ using testing::ReturnPointee;
using testing::SaveArg;
using testing::SaveArgPointee;
using testing::SetArgReferee;
using testing::StaticAssertTypeEq;
using testing::Unused;
using testing::WithArg;
using testing::WithoutArgs;
using testing::internal::linked_ptr;
// For suppressing compiler warnings on conversion possibly losing precision.
inline short Short(short n) { return n; } // NOLINT
@ -232,45 +226,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
@ -283,9 +278,9 @@ TEST(InvokeTest, FunctionThatTakes7Arguments) {
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.
@ -294,9 +289,9 @@ TEST(InvokeTest, FunctionThatTakes8Arguments) {
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.
@ -305,10 +300,10 @@ TEST(InvokeTest, FunctionThatTakes9Arguments) {
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"))));
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.
@ -318,45 +313,46 @@ TEST(InvokeTest, FunctionThatTakes10Arguments) {
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 std::string&)> a1 = Invoke(SumOfFirst2);
tuple<int, int, double, std::string> dummy =
make_tuple(10, 2, 5.6, std::string("hi"));
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(std::string, bool, int, int)> a1 = Invoke(&foo, &Foo::SumOfLast2);
EXPECT_EQ(12, a1.Perform(make_tuple(CharPtr("hi"), true, 10, 2)));
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.
@ -365,14 +361,14 @@ 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.
@ -380,7 +376,7 @@ TEST(InvokeMethodTest, Binary) {
Foo foo;
Action<std::string(const std::string&, char)> a = Invoke(&foo, &Foo::Binary);
std::string s("Hell");
tuple<std::string, char> dummy = make_tuple(s, 'o');
std::tuple<std::string, char> dummy = std::make_tuple(s, 'o');
EXPECT_EQ("Hello", a.Perform(dummy));
}
@ -388,21 +384,21 @@ TEST(InvokeMethodTest, Binary) {
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.
@ -410,7 +406,8 @@ 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.
@ -420,9 +417,9 @@ TEST(InvokeMethodTest, MethodThatTakes7Arguments) {
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.
@ -432,9 +429,9 @@ TEST(InvokeMethodTest, MethodThatTakes8Arguments) {
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.
@ -444,10 +441,10 @@ TEST(InvokeMethodTest, MethodThatTakes9Arguments) {
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"))));
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.
@ -458,10 +455,10 @@ TEST(InvokeMethodTest, MethodThatTakes10Arguments) {
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.
@ -469,48 +466,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<std::string(int, int, std::string, int)> a = ReturnArg<2>();
EXPECT_EQ("seven", a.Perform(make_tuple(5, 6, std::string("seven"), 8)));
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);
}
@ -518,7 +515,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);
}
@ -526,36 +523,28 @@ 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);
}
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));
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);
}
@ -582,7 +571,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);
}
@ -592,7 +581,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);
}
@ -600,19 +589,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
@ -628,7 +617,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]);
@ -643,7 +632,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]);
@ -662,7 +651,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]);
@ -678,7 +667,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]);
@ -692,17 +681,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

View File

@ -27,8 +27,7 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "gmock/gmock-generated-nice-strict.h"
#include "gmock/gmock-nice-strict.h"
#include <string>
#include <utility>
@ -114,23 +113,22 @@ class MockBar {
GTEST_DISALLOW_COPY_AND_ASSIGN_(MockBar);
};
#if GTEST_GTEST_LANG_CXX11
class MockBaz {
public:
class MoveOnly {
public:
MoveOnly() = default;
MoveOnly(const MoveOnly&) = delete;
operator=(const MoveOnly&) = delete;
MoveOnly& operator=(const MoveOnly&) = delete;
MoveOnly(MoveOnly&&) = default;
operator=(MoveOnly&&) = default;
MoveOnly& operator=(MoveOnly&&) = default;
};
MockBaz(MoveOnly) {}
}
#endif // GTEST_GTEST_LANG_CXX11 && GTEST_HAS_STD_MOVE_
};
#if GTEST_HAS_STREAM_REDIRECTION
@ -184,6 +182,13 @@ TEST(RawMockTest, InfoForUninterestingCall) {
GMOCK_FLAG(verbose) = saved_flag;
}
TEST(RawMockTest, IsNaggy_IsNice_IsStrict) {
MockFoo raw_foo;
EXPECT_TRUE(Mock::IsNaggy(&raw_foo));
EXPECT_FALSE(Mock::IsNice(&raw_foo));
EXPECT_FALSE(Mock::IsStrict(&raw_foo));
}
// Tests that a nice mock generates no warning for uninteresting calls.
TEST(NiceMockTest, NoWarningForUninterestingCall) {
NiceMock<MockFoo> nice_foo;
@ -285,29 +290,24 @@ TEST(NiceMockTest, AllowLeak) {
leaked->DoThis();
}
#if GTEST_GTEST_LANG_CXX11 && GTEST_HAS_STD_MOVE_
TEST(NiceMockTest, MoveOnlyConstructor) {
NiceMock<MockBaz> nice_baz(MockBaz::MoveOnly());
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
// MSVC 8.0 bug that caused the symbol Mock used in the definition of
// NiceMock to be looked up in the wrong context, and this test
// ensures that our fix works.
//
// We have to skip this test on Symbian and Windows Mobile, as it
// causes the program to crash there, for reasons unclear to us yet.
// class (as opposed to ::testing::Mock).
TEST(NiceMockTest, AcceptsClassNamedMock) {
NiceMock< ::Mock> nice;
EXPECT_CALL(nice, DoThis());
nice.DoThis();
}
#endif // !GTEST_OS_SYMBIAN && !GTEST_OS_WINDOWS_MOBILE
TEST(NiceMockTest, IsNaggy_IsNice_IsStrict) {
NiceMock<MockFoo> nice_foo;
EXPECT_FALSE(Mock::IsNaggy(&nice_foo));
EXPECT_TRUE(Mock::IsNice(&nice_foo));
EXPECT_FALSE(Mock::IsStrict(&nice_foo));
}
#if GTEST_HAS_STREAM_REDIRECTION
@ -393,29 +393,24 @@ TEST(NaggyMockTest, AllowLeak) {
leaked->DoThis();
}
#if GTEST_GTEST_LANG_CXX11 && GTEST_HAS_STD_MOVE_
TEST(NaggyMockTest, MoveOnlyConstructor) {
NaggyMock<MockBaz> naggy_baz(MockBaz::MoveOnly());
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
// MSVC 8.0 bug that caused the symbol Mock used in the definition of
// NaggyMock to be looked up in the wrong context, and this test
// ensures that our fix works.
//
// We have to skip this test on Symbian and Windows Mobile, as it
// causes the program to crash there, for reasons unclear to us yet.
// class (as opposed to ::testing::Mock).
TEST(NaggyMockTest, AcceptsClassNamedMock) {
NaggyMock< ::Mock> naggy;
EXPECT_CALL(naggy, DoThis());
naggy.DoThis();
}
#endif // !GTEST_OS_SYMBIAN && !GTEST_OS_WINDOWS_MOBILE
TEST(NaggyMockTest, IsNaggy_IsNice_IsStrict) {
NaggyMock<MockFoo> naggy_foo;
EXPECT_TRUE(Mock::IsNaggy(&naggy_foo));
EXPECT_FALSE(Mock::IsNice(&naggy_foo));
EXPECT_FALSE(Mock::IsStrict(&naggy_foo));
}
// Tests that a strict mock allows expected calls.
TEST(StrictMockTest, AllowsExpectedCall) {
@ -482,29 +477,24 @@ TEST(StrictMockTest, AllowLeak) {
leaked->DoThis();
}
#if GTEST_GTEST_LANG_CXX11 && GTEST_HAS_STD_MOVE_
TEST(StrictMockTest, MoveOnlyConstructor) {
StrictMock<MockBaz> strict_baz(MockBaz::MoveOnly());
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
// MSVC 8.0 bug that caused the symbol Mock used in the definition of
// StrictMock to be looked up in the wrong context, and this test
// ensures that our fix works.
//
// We have to skip this test on Symbian and Windows Mobile, as it
// causes the program to crash there, for reasons unclear to us yet.
// class (as opposed to ::testing::Mock).
TEST(StrictMockTest, AcceptsClassNamedMock) {
StrictMock< ::Mock> strict;
EXPECT_CALL(strict, DoThis());
strict.DoThis();
}
#endif // !GTEST_OS_SYMBIAN && !GTEST_OS_WINDOWS_MOBILE
TEST(StrictMockTest, IsNaggy_IsNice_IsStrict) {
StrictMock<MockFoo> strict_foo;
EXPECT_FALSE(Mock::IsNaggy(&strict_foo));
EXPECT_FALSE(Mock::IsNice(&strict_foo));
EXPECT_TRUE(Mock::IsStrict(&strict_foo));
}
} // namespace gmock_nice_strict_test
} // namespace testing

View File

@ -0,0 +1,206 @@
// Copyright 2018, 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.
// Google Mock - a framework for writing C++ mock classes.
//
// This file tests the internal preprocessor macro library.
#include "gmock/internal/gmock-pp.h"
#include <string>
#include "gmock/gmock.h"
namespace testing {
namespace {
// Matcher to verify that to strings are identical up to whitespace
// Not 100% correct, because it treats "AB" as equal to "A B".
::testing::Matcher<const std::string&> SameExceptSpaces(const std::string& s) {
auto remove_spaces = [](std::string to_split) {
to_split.erase(std::remove(to_split.begin(), to_split.end(), ' '),
to_split.end());
return to_split;
};
return ::testing::ResultOf(remove_spaces, remove_spaces(s));
}
// Verify that a macro expands to a given text. Ignores whitespace difference.
// In MSVC, GMOCK_PP_STRINGIZE() returns nothing, rather than "". So concatenate
// with an empty string.
#define EXPECT_EXPANSION(Result, Macro) \
EXPECT_THAT("" GMOCK_PP_STRINGIZE(Macro), SameExceptSpaces(Result))
TEST(Macros, Cat) {
EXPECT_EXPANSION("14", GMOCK_PP_CAT(1, 4));
EXPECT_EXPANSION("+=", GMOCK_PP_CAT(+, =));
}
TEST(Macros, Narg) {
EXPECT_EXPANSION("1", GMOCK_PP_NARG());
EXPECT_EXPANSION("1", GMOCK_PP_NARG(x));
EXPECT_EXPANSION("2", GMOCK_PP_NARG(x, y));
EXPECT_EXPANSION("3", GMOCK_PP_NARG(x, y, z));
EXPECT_EXPANSION("4", GMOCK_PP_NARG(x, y, z, w));
EXPECT_EXPANSION("0", GMOCK_PP_NARG0());
EXPECT_EXPANSION("1", GMOCK_PP_NARG0(x));
EXPECT_EXPANSION("2", GMOCK_PP_NARG0(x, y));
}
TEST(Macros, Comma) {
EXPECT_EXPANSION("0", GMOCK_PP_HAS_COMMA());
EXPECT_EXPANSION("1", GMOCK_PP_HAS_COMMA(, ));
EXPECT_EXPANSION("0", GMOCK_PP_HAS_COMMA((, )));
}
TEST(Macros, IsEmpty) {
EXPECT_EXPANSION("1", GMOCK_PP_IS_EMPTY());
EXPECT_EXPANSION("0", GMOCK_PP_IS_EMPTY(, ));
EXPECT_EXPANSION("0", GMOCK_PP_IS_EMPTY(a));
EXPECT_EXPANSION("0", GMOCK_PP_IS_EMPTY(()));
#define GMOCK_PP_INTERNAL_IS_EMPTY_TEST_1
EXPECT_EXPANSION("1", GMOCK_PP_IS_EMPTY(GMOCK_PP_INTERNAL_IS_EMPTY_TEST_1));
}
TEST(Macros, If) {
EXPECT_EXPANSION("1", GMOCK_PP_IF(1, 1, 2));
EXPECT_EXPANSION("2", GMOCK_PP_IF(0, 1, 2));
}
TEST(Macros, HeadTail) {
EXPECT_EXPANSION("1", GMOCK_PP_HEAD(1));
EXPECT_EXPANSION("1", GMOCK_PP_HEAD(1, 2));
EXPECT_EXPANSION("1", GMOCK_PP_HEAD(1, 2, 3));
EXPECT_EXPANSION("", GMOCK_PP_TAIL(1));
EXPECT_EXPANSION("2", GMOCK_PP_TAIL(1, 2));
EXPECT_EXPANSION("2", GMOCK_PP_HEAD(GMOCK_PP_TAIL(1, 2, 3)));
}
TEST(Macros, Parentheses) {
EXPECT_EXPANSION("0", GMOCK_PP_IS_BEGIN_PARENS(sss));
EXPECT_EXPANSION("0", GMOCK_PP_IS_BEGIN_PARENS(sss()));
EXPECT_EXPANSION("0", GMOCK_PP_IS_BEGIN_PARENS(sss() sss));
EXPECT_EXPANSION("1", GMOCK_PP_IS_BEGIN_PARENS((sss)));
EXPECT_EXPANSION("1", GMOCK_PP_IS_BEGIN_PARENS((sss)ss));
EXPECT_EXPANSION("0", GMOCK_PP_IS_ENCLOSED_PARENS(sss));
EXPECT_EXPANSION("0", GMOCK_PP_IS_ENCLOSED_PARENS(sss()));
EXPECT_EXPANSION("0", GMOCK_PP_IS_ENCLOSED_PARENS(sss() sss));
EXPECT_EXPANSION("1", GMOCK_PP_IS_ENCLOSED_PARENS((sss)));
EXPECT_EXPANSION("0", GMOCK_PP_IS_ENCLOSED_PARENS((sss)ss));
EXPECT_EXPANSION("1 + 1", GMOCK_PP_REMOVE_PARENS((1 + 1)));
}
TEST(Macros, Increment) {
EXPECT_EXPANSION("1", GMOCK_PP_INC(0));
EXPECT_EXPANSION("2", GMOCK_PP_INC(1));
EXPECT_EXPANSION("3", GMOCK_PP_INC(2));
EXPECT_EXPANSION("4", GMOCK_PP_INC(3));
EXPECT_EXPANSION("5", GMOCK_PP_INC(4));
EXPECT_EXPANSION("16", GMOCK_PP_INC(15));
}
#define JOINER_CAT(a, b) a##b
#define JOINER(_N, _Data, _Elem) JOINER_CAT(_Data, _N) = _Elem
TEST(Macros, Repeat) {
EXPECT_EXPANSION("", GMOCK_PP_REPEAT(JOINER, X, 0));
EXPECT_EXPANSION("X0=", GMOCK_PP_REPEAT(JOINER, X, 1));
EXPECT_EXPANSION("X0= X1=", GMOCK_PP_REPEAT(JOINER, X, 2));
EXPECT_EXPANSION("X0= X1= X2=", GMOCK_PP_REPEAT(JOINER, X, 3));
EXPECT_EXPANSION("X0= X1= X2= X3=", GMOCK_PP_REPEAT(JOINER, X, 4));
EXPECT_EXPANSION("X0= X1= X2= X3= X4=", GMOCK_PP_REPEAT(JOINER, X, 5));
EXPECT_EXPANSION("X0= X1= X2= X3= X4= X5=", GMOCK_PP_REPEAT(JOINER, X, 6));
EXPECT_EXPANSION("X0= X1= X2= X3= X4= X5= X6=",
GMOCK_PP_REPEAT(JOINER, X, 7));
EXPECT_EXPANSION("X0= X1= X2= X3= X4= X5= X6= X7=",
GMOCK_PP_REPEAT(JOINER, X, 8));
EXPECT_EXPANSION("X0= X1= X2= X3= X4= X5= X6= X7= X8=",
GMOCK_PP_REPEAT(JOINER, X, 9));
EXPECT_EXPANSION("X0= X1= X2= X3= X4= X5= X6= X7= X8= X9=",
GMOCK_PP_REPEAT(JOINER, X, 10));
EXPECT_EXPANSION("X0= X1= X2= X3= X4= X5= X6= X7= X8= X9= X10=",
GMOCK_PP_REPEAT(JOINER, X, 11));
EXPECT_EXPANSION("X0= X1= X2= X3= X4= X5= X6= X7= X8= X9= X10= X11=",
GMOCK_PP_REPEAT(JOINER, X, 12));
EXPECT_EXPANSION("X0= X1= X2= X3= X4= X5= X6= X7= X8= X9= X10= X11= X12=",
GMOCK_PP_REPEAT(JOINER, X, 13));
EXPECT_EXPANSION(
"X0= X1= X2= X3= X4= X5= X6= X7= X8= X9= X10= X11= X12= X13=",
GMOCK_PP_REPEAT(JOINER, X, 14));
EXPECT_EXPANSION(
"X0= X1= X2= X3= X4= X5= X6= X7= X8= X9= X10= X11= X12= X13= X14=",
GMOCK_PP_REPEAT(JOINER, X, 15));
}
TEST(Macros, ForEach) {
EXPECT_EXPANSION("", GMOCK_PP_FOR_EACH(JOINER, X, ()));
EXPECT_EXPANSION("X0=a", GMOCK_PP_FOR_EACH(JOINER, X, (a)));
EXPECT_EXPANSION("X0=a X1=b", GMOCK_PP_FOR_EACH(JOINER, X, (a, b)));
EXPECT_EXPANSION("X0=a X1=b X2=c", GMOCK_PP_FOR_EACH(JOINER, X, (a, b, c)));
EXPECT_EXPANSION("X0=a X1=b X2=c X3=d",
GMOCK_PP_FOR_EACH(JOINER, X, (a, b, c, d)));
EXPECT_EXPANSION("X0=a X1=b X2=c X3=d X4=e",
GMOCK_PP_FOR_EACH(JOINER, X, (a, b, c, d, e)));
EXPECT_EXPANSION("X0=a X1=b X2=c X3=d X4=e X5=f",
GMOCK_PP_FOR_EACH(JOINER, X, (a, b, c, d, e, f)));
EXPECT_EXPANSION("X0=a X1=b X2=c X3=d X4=e X5=f X6=g",
GMOCK_PP_FOR_EACH(JOINER, X, (a, b, c, d, e, f, g)));
EXPECT_EXPANSION("X0=a X1=b X2=c X3=d X4=e X5=f X6=g X7=h",
GMOCK_PP_FOR_EACH(JOINER, X, (a, b, c, d, e, f, g, h)));
EXPECT_EXPANSION("X0=a X1=b X2=c X3=d X4=e X5=f X6=g X7=h X8=i",
GMOCK_PP_FOR_EACH(JOINER, X, (a, b, c, d, e, f, g, h, i)));
EXPECT_EXPANSION(
"X0=a X1=b X2=c X3=d X4=e X5=f X6=g X7=h X8=i X9=j",
GMOCK_PP_FOR_EACH(JOINER, X, (a, b, c, d, e, f, g, h, i, j)));
EXPECT_EXPANSION(
"X0=a X1=b X2=c X3=d X4=e X5=f X6=g X7=h X8=i X9=j X10=k",
GMOCK_PP_FOR_EACH(JOINER, X, (a, b, c, d, e, f, g, h, i, j, k)));
EXPECT_EXPANSION(
"X0=a X1=b X2=c X3=d X4=e X5=f X6=g X7=h X8=i X9=j X10=k X11=l",
GMOCK_PP_FOR_EACH(JOINER, X, (a, b, c, d, e, f, g, h, i, j, k, l)));
EXPECT_EXPANSION(
"X0=a X1=b X2=c X3=d X4=e X5=f X6=g X7=h X8=i X9=j X10=k X11=l X12=m",
GMOCK_PP_FOR_EACH(JOINER, X, (a, b, c, d, e, f, g, h, i, j, k, l, m)));
EXPECT_EXPANSION(
"X0=a X1=b X2=c X3=d X4=e X5=f X6=g X7=h X8=i X9=j X10=k X11=l X12=m "
"X13=n",
GMOCK_PP_FOR_EACH(JOINER, X, (a, b, c, d, e, f, g, h, i, j, k, l, m, n)));
EXPECT_EXPANSION(
"X0=a X1=b X2=c X3=d X4=e X5=f X6=g X7=h X8=i X9=j X10=k X11=l X12=m "
"X13=n X14=o",
GMOCK_PP_FOR_EACH(JOINER, X,
(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o)));
}
} // namespace
} // namespace testing

View File

@ -0,0 +1,73 @@
#include "gmock/internal/gmock-pp.h"
// Static assertions.
namespace testing {
namespace internal {
namespace gmockpp {
static_assert(GMOCK_PP_CAT(1, 4) == 14, "");
static_assert(GMOCK_PP_INTERNAL_INTERNAL_16TH(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
12, 13, 14, 15, 16, 17, 18) == 16,
"");
static_assert(GMOCK_PP_NARG() == 1, "");
static_assert(GMOCK_PP_NARG(x) == 1, "");
static_assert(GMOCK_PP_NARG(x, y) == 2, "");
static_assert(GMOCK_PP_NARG(x, y, z) == 3, "");
static_assert(GMOCK_PP_NARG(x, y, z, w) == 4, "");
static_assert(!GMOCK_PP_HAS_COMMA(), "");
static_assert(GMOCK_PP_HAS_COMMA(b, ), "");
static_assert(!GMOCK_PP_HAS_COMMA((, )), "");
static_assert(!GMOCK_PP_IS_EMPTY(, ), "");
static_assert(!GMOCK_PP_IS_EMPTY(a), "");
static_assert(!GMOCK_PP_IS_EMPTY(()), "");
static_assert(GMOCK_PP_IF(1, 1, 2) == 1, "");
static_assert(GMOCK_PP_IF(0, 1, 2) == 2, "");
static_assert(GMOCK_PP_NARG0(x) == 1, "");
static_assert(GMOCK_PP_NARG0(x, y) == 2, "");
static_assert(GMOCK_PP_HEAD(1) == 1, "");
static_assert(GMOCK_PP_HEAD(1, 2) == 1, "");
static_assert(GMOCK_PP_HEAD(1, 2, 3) == 1, "");
static_assert(GMOCK_PP_TAIL(1, 2) == 2, "");
static_assert(GMOCK_PP_HEAD(GMOCK_PP_TAIL(1, 2, 3)) == 2, "");
static_assert(!GMOCK_PP_IS_BEGIN_PARENS(sss), "");
static_assert(!GMOCK_PP_IS_BEGIN_PARENS(sss()), "");
static_assert(!GMOCK_PP_IS_BEGIN_PARENS(sss() sss), "");
static_assert(GMOCK_PP_IS_BEGIN_PARENS((sss)), "");
static_assert(GMOCK_PP_IS_BEGIN_PARENS((sss)ss), "");
static_assert(!GMOCK_PP_IS_ENCLOSED_PARENS(sss), "");
static_assert(!GMOCK_PP_IS_ENCLOSED_PARENS(sss()), "");
static_assert(!GMOCK_PP_IS_ENCLOSED_PARENS(sss() sss), "");
static_assert(!GMOCK_PP_IS_ENCLOSED_PARENS((sss)ss), "");
static_assert(GMOCK_PP_REMOVE_PARENS((1 + 1)) * 2 == 3, "");
static_assert(GMOCK_PP_INC(4) == 5, "");
template <class... Args>
struct Test {
static constexpr int kArgs = sizeof...(Args);
};
#define GMOCK_PP_INTERNAL_TYPE_TEST(_i, _Data, _element) \
GMOCK_PP_COMMA_IF(_i) _element
static_assert(Test<GMOCK_PP_FOR_EACH(GMOCK_PP_INTERNAL_TYPE_TEST, ~,
(int, float, double, char))>::kArgs == 4,
"");
#define GMOCK_PP_INTERNAL_VAR_TEST_1(_x) 1
#define GMOCK_PP_INTERNAL_VAR_TEST_2(_x, _y) 2
#define GMOCK_PP_INTERNAL_VAR_TEST_3(_x, _y, _z) 3
#define GMOCK_PP_INTERNAL_VAR_TEST(...) \
GMOCK_PP_VARIADIC_CALL(GMOCK_PP_INTERNAL_VAR_TEST_, __VA_ARGS__)
static_assert(GMOCK_PP_INTERNAL_VAR_TEST(x, y) == 2, "");
static_assert(GMOCK_PP_INTERNAL_VAR_TEST(silly) == 1, "");
static_assert(GMOCK_PP_INTERNAL_VAR_TEST(x, y, z) == 3, "");
// TODO(iserna): The following asserts fail in --config=lexan.
#define GMOCK_PP_INTERNAL_IS_EMPTY_TEST_1
static_assert(GMOCK_PP_IS_EMPTY(GMOCK_PP_INTERNAL_IS_EMPTY_TEST_1), "");
static_assert(GMOCK_PP_IS_EMPTY(), "");
static_assert(GMOCK_PP_IS_ENCLOSED_PARENS((sss)), "");
static_assert(GMOCK_PP_IS_EMPTY(GMOCK_PP_TAIL(1)), "");
static_assert(GMOCK_PP_NARG0() == 0, "");
} // namespace gmockpp
} // namespace internal
} // namespace testing

View File

@ -34,6 +34,7 @@
#include "gmock/gmock-spec-builders.h"
#include <memory>
#include <ostream> // NOLINT
#include <sstream>
#include <string>
@ -77,6 +78,7 @@ using testing::Expectation;
using testing::ExpectationSet;
using testing::GMOCK_FLAG(verbose);
using testing::Gt;
using testing::IgnoreResult;
using testing::InSequence;
using testing::Invoke;
using testing::InvokeWithoutArgs;
@ -99,7 +101,6 @@ using testing::internal::kFail;
using testing::internal::kInfoVerbosity;
using testing::internal::kWarn;
using testing::internal::kWarningVerbosity;
using testing::internal::linked_ptr;
#if GTEST_HAS_STREAM_REDIRECTION
using testing::HasSubstr;
@ -172,7 +173,7 @@ class ReferenceHoldingMock {
public:
ReferenceHoldingMock() {}
MOCK_METHOD1(AcceptReference, void(linked_ptr<MockA>*));
MOCK_METHOD1(AcceptReference, void(std::shared_ptr<MockA>*));
private:
GTEST_DISALLOW_COPY_AND_ASSIGN_(ReferenceHoldingMock);
@ -1951,18 +1952,20 @@ TEST(DeletingMockEarlyTest, Failure2) {
class EvenNumberCardinality : public CardinalityInterface {
public:
// Returns true iff call_count calls will satisfy this cardinality.
virtual bool IsSatisfiedByCallCount(int call_count) const {
// Returns true if and only if call_count calls will satisfy this
// cardinality.
bool IsSatisfiedByCallCount(int call_count) const override {
return call_count % 2 == 0;
}
// Returns true iff call_count calls will saturate this cardinality.
virtual bool IsSaturatedByCallCount(int /* call_count */) const {
// Returns true if and only if call_count calls will saturate this
// cardinality.
bool IsSaturatedByCallCount(int /* call_count */) const override {
return false;
}
// Describes self to an ostream.
virtual void DescribeTo(::std::ostream* os) const {
void DescribeTo(::std::ostream* os) const override {
*os << "called even number of times";
}
};
@ -2023,7 +2026,9 @@ class VerboseFlagPreservingFixture : public testing::Test {
VerboseFlagPreservingFixture()
: saved_verbose_flag_(GMOCK_FLAG(verbose)) {}
~VerboseFlagPreservingFixture() { GMOCK_FLAG(verbose) = saved_verbose_flag_; }
~VerboseFlagPreservingFixture() override {
GMOCK_FLAG(verbose) = saved_verbose_flag_;
}
private:
const std::string saved_verbose_flag_;
@ -2041,7 +2046,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);
@ -2055,7 +2060,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);
@ -2098,7 +2103,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(
@ -2175,7 +2180,7 @@ class GMockVerboseFlagTest : public VerboseFlagPreservingFixture {
"an EXPECT_CALL() if you don't mean to enforce the call. "
"See "
"https://github.com/google/googletest/blob/master/googlemock/docs/"
"CookBook.md#"
"cook_book.md#"
"knowing-when-to-expect for details.";
// A void-returning function.
@ -2619,7 +2624,7 @@ TEST(VerifyAndClearTest, DoesNotAffectOtherMockObjects) {
TEST(VerifyAndClearTest,
DestroyingChainedMocksDoesNotDeadlockThroughExpectations) {
linked_ptr<MockA> a(new MockA);
std::shared_ptr<MockA> a(new MockA);
ReferenceHoldingMock test_mock;
// EXPECT_CALL stores a reference to a inside test_mock.
@ -2639,7 +2644,7 @@ TEST(VerifyAndClearTest,
TEST(VerifyAndClearTest,
DestroyingChainedMocksDoesNotDeadlockThroughDefaultAction) {
linked_ptr<MockA> a(new MockA);
std::shared_ptr<MockA> a(new MockA);
ReferenceHoldingMock test_mock;
// ON_CALL stores a reference to a inside test_mock.

View File

@ -39,7 +39,6 @@
#include "test/gmock-cardinalities_test.cc"
#include "test/gmock-generated-actions_test.cc"
#include "test/gmock-generated-function-mockers_test.cc"
#include "test/gmock-generated-internal-utils_test.cc"
#include "test/gmock-generated-matchers_test.cc"
#include "test/gmock-internal-utils_test.cc"
#include "test/gmock-matchers_test.cc"

View File

@ -248,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.
@ -257,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.
@ -265,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.
@ -274,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.
@ -283,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.
@ -314,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;
}
@ -328,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.
@ -341,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.
@ -360,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.
@ -369,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.
@ -377,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.
@ -405,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
@ -414,7 +414,7 @@ TEST(LinkTest, TestThrow) {
Mock mock;
EXPECT_CALL(mock, VoidFromString(_)).WillOnce(Throw(42));
EXPECT_THROW(mock.VoidFromString(NULL), int);
EXPECT_THROW(mock.VoidFromString(nullptr), int);
}
#endif // GTEST_HAS_EXCEPTIONS
@ -437,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.
@ -449,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.
@ -646,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.
@ -660,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.
@ -684,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_

View File

@ -39,6 +39,7 @@ gmock_output_test.py
"""
from io import open # pylint: disable=redefined-builtin, g-importing-member
import os
import re
import sys
@ -152,10 +153,11 @@ def GetNormalizedCommandOutputAndLeakyTests(cmd):
class GMockOutputTest(gmock_test_utils.TestCase):
def testOutput(self):
(output, leaky_tests) = GetNormalizedCommandOutputAndLeakyTests(COMMAND)
golden_file = open(GOLDEN_PATH, 'rb')
golden = golden_file.read()
golden = golden_file.read().decode('utf-8')
golden_file.close()
# The normalized output should match the golden file.

View File

@ -75,14 +75,14 @@ GMOCK WARNING:
Uninteresting mock function call - returning default value.
Function call: Bar2(0, 1)
Returns: false
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#knowing-when-to-expect for details.
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/cook_book.md#knowing-when-to-expect for details.
[ OK ] GMockOutputTest.UninterestingCall
[ RUN ] GMockOutputTest.UninterestingCallToVoidFunction
GMOCK WARNING:
Uninteresting mock function call - returning directly.
Function call: Bar3(0, 1)
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#knowing-when-to-expect for details.
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/cook_book.md#knowing-when-to-expect for details.
[ OK ] GMockOutputTest.UninterestingCallToVoidFunction
[ RUN ] GMockOutputTest.RetiredExpectation
unknown file: Failure
@ -266,14 +266,14 @@ Uninteresting mock function call - taking default action specified at:
FILE:#:
Function call: Bar2(2, 2)
Returns: true
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#knowing-when-to-expect for details.
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/cook_book.md#knowing-when-to-expect for details.
GMOCK WARNING:
Uninteresting mock function call - taking default action specified at:
FILE:#:
Function call: Bar2(1, 1)
Returns: false
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#knowing-when-to-expect for details.
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/cook_book.md#knowing-when-to-expect for details.
[ OK ] GMockOutputTest.UninterestingCallWithDefaultAction
[ RUN ] GMockOutputTest.ExplicitActionsRunOutWithDefaultAction

Some files were not shown because too many files have changed in this diff Show More