Merge branch 'master' into cleanup-cmake

This commit is contained in:
Gennadiy Civil 2018-08-15 13:02:54 -07:00 committed by GitHub
commit 1246e5807a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
218 changed files with 8799 additions and 6648 deletions

14
.gitignore vendored
View File

@ -38,3 +38,17 @@ googletest/m4/lt~obsolete.m4
# Ignore generated directories.
googlemock/fused-src/
googletest/fused-src/
# macOS files
.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

View File

@ -1,5 +1,5 @@
# Build matrix / environment variable are explained on:
# http://about.travis-ci.org/docs/user/build-configuration/
# https://docs.travis-ci.com/user/customizing-the-build/
# This file can be validated on:
# http://lint.travis-ci.org/
@ -37,13 +37,15 @@ matrix:
group: deprecated-2017Q4
compiler: clang
env: BUILD_TYPE=Release VERBOSE=1 CXX_FLAGS=-std=c++11
- 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=Debug VERBOSE=1
- os: osx
compiler: gcc
env: BUILD_TYPE=Release VERBOSE=1 CXX_FLAGS=-std=c++11
if: type != pull_request
- os: osx
compiler: clang
env: BUILD_TYPE=Debug VERBOSE=1

View File

@ -38,7 +38,7 @@ licenses(["notice"])
config_setting(
name = "windows",
values = { "cpu": "x64_windows" },
values = {"cpu": "x64_windows"},
)
config_setting(
@ -51,7 +51,6 @@ config_setting(
values = {"define": "absl=1"},
)
# Google Test including Google Mock
cc_library(
name = "gtest",
@ -70,7 +69,7 @@ cc_library(
"googlemock/src/gmock_main.cc",
],
),
hdrs =glob([
hdrs = glob([
"googletest/include/gtest/*.h",
"googlemock/include/gmock/*.h",
]),
@ -81,6 +80,14 @@ cc_library(
"//conditions:default": ["-pthread"],
},
),
defines = select(
{
":has_absl": [
"GTEST_HAS_ABSL=1",
],
"//conditions:default": [],
},
),
includes = [
"googlemock",
"googlemock/include",
@ -94,21 +101,19 @@ cc_library(
"-pthread",
],
}),
defines = select ({
":has_absl": [
"GTEST_HAS_ABSL=1",
],
"//conditions:default": [],
}
),
deps = select ({
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/strings"
"@com_google_absl//absl/types:variant",
],
"//conditions:default": [],
}
)
},
),
)
cc_library(

View File

@ -4,6 +4,12 @@
[![Build Status](https://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.1 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)
Welcome to **Google Test**, Google's C++ test framework!
This repository is a merger of the formerly separate GoogleTest and
@ -16,7 +22,7 @@ also an IRC channel on [OFTC](https://webchat.oftc.net/) (irc.oftc.net) #gtest a
join us!
Getting started information for **Google Test** is available in the
[Google Test Primer](googletest/docs/Primer.md) documentation.
[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).

View File

@ -78,6 +78,11 @@ build_script:
throw "Exec: $ErrorMessage"
}
skip_commits:
files:
- '**/*.md'
test_script:
- ps: |
# Only enable some builds for pull requests, the AppVeyor queue is too long.

View File

@ -24,11 +24,19 @@ export MAKEFLAGS
env | sort
# Set default values to OFF for these variables if not specified.
: "${NO_EXCEPTION:=OFF}"
: "${NO_RTTI:=OFF}"
: "${COMPILER_IS_GNUCXX:=OFF}"
mkdir build || true
cd build
cmake -Dgtest_build_samples=ON \
-Dgtest_build_tests=ON \
-Dgmock_build_tests=ON \
-Dcxx_no_exception=$NO_EXCEPTION \
-Dcxx_no_rtti=$NO_RTTI \
-DCMAKE_COMPILER_IS_GNUCXX=$COMPILER_IS_GNUCXX \
-DCMAKE_CXX_FLAGS=$CXX_FLAGS \
-DCMAKE_BUILD_TYPE=$BUILD_TYPE \
..

View File

@ -138,13 +138,13 @@ if(INSTALL_GMOCK)
# configure and install pkgconfig files
configure_file(
cmake/gmock.pc.in
"${CMAKE_BINARY_DIR}/gmock.pc"
"${gmock_BINARY_DIR}/gmock.pc"
@ONLY)
configure_file(
cmake/gmock_main.pc.in
"${CMAKE_BINARY_DIR}/gmock_main.pc"
"${gmock_BINARY_DIR}/gmock_main.pc"
@ONLY)
install(FILES "${CMAKE_BINARY_DIR}/gmock.pc" "${CMAKE_BINARY_DIR}/gmock_main.pc"
install(FILES "${gmock_BINARY_DIR}/gmock.pc" "${gmock_BINARY_DIR}/gmock_main.pc"
DESTINATION "${CMAKE_INSTALL_LIBDIR}/pkgconfig")
endif()

View File

@ -53,7 +53,7 @@ the Apache License, which is different from Google Mock's license.
If you are new to the project, we suggest that you read the user
documentation in the following order:
* Learn the [basics](../../master/googletest/docs/Primer.md) of
* 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.

View File

@ -229,7 +229,7 @@ The `argument` can be either a C string or a C++ string object:
`ContainsRegex()` and `MatchesRegex()` use the regular expression
syntax defined
[here](../../googletest/docs/AdvancedGuide.md#regular-expression-syntax).
[here](../../googletest/docs/advanced.md#regular-expression-syntax).
`StrCaseEq()`, `StrCaseNe()`, `StrEq()`, and `StrNe()` work for wide
strings as well.
@ -349,7 +349,7 @@ You can make a matcher from one or more other matchers:
## Matchers as Test Assertions ##
|`ASSERT_THAT(expression, m)`|Generates a [fatal failure](../../googletest/docs/Primer.md#assertions) if the value of `expression` doesn't match matcher `m`.|
|`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`. |

View File

@ -2229,77 +2229,71 @@ versus
## Mocking Methods That Use Move-Only Types ##
C++11 introduced <em>move-only types</em>. A move-only-typed value can be moved from one object to another, but cannot be copied. `std::unique_ptr<T>` is probably the most commonly used move-only type.
C++11 introduced *move-only types*. A move-only-typed value can be moved from
one object to another, but cannot be copied. `std::unique_ptr<T>` is
probably the most commonly used move-only type.
Mocking a method that takes and/or returns move-only types presents some challenges, but nothing insurmountable. This recipe shows you how you can do it.
Mocking a method that takes and/or returns move-only types presents some
challenges, but nothing insurmountable. This recipe shows you how you can do it.
Note that the support for move-only method arguments was only introduced to
gMock in April 2017; in older code, you may find more complex
[workarounds](#LegacyMoveOnly) for lack of this feature.
Lets say we are working on a fictional project that lets one post and share snippets called “buzzes”. Your code uses these types:
Lets say we are working on a fictional project that lets one post and share
snippets called “buzzes”. Your code uses these types:
```
```cpp
enum class AccessLevel { kInternal, kPublic };
class Buzz {
public:
explicit Buzz(AccessLevel access) { }
explicit Buzz(AccessLevel access) { ... }
...
};
class Buzzer {
public:
virtual ~Buzzer() {}
virtual std::unique_ptr<Buzz> MakeBuzz(const std::string& text) = 0;
virtual bool ShareBuzz(std::unique_ptr<Buzz> buzz, Time timestamp) = 0;
virtual std::unique_ptr<Buzz> MakeBuzz(StringPiece text) = 0;
virtual bool ShareBuzz(std::unique_ptr<Buzz> buzz, int64_t timestamp) = 0;
...
};
```
A `Buzz` object represents a snippet being posted. A class that implements the `Buzzer` interface is capable of creating and sharing `Buzz`. Methods in `Buzzer` may return a `unique_ptr<Buzz>` or take a `unique_ptr<Buzz>`. Now we need to mock `Buzzer` in our tests.
A `Buzz` object represents a snippet being posted. A class that implements the
`Buzzer` interface is capable of creating and sharing `Buzz`es. Methods in
`Buzzer` may return a `unique_ptr<Buzz>` or take a
`unique_ptr<Buzz>`. Now we need to mock `Buzzer` in our tests.
To mock a method that returns a move-only type, you just use the familiar `MOCK_METHOD` syntax as usual:
To mock a method that accepts or returns move-only types, you just use the
familiar `MOCK_METHOD` syntax as usual:
```
```cpp
class MockBuzzer : public Buzzer {
public:
MOCK_METHOD1(MakeBuzz, std::unique_ptr<Buzz>(const std::string& text));
MOCK_METHOD1(MakeBuzz, std::unique_ptr<Buzz>(StringPiece text));
MOCK_METHOD2(ShareBuzz, bool(std::unique_ptr<Buzz> buzz, int64_t timestamp));
};
```
However, if you attempt to use the same `MOCK_METHOD` pattern to mock a method that takes a move-only parameter, youll get a compiler error currently:
Now that we have the mock class defined, we can use it in tests. In the
following code examples, we assume that we have defined a `MockBuzzer` object
named `mock_buzzer_`:
```
// Does NOT compile!
MOCK_METHOD2(ShareBuzz, bool(std::unique_ptr<Buzz> buzz, Time timestamp));
```
While its highly desirable to make this syntax just work, its not trivial and the work hasnt been done yet. Fortunately, there is a trick you can apply today to get something that works nearly as well as this.
The trick, is to delegate the `ShareBuzz()` method to a mock method (lets call it `DoShareBuzz()`) that does not take move-only parameters:
```
class MockBuzzer : public Buzzer {
public:
MOCK_METHOD1(MakeBuzz, std::unique_ptr<Buzz>(const std::string& text));
MOCK_METHOD2(DoShareBuzz, bool(Buzz* buzz, Time timestamp));
bool ShareBuzz(std::unique_ptr<Buzz> buzz, Time timestamp) {
return DoShareBuzz(buzz.get(), timestamp);
}
};
```
Note that there's no need to define or declare `DoShareBuzz()` in a base class. You only need to define it as a `MOCK_METHOD` in the mock class.
Now that we have the mock class defined, we can use it in tests. In the following code examples, we assume that we have defined a `MockBuzzer` object named `mock_buzzer_`:
```
```cpp
MockBuzzer mock_buzzer_;
```
First lets see how we can set expectations on the `MakeBuzz()` method, which returns a `unique_ptr<Buzz>`.
First lets see how we can set expectations on the `MakeBuzz()` method, which
returns a `unique_ptr<Buzz>`.
As usual, if you set an expectation without an action (i.e. the `.WillOnce()` or `.WillRepeated()` clause), when that expectation fires, the default action for that method will be taken. Since `unique_ptr<>` has a default constructor that returns a null `unique_ptr`, thats what youll get if you dont specify an action:
As usual, if you set an expectation without an action (i.e. the `.WillOnce()` or
`.WillRepeated()` clause), when that expectation fires, the default action for
that method will be taken. Since `unique_ptr<>` has a default constructor
that returns a null `unique_ptr`, thats what youll get if you dont specify an
action:
```
```cpp
// Use the default action.
EXPECT_CALL(mock_buzzer_, MakeBuzz("hello"));
@ -2307,32 +2301,13 @@ As usual, if you set an expectation without an action (i.e. the `.WillOnce()` or
EXPECT_EQ(nullptr, mock_buzzer_.MakeBuzz("hello"));
```
If you are not happy with the default action, you can tweak it. Depending on what you need, you may either tweak the default action for a specific (mock object, mock method) combination using `ON_CALL()`, or you may tweak the default action for all mock methods that return a specific type. The usage of `ON_CALL()` is similar to `EXPECT_CALL()`, so well skip it and just explain how to do the latter (tweaking the default action for a specific return type). You do this via the `DefaultValue<>::SetFactory()` and `DefaultValue<>::Clear()` API:
If you are not happy with the default action, you can tweak it as usual; see
[Setting Default Actions](#OnCall).
```
// 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); });
If you just need to return a pre-defined move-only value, you can use the
`Return(ByMove(...))` action:
// When this fires, the default action of MakeBuzz() will run, which
// will return a new Buzz object.
EXPECT_CALL(mock_buzzer_, MakeBuzz("hello")).Times(AnyNumber());
auto buzz1 = mock_buzzer_.MakeBuzz("hello");
auto buzz2 = mock_buzzer_.MakeBuzz("hello");
EXPECT_NE(nullptr, buzz1);
EXPECT_NE(nullptr, buzz2);
EXPECT_NE(buzz1, buzz2);
// Resets the default action for return type std::unique_ptr<Buzz>,
// to avoid interfere with other tests.
DefaultValue<std::unique_ptr<Buzz>>::Clear();
```
What if you want the method to do something other than the default action? If you just need to return a pre-defined move-only value, you can use the `Return(ByMove(...))` action:
```
```cpp
// When this fires, the unique_ptr<> specified by ByMove(...) will
// be returned.
EXPECT_CALL(mock_buzzer_, MakeBuzz("world"))
@ -2343,81 +2318,87 @@ What if you want the method to do something other than the default action? If y
Note that `ByMove()` is essential here - if you drop it, the code wont compile.
Quiz time! What do you think will happen if a `Return(ByMove(...))` action is performed more than once (e.g. you write `….WillRepeatedly(Return(ByMove(...)));`)? Come think of it, after the first time the action runs, the source value will be consumed (since its a move-only value), so the next time around, theres no value to move from -- youll get a run-time error that `Return(ByMove(...))` can only be run once.
Quiz time! What do you think will happen if a `Return(ByMove(...))` action is
performed more than once (e.g. you write
`.WillRepeatedly(Return(ByMove(...)));`)? Come think of it, after the first
time the action runs, the source value will be consumed (since its a move-only
value), so the next time around, theres no value to move from -- youll get a
run-time error that `Return(ByMove(...))` can only be run once.
If you need your mock method to do more than just moving a pre-defined value, remember that you can always use `Invoke()` to call a lambda or a callable object, which can do pretty much anything you want:
If you need your mock method to do more than just moving a pre-defined value,
remember that you can always use a lambda or a callable object, which can do
pretty much anything you want:
```
```cpp
EXPECT_CALL(mock_buzzer_, MakeBuzz("x"))
.WillRepeatedly(Invoke([](const std::string& text) {
return std::make_unique<Buzz>(AccessLevel::kInternal);
}));
.WillRepeatedly([](StringPiece text) {
return MakeUnique<Buzz>(AccessLevel::kInternal);
});
EXPECT_NE(nullptr, mock_buzzer_.MakeBuzz("x"));
EXPECT_NE(nullptr, mock_buzzer_.MakeBuzz("x"));
```
Every time this `EXPECT_CALL` fires, a new `unique_ptr<Buzz>` will be created and returned. You cannot do this with `Return(ByMove(...))`.
Every time this `EXPECT_CALL` fires, a new `unique_ptr<Buzz>` will be
created and returned. You cannot do this with `Return(ByMove(...))`.
Now theres one topic we havent covered: how do you set expectations on `ShareBuzz()`, which takes a move-only-typed parameter? The answer is you dont. Instead, you set expectations on the `DoShareBuzz()` mock method (remember that we defined a `MOCK_METHOD` for `DoShareBuzz()`, not `ShareBuzz()`):
That covers returning move-only values; but how do we work with methods
accepting move-only arguments? The answer is that they work normally, although
some actions will not compile when any of method's arguments are move-only. You
can always use `Return`, or a [lambda or functor](#FunctionsAsActions):
```cpp
using ::testing::Unused;
EXPECT_CALL(mock_buzzer_, ShareBuzz(NotNull(), _)) .WillOnce(Return(true));
EXPECT_TRUE(mock_buzzer_.ShareBuzz(MakeUnique<Buzz>(AccessLevel::kInternal)),
0);
EXPECT_CALL(mock_buzzer_, ShareBuzz(_, _)) .WillOnce(
[](std::unique_ptr<Buzz> buzz, Unused) { return buzz != nullptr; });
EXPECT_FALSE(mock_buzzer_.ShareBuzz(nullptr, 0));
```
Many built-in actions (`WithArgs`, `WithoutArgs`,`DeleteArg`, `SaveArg`, ...)
could in principle support move-only arguments, but the support for this is not
implemented yet. If this is blocking you, please file a bug.
A few actions (e.g. `DoAll`) copy their arguments internally, so they can never
work with non-copyable objects; you'll have to use functors instead.
##### Legacy workarounds for move-only types {#LegacyMoveOnly}
Support for move-only function arguments was only introduced to gMock in April
2017. In older code, you may encounter the following workaround for the lack of
this feature (it is no longer necessary - we're including it just for
reference):
```cpp
class MockBuzzer : public Buzzer {
public:
MOCK_METHOD2(DoShareBuzz, bool(Buzz* buzz, Time timestamp));
bool ShareBuzz(std::unique_ptr<Buzz> buzz, Time timestamp) override {
return DoShareBuzz(buzz.get(), timestamp);
}
};
```
The trick is to delegate the `ShareBuzz()` method to a mock method (lets call
it `DoShareBuzz()`) that does not take move-only parameters. Then, instead of
setting expectations on `ShareBuzz()`, you set them on the `DoShareBuzz()` mock
method:
```cpp
MockBuzzer mock_buzzer_;
EXPECT_CALL(mock_buzzer_, DoShareBuzz(NotNull(), _));
// When one calls ShareBuzz() on the MockBuzzer like this, the call is
// forwarded to DoShareBuzz(), which is mocked. Therefore this statement
// will trigger the above EXPECT_CALL.
mock_buzzer_.ShareBuzz(MakeUnique<Buzz>(AccessLevel::kInternal),
::base::Now());
mock_buzzer_.ShareBuzz(MakeUnique<Buzz>(AccessLevel::kInternal), 0);
```
Some of you may have spotted one problem with this approach: the `DoShareBuzz()` mock method differs from the real `ShareBuzz()` method in that it cannot take ownership of the buzz parameter - `ShareBuzz()` will always delete buzz after `DoShareBuzz()` returns. What if you need to save the buzz object somewhere for later use when `ShareBuzz()` is called? Indeed, you'd be stuck.
Another problem with the `DoShareBuzz()` we had is that it can surprise people reading or maintaining the test, as one would expect that `DoShareBuzz()` has (logically) the same contract as `ShareBuzz()`.
Fortunately, these problems can be fixed with a bit more code. Let's try to get it right this time:
```
class MockBuzzer : public Buzzer {
public:
MockBuzzer() {
// Since DoShareBuzz(buzz, time) is supposed to take ownership of
// buzz, define a default behavior for DoShareBuzz(buzz, time) to
// delete buzz.
ON_CALL(*this, DoShareBuzz(_, _))
.WillByDefault(Invoke([](Buzz* buzz, Time timestamp) {
delete buzz;
return true;
}));
}
MOCK_METHOD1(MakeBuzz, std::unique_ptr<Buzz>(const std::string& text));
// Takes ownership of buzz.
MOCK_METHOD2(DoShareBuzz, bool(Buzz* buzz, Time timestamp));
bool ShareBuzz(std::unique_ptr<Buzz> buzz, Time timestamp) {
return DoShareBuzz(buzz.release(), timestamp);
}
};
```
Now, the mock `DoShareBuzz()` method is free to save the buzz argument for later use if this is what you want:
```
std::unique_ptr<Buzz> intercepted_buzz;
EXPECT_CALL(mock_buzzer_, DoShareBuzz(NotNull(), _))
.WillOnce(Invoke([&intercepted_buzz](Buzz* buzz, Time timestamp) {
// Save buzz in intercepted_buzz for analysis later.
intercepted_buzz.reset(buzz);
return false;
}));
mock_buzzer_.ShareBuzz(std::make_unique<Buzz>(AccessLevel::kInternal),
Now());
EXPECT_NE(nullptr, intercepted_buzz);
```
Using the tricks covered in this recipe, you are now able to mock methods that take and/or return move-only types. Put your newly-acquired power to good use - when you design a new API, you can now feel comfortable using `unique_ptrs` as appropriate, without fearing that doing so will compromise your tests.
## Making the Compilation Faster ##
@ -3674,6 +3655,6 @@ This printer knows how to print built-in C++ types, native arrays, STL
containers, and any type that supports the `<<` operator. For other
types, it prints the raw bytes in the value and hopes that you the
user can figure it out.
[Google Test's advanced guide](../../googletest/docs/AdvancedGuide.md#teaching-google-test-how-to-print-your-values)
[Google Test's advanced guide](../../googletest/docs/advanced.md#teaching-google-test-how-to-print-your-values)
explains how to extend the printer to do a better job at
printing your particular type than to dump the bytes.

View File

@ -170,7 +170,7 @@ Admittedly, this test is contrived and doesn't do much. You can easily achieve t
## Using Google Mock with Any Testing Framework ##
If you want to use something other than Google Test (e.g. [CppUnit](http://sourceforge.net/projects/cppunit/) or
[CxxTest](http://cxxtest.tigris.org/)) as your testing framework, just change the `main()` function in the previous section to:
[CxxTest](https://cxxtest.com/)) as your testing framework, just change the `main()` function in the previous section to:
```
int main(int argc, char** argv) {
// The following line causes Google Mock to throw an exception on failure,
@ -187,7 +187,7 @@ sometimes causes the test program to crash. You'll still be able to
notice that the test has failed, but it's not a graceful failure.
A better solution is to use Google Test's
[event listener API](../../googletest/docs/AdvancedGuide.md#extending-google-test-by-handling-test-events)
[event listener API](../../googletest/docs/advanced.md#extending-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.

View File

@ -528,7 +528,7 @@ interface, which then can be easily mocked. It's a bit of work
initially, but usually pays for itself quickly.
This Google Testing Blog
[post](http://googletesting.blogspot.com/2008/06/defeat-static-cling.html)
[post](https://testing.googleblog.com/2008/06/defeat-static-cling.html)
says it excellently. Check it out.
## My mock object needs to do complex stuff. It's a lot of pain to specify the actions. Google Mock sucks! ##
@ -607,7 +607,6 @@ See this [recipe](CookBook.md#mocking_side_effects) for more details and an exam
If you cannot find the answer to your question in this FAQ, there are
some other resources you can use:
1. read other [documentation](Documentation.md),
1. search the mailing list [archive](http://groups.google.com/group/googlemock/topics),
1. ask it on [googlemock@googlegroups.com](mailto:googlemock@googlegroups.com) and someone will answer it (to prevent spam, we require you to join the [discussion group](http://groups.google.com/group/googlemock) before you can post.).

View File

@ -26,13 +26,14 @@
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Author: wan@google.com (Zhanyong Wan)
// Google Mock - a framework for writing C++ mock classes.
//
// This file implements some commonly used actions.
// GOOGLETEST_CM0002 DO NOT DELETE
#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_
#define GMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_
@ -360,15 +361,21 @@ class Action {
// Constructs a null Action. Needed for storing Action objects in
// STL containers.
Action() : impl_(NULL) {}
Action() {}
// Constructs an Action from its implementation. A NULL impl is
// used to represent the "do-default" action.
#if GTEST_LANG_CXX11
// Construct an Action from a specified callable.
// This cannot take std::function directly, because then Action would not be
// directly constructible from lambda (it would require two conversions).
template <typename G,
typename = typename ::std::enable_if<
::std::is_constructible<::std::function<F>, G>::value>::type>
Action(G&& fun) : fun_(::std::forward<G>(fun)) {} // NOLINT
#endif
// Constructs an Action from its implementation.
explicit Action(ActionInterface<F>* impl) : impl_(impl) {}
// Copy constructor.
Action(const Action& action) : impl_(action.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
@ -377,7 +384,13 @@ class Action {
explicit Action(const Action<Func>& action);
// Returns true iff this is the DoDefault() action.
bool IsDoDefault() const { return impl_.get() == NULL; }
bool IsDoDefault() const {
#if GTEST_LANG_CXX11
return impl_ == nullptr && fun_ == nullptr;
#else
return impl_ == NULL;
#endif
}
// Performs the action. Note that this method is const even though
// the corresponding method in ActionInterface is not. The reason
@ -385,14 +398,15 @@ class Action {
// another concrete action, not that the concrete action it binds to
// cannot change state. (Think of the difference between a const
// pointer and a pointer to const.)
Result Perform(const ArgumentTuple& args) const {
internal::Assert(
!IsDoDefault(), __FILE__, __LINE__,
"You are using DoDefault() inside a composite action like "
"DoAll() or WithArgs(). This is not supported for technical "
"reasons. Please instead spell out the default action, or "
"assign the default action to an Action variable and use "
"the variable in various places.");
Result Perform(ArgumentTuple args) const {
if (IsDoDefault()) {
internal::IllegalDoDefault(__FILE__, __LINE__);
}
#if GTEST_LANG_CXX11
if (fun_ != nullptr) {
return internal::Apply(fun_, ::std::move(args));
}
#endif
return impl_->Perform(args);
}
@ -400,6 +414,18 @@ class Action {
template <typename F1, typename F2>
friend class internal::ActionAdaptor;
template <typename G>
friend class Action;
// In C++11, Action can be implemented either as a generic functor (through
// std::function), or legacy ActionInterface. In C++98, only ActionInterface
// is available. The invariants are as follows:
// * in C++98, impl_ is null iff this is the default action
// * in C++11, at most one of fun_ & impl_ may be nonnull; both are null iff
// this is the default action
#if GTEST_LANG_CXX11
::std::function<F> fun_;
#endif
internal::linked_ptr<ActionInterface<F> > impl_;
};
@ -531,6 +557,9 @@ struct ByMoveWrapper {
// statement, and conversion of the result of Return to Action<T(U)> is a
// good place for that.
//
// The real life example of the above scenario happens when an invocation
// of gtl::Container() is passed into Return.
//
template <typename R>
class ReturnAction {
public:
@ -750,7 +779,7 @@ class DoDefaultAction {
// This template type conversion operator allows DoDefault() to be
// used in any function.
template <typename F>
operator Action<F>() const { return Action<F>(NULL); }
operator Action<F>() const { return Action<F>(); } // NOLINT
};
// Implements the Assign action to set a given pointer referent to a
@ -886,6 +915,28 @@ class InvokeMethodWithoutArgsAction {
GTEST_DISALLOW_ASSIGN_(InvokeMethodWithoutArgsAction);
};
// Implements the InvokeWithoutArgs(callback) action.
template <typename CallbackType>
class InvokeCallbackWithoutArgsAction {
public:
// The c'tor takes ownership of the callback.
explicit InvokeCallbackWithoutArgsAction(CallbackType* callback)
: callback_(callback) {
callback->CheckIsRepeatable(); // Makes sure the callback is permanent.
}
// This type conversion operator template allows Invoke(callback) to
// be used wherever the callback's return type can be implicitly
// converted to that of the mock function.
template <typename Result, typename ArgumentTuple>
Result Perform(const ArgumentTuple&) const { return callback_->Run(); }
private:
const internal::linked_ptr<CallbackType> callback_;
GTEST_DISALLOW_ASSIGN_(InvokeCallbackWithoutArgsAction);
};
// Implements the IgnoreResult(action) action.
template <typename A>
class IgnoreResultAction {
@ -1053,7 +1104,13 @@ typedef internal::IgnoredValue Unused;
template <typename To>
template <typename From>
Action<To>::Action(const Action<From>& from)
: impl_(new internal::ActionAdaptor<To, From>(from)) {}
:
#if GTEST_LANG_CXX11
fun_(from.fun_),
#endif
impl_(from.impl_ == NULL ? NULL
: new internal::ActionAdaptor<To, From>(from)) {
}
// Creates an action that returns 'value'. 'value' is passed by value
// instead of const reference - otherwise Return("string literal")

View File

@ -26,8 +26,7 @@
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Author: wan@google.com (Zhanyong Wan)
// Google Mock - a framework for writing C++ mock classes.
//
@ -35,6 +34,8 @@
// cardinalities can be defined by the user implementing the
// CardinalityInterface interface if necessary.
// GOOGLETEST_CM0002 DO NOT DELETE
#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_CARDINALITIES_H_
#define GMOCK_INCLUDE_GMOCK_GMOCK_CARDINALITIES_H_

View File

@ -1,4 +1,6 @@
// This file was GENERATED by a script. DO NOT EDIT BY HAND!!!
// This file was GENERATED by command:
// pump.py gmock-generated-actions.h.pump
// DO NOT EDIT BY HAND!!!
// Copyright 2007, Google Inc.
// All rights reserved.
@ -28,13 +30,14 @@
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Author: wan@google.com (Zhanyong Wan)
// Google Mock - a framework for writing C++ mock classes.
//
// This file implements some commonly used variadic actions.
// GOOGLETEST_CM0002 DO NOT DELETE
#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_ACTIONS_H_
#define GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_ACTIONS_H_
@ -45,8 +48,8 @@ namespace testing {
namespace internal {
// InvokeHelper<F> knows how to unpack an N-tuple and invoke an N-ary
// function or method with the unpacked values, where F is a function
// type that takes N arguments.
// function, method, or callback with the unpacked values, where F is
// a function type that takes N arguments.
template <typename Result, typename ArgumentTuple>
class InvokeHelper;
@ -64,6 +67,12 @@ class InvokeHelper<R, ::testing::tuple<> > {
const ::testing::tuple<>&) {
return (obj_ptr->*method_ptr)();
}
template <typename CallbackType>
static R InvokeCallback(CallbackType* callback,
const ::testing::tuple<>&) {
return callback->Run();
}
};
template <typename R, typename A1>
@ -80,6 +89,12 @@ class InvokeHelper<R, ::testing::tuple<A1> > {
const ::testing::tuple<A1>& args) {
return (obj_ptr->*method_ptr)(get<0>(args));
}
template <typename CallbackType>
static R InvokeCallback(CallbackType* callback,
const ::testing::tuple<A1>& args) {
return callback->Run(get<0>(args));
}
};
template <typename R, typename A1, typename A2>
@ -96,6 +111,12 @@ class InvokeHelper<R, ::testing::tuple<A1, A2> > {
const ::testing::tuple<A1, A2>& args) {
return (obj_ptr->*method_ptr)(get<0>(args), get<1>(args));
}
template <typename CallbackType>
static R InvokeCallback(CallbackType* callback,
const ::testing::tuple<A1, A2>& args) {
return callback->Run(get<0>(args), get<1>(args));
}
};
template <typename R, typename A1, typename A2, typename A3>
@ -113,6 +134,12 @@ class InvokeHelper<R, ::testing::tuple<A1, A2, A3> > {
return (obj_ptr->*method_ptr)(get<0>(args), get<1>(args),
get<2>(args));
}
template <typename CallbackType>
static R InvokeCallback(CallbackType* callback,
const ::testing::tuple<A1, A2, A3>& args) {
return callback->Run(get<0>(args), get<1>(args), get<2>(args));
}
};
template <typename R, typename A1, typename A2, typename A3, typename A4>
@ -132,6 +159,13 @@ class InvokeHelper<R, ::testing::tuple<A1, A2, A3, A4> > {
return (obj_ptr->*method_ptr)(get<0>(args), get<1>(args),
get<2>(args), get<3>(args));
}
template <typename CallbackType>
static R InvokeCallback(CallbackType* callback,
const ::testing::tuple<A1, A2, A3, A4>& args) {
return callback->Run(get<0>(args), get<1>(args), get<2>(args),
get<3>(args));
}
};
template <typename R, typename A1, typename A2, typename A3, typename A4,
@ -152,6 +186,13 @@ class InvokeHelper<R, ::testing::tuple<A1, A2, A3, A4, A5> > {
return (obj_ptr->*method_ptr)(get<0>(args), get<1>(args),
get<2>(args), get<3>(args), get<4>(args));
}
template <typename CallbackType>
static R InvokeCallback(CallbackType* callback,
const ::testing::tuple<A1, A2, A3, A4, A5>& args) {
return callback->Run(get<0>(args), get<1>(args), get<2>(args),
get<3>(args), get<4>(args));
}
};
template <typename R, typename A1, typename A2, typename A3, typename A4,
@ -172,6 +213,8 @@ class InvokeHelper<R, ::testing::tuple<A1, A2, A3, A4, A5, A6> > {
return (obj_ptr->*method_ptr)(get<0>(args), get<1>(args),
get<2>(args), get<3>(args), get<4>(args), get<5>(args));
}
// There is no InvokeCallback() for 6-tuples
};
template <typename R, typename A1, typename A2, typename A3, typename A4,
@ -194,6 +237,8 @@ class InvokeHelper<R, ::testing::tuple<A1, A2, A3, A4, A5, A6, A7> > {
get<2>(args), get<3>(args), get<4>(args), get<5>(args),
get<6>(args));
}
// There is no InvokeCallback() for 7-tuples
};
template <typename R, typename A1, typename A2, typename A3, typename A4,
@ -217,6 +262,8 @@ class InvokeHelper<R, ::testing::tuple<A1, A2, A3, A4, A5, A6, A7, A8> > {
get<2>(args), get<3>(args), get<4>(args), get<5>(args),
get<6>(args), get<7>(args));
}
// There is no InvokeCallback() for 8-tuples
};
template <typename R, typename A1, typename A2, typename A3, typename A4,
@ -240,6 +287,8 @@ class InvokeHelper<R, ::testing::tuple<A1, A2, A3, A4, A5, A6, A7, A8, A9> > {
get<2>(args), get<3>(args), get<4>(args), get<5>(args),
get<6>(args), get<7>(args), get<8>(args));
}
// There is no InvokeCallback() for 9-tuples
};
template <typename R, typename A1, typename A2, typename A3, typename A4,
@ -265,6 +314,33 @@ class InvokeHelper<R, ::testing::tuple<A1, A2, A3, A4, A5, A6, A7, A8, A9,
get<2>(args), get<3>(args), get<4>(args), get<5>(args),
get<6>(args), get<7>(args), get<8>(args), get<9>(args));
}
// There is no InvokeCallback() for 10-tuples
};
// Implements the Invoke(callback) action.
template <typename CallbackType>
class InvokeCallbackAction {
public:
// The c'tor takes ownership of the callback.
explicit InvokeCallbackAction(CallbackType* callback)
: callback_(callback) {
callback->CheckIsRepeatable(); // Makes sure the callback is permanent.
}
// This type conversion operator template allows Invoke(callback) to
// be used wherever the callback's type is compatible with that of
// the mock function, i.e. if the mock function's arguments can be
// implicitly converted to the callback's arguments and the
// callback's result can be implicitly converted to the mock
// function's result.
template <typename Result, typename ArgumentTuple>
Result Perform(const ArgumentTuple& args) const {
return InvokeHelper<Result, ArgumentTuple>::InvokeCallback(
callback_.get(), args);
}
private:
const linked_ptr<CallbackType> callback_;
};
// An INTERNAL macro for extracting the type of a tuple field. It's
@ -1073,52 +1149,90 @@ DoAll(Action1 a1, Action2 a2, Action3 a3, Action4 a4, Action5 a5, Action6 a6,
#define GMOCK_INTERNAL_INIT_AND_0_VALUE_PARAMS()\
()
#define GMOCK_INTERNAL_INIT_AND_1_VALUE_PARAMS(p0)\
(p0##_type gmock_p0) : p0(gmock_p0)
(p0##_type gmock_p0) : p0(::testing::internal::move(gmock_p0))
#define GMOCK_INTERNAL_INIT_AND_2_VALUE_PARAMS(p0, p1)\
(p0##_type gmock_p0, p1##_type gmock_p1) : p0(gmock_p0), p1(gmock_p1)
(p0##_type gmock_p0, \
p1##_type gmock_p1) : p0(::testing::internal::move(gmock_p0)), \
p1(::testing::internal::move(gmock_p1))
#define GMOCK_INTERNAL_INIT_AND_3_VALUE_PARAMS(p0, p1, p2)\
(p0##_type gmock_p0, p1##_type gmock_p1, \
p2##_type gmock_p2) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2)
p2##_type gmock_p2) : p0(::testing::internal::move(gmock_p0)), \
p1(::testing::internal::move(gmock_p1)), \
p2(::testing::internal::move(gmock_p2))
#define GMOCK_INTERNAL_INIT_AND_4_VALUE_PARAMS(p0, p1, p2, p3)\
(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
p3##_type gmock_p3) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), \
p3(gmock_p3)
p3##_type gmock_p3) : p0(::testing::internal::move(gmock_p0)), \
p1(::testing::internal::move(gmock_p1)), \
p2(::testing::internal::move(gmock_p2)), \
p3(::testing::internal::move(gmock_p3))
#define GMOCK_INTERNAL_INIT_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4)\
(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
p3##_type gmock_p3, p4##_type gmock_p4) : p0(gmock_p0), p1(gmock_p1), \
p2(gmock_p2), p3(gmock_p3), p4(gmock_p4)
p3##_type gmock_p3, \
p4##_type gmock_p4) : p0(::testing::internal::move(gmock_p0)), \
p1(::testing::internal::move(gmock_p1)), \
p2(::testing::internal::move(gmock_p2)), \
p3(::testing::internal::move(gmock_p3)), \
p4(::testing::internal::move(gmock_p4))
#define GMOCK_INTERNAL_INIT_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5)\
(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
p3##_type gmock_p3, p4##_type gmock_p4, \
p5##_type gmock_p5) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), \
p3(gmock_p3), p4(gmock_p4), p5(gmock_p5)
p5##_type gmock_p5) : p0(::testing::internal::move(gmock_p0)), \
p1(::testing::internal::move(gmock_p1)), \
p2(::testing::internal::move(gmock_p2)), \
p3(::testing::internal::move(gmock_p3)), \
p4(::testing::internal::move(gmock_p4)), \
p5(::testing::internal::move(gmock_p5))
#define GMOCK_INTERNAL_INIT_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6)\
(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \
p6##_type gmock_p6) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), \
p3(gmock_p3), p4(gmock_p4), p5(gmock_p5), p6(gmock_p6)
p6##_type gmock_p6) : p0(::testing::internal::move(gmock_p0)), \
p1(::testing::internal::move(gmock_p1)), \
p2(::testing::internal::move(gmock_p2)), \
p3(::testing::internal::move(gmock_p3)), \
p4(::testing::internal::move(gmock_p4)), \
p5(::testing::internal::move(gmock_p5)), \
p6(::testing::internal::move(gmock_p6))
#define GMOCK_INTERNAL_INIT_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7)\
(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \
p6##_type gmock_p6, p7##_type gmock_p7) : p0(gmock_p0), p1(gmock_p1), \
p2(gmock_p2), p3(gmock_p3), p4(gmock_p4), p5(gmock_p5), p6(gmock_p6), \
p7(gmock_p7)
p6##_type gmock_p6, \
p7##_type gmock_p7) : p0(::testing::internal::move(gmock_p0)), \
p1(::testing::internal::move(gmock_p1)), \
p2(::testing::internal::move(gmock_p2)), \
p3(::testing::internal::move(gmock_p3)), \
p4(::testing::internal::move(gmock_p4)), \
p5(::testing::internal::move(gmock_p5)), \
p6(::testing::internal::move(gmock_p6)), \
p7(::testing::internal::move(gmock_p7))
#define GMOCK_INTERNAL_INIT_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
p7, p8)\
(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \
p6##_type gmock_p6, p7##_type gmock_p7, \
p8##_type gmock_p8) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), \
p3(gmock_p3), p4(gmock_p4), p5(gmock_p5), p6(gmock_p6), p7(gmock_p7), \
p8(gmock_p8)
p8##_type gmock_p8) : p0(::testing::internal::move(gmock_p0)), \
p1(::testing::internal::move(gmock_p1)), \
p2(::testing::internal::move(gmock_p2)), \
p3(::testing::internal::move(gmock_p3)), \
p4(::testing::internal::move(gmock_p4)), \
p5(::testing::internal::move(gmock_p5)), \
p6(::testing::internal::move(gmock_p6)), \
p7(::testing::internal::move(gmock_p7)), \
p8(::testing::internal::move(gmock_p8))
#define GMOCK_INTERNAL_INIT_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
p7, p8, p9)\
(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \
p6##_type gmock_p6, p7##_type gmock_p7, p8##_type gmock_p8, \
p9##_type gmock_p9) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), \
p3(gmock_p3), p4(gmock_p4), p5(gmock_p5), p6(gmock_p6), p7(gmock_p7), \
p8(gmock_p8), p9(gmock_p9)
p9##_type gmock_p9) : p0(::testing::internal::move(gmock_p0)), \
p1(::testing::internal::move(gmock_p1)), \
p2(::testing::internal::move(gmock_p2)), \
p3(::testing::internal::move(gmock_p3)), \
p4(::testing::internal::move(gmock_p4)), \
p5(::testing::internal::move(gmock_p5)), \
p6(::testing::internal::move(gmock_p6)), \
p7(::testing::internal::move(gmock_p7)), \
p8(::testing::internal::move(gmock_p8)), \
p9(::testing::internal::move(gmock_p9))
// Declares the fields for storing the value parameters.
#define GMOCK_INTERNAL_DEFN_AND_0_VALUE_PARAMS()
@ -1354,7 +1468,8 @@ DoAll(Action1 a1, Action2 a2, Action3 a3, Action4 a4, Action5 a5, Action6 a6,
template <typename p0##_type>\
class name##ActionP {\
public:\
explicit name##ActionP(p0##_type gmock_p0) : p0(gmock_p0) {}\
explicit name##ActionP(p0##_type gmock_p0) : \
p0(::testing::internal::forward<p0##_type>(gmock_p0)) {}\
template <typename F>\
class gmock_Impl : public ::testing::ActionInterface<F> {\
public:\
@ -1362,7 +1477,8 @@ DoAll(Action1 a1, Action2 a2, Action3 a3, Action4 a4, Action5 a5, Action6 a6,
typedef typename ::testing::internal::Function<F>::Result return_type;\
typedef typename ::testing::internal::Function<F>::ArgumentTuple\
args_type;\
explicit gmock_Impl(p0##_type gmock_p0) : p0(gmock_p0) {}\
explicit gmock_Impl(p0##_type gmock_p0) : \
p0(::testing::internal::forward<p0##_type>(gmock_p0)) {}\
virtual return_type Perform(const args_type& args) {\
return ::testing::internal::ActionHelper<return_type, gmock_Impl>::\
Perform(this, args);\
@ -1404,8 +1520,9 @@ DoAll(Action1 a1, Action2 a2, Action3 a3, Action4 a4, Action5 a5, Action6 a6,
template <typename p0##_type, typename p1##_type>\
class name##ActionP2 {\
public:\
name##ActionP2(p0##_type gmock_p0, p1##_type gmock_p1) : p0(gmock_p0), \
p1(gmock_p1) {}\
name##ActionP2(p0##_type gmock_p0, \
p1##_type gmock_p1) : p0(::testing::internal::forward<p0##_type>(gmock_p0)), \
p1(::testing::internal::forward<p1##_type>(gmock_p1)) {}\
template <typename F>\
class gmock_Impl : public ::testing::ActionInterface<F> {\
public:\
@ -1413,8 +1530,9 @@ DoAll(Action1 a1, Action2 a2, Action3 a3, Action4 a4, Action5 a5, Action6 a6,
typedef typename ::testing::internal::Function<F>::Result return_type;\
typedef typename ::testing::internal::Function<F>::ArgumentTuple\
args_type;\
gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1) : p0(gmock_p0), \
p1(gmock_p1) {}\
gmock_Impl(p0##_type gmock_p0, \
p1##_type gmock_p1) : p0(::testing::internal::forward<p0##_type>(gmock_p0)), \
p1(::testing::internal::forward<p1##_type>(gmock_p1)) {}\
virtual return_type Perform(const args_type& args) {\
return ::testing::internal::ActionHelper<return_type, gmock_Impl>::\
Perform(this, args);\
@ -1460,7 +1578,9 @@ DoAll(Action1 a1, Action2 a2, Action3 a3, Action4 a4, Action5 a5, Action6 a6,
class name##ActionP3 {\
public:\
name##ActionP3(p0##_type gmock_p0, p1##_type gmock_p1, \
p2##_type gmock_p2) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2) {}\
p2##_type gmock_p2) : p0(::testing::internal::forward<p0##_type>(gmock_p0)), \
p1(::testing::internal::forward<p1##_type>(gmock_p1)), \
p2(::testing::internal::forward<p2##_type>(gmock_p2)) {}\
template <typename F>\
class gmock_Impl : public ::testing::ActionInterface<F> {\
public:\
@ -1469,7 +1589,9 @@ DoAll(Action1 a1, Action2 a2, Action3 a3, Action4 a4, Action5 a5, Action6 a6,
typedef typename ::testing::internal::Function<F>::ArgumentTuple\
args_type;\
gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, \
p2##_type gmock_p2) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2) {}\
p2##_type gmock_p2) : p0(::testing::internal::forward<p0##_type>(gmock_p0)), \
p1(::testing::internal::forward<p1##_type>(gmock_p1)), \
p2(::testing::internal::forward<p2##_type>(gmock_p2)) {}\
virtual return_type Perform(const args_type& args) {\
return ::testing::internal::ActionHelper<return_type, gmock_Impl>::\
Perform(this, args);\
@ -1519,8 +1641,11 @@ DoAll(Action1 a1, Action2 a2, Action3 a3, Action4 a4, Action5 a5, Action6 a6,
class name##ActionP4 {\
public:\
name##ActionP4(p0##_type gmock_p0, p1##_type gmock_p1, \
p2##_type gmock_p2, p3##_type gmock_p3) : p0(gmock_p0), p1(gmock_p1), \
p2(gmock_p2), p3(gmock_p3) {}\
p2##_type gmock_p2, \
p3##_type gmock_p3) : p0(::testing::internal::forward<p0##_type>(gmock_p0)), \
p1(::testing::internal::forward<p1##_type>(gmock_p1)), \
p2(::testing::internal::forward<p2##_type>(gmock_p2)), \
p3(::testing::internal::forward<p3##_type>(gmock_p3)) {}\
template <typename F>\
class gmock_Impl : public ::testing::ActionInterface<F> {\
public:\
@ -1529,8 +1654,10 @@ DoAll(Action1 a1, Action2 a2, Action3 a3, Action4 a4, Action5 a5, Action6 a6,
typedef typename ::testing::internal::Function<F>::ArgumentTuple\
args_type;\
gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
p3##_type gmock_p3) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), \
p3(gmock_p3) {}\
p3##_type gmock_p3) : p0(::testing::internal::forward<p0##_type>(gmock_p0)), \
p1(::testing::internal::forward<p1##_type>(gmock_p1)), \
p2(::testing::internal::forward<p2##_type>(gmock_p2)), \
p3(::testing::internal::forward<p3##_type>(gmock_p3)) {}\
virtual return_type Perform(const args_type& args) {\
return ::testing::internal::ActionHelper<return_type, gmock_Impl>::\
Perform(this, args);\
@ -1587,8 +1714,11 @@ DoAll(Action1 a1, Action2 a2, Action3 a3, Action4 a4, Action5 a5, Action6 a6,
public:\
name##ActionP5(p0##_type gmock_p0, p1##_type gmock_p1, \
p2##_type gmock_p2, p3##_type gmock_p3, \
p4##_type gmock_p4) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), \
p3(gmock_p3), p4(gmock_p4) {}\
p4##_type gmock_p4) : p0(::testing::internal::forward<p0##_type>(gmock_p0)), \
p1(::testing::internal::forward<p1##_type>(gmock_p1)), \
p2(::testing::internal::forward<p2##_type>(gmock_p2)), \
p3(::testing::internal::forward<p3##_type>(gmock_p3)), \
p4(::testing::internal::forward<p4##_type>(gmock_p4)) {}\
template <typename F>\
class gmock_Impl : public ::testing::ActionInterface<F> {\
public:\
@ -1597,8 +1727,12 @@ DoAll(Action1 a1, Action2 a2, Action3 a3, Action4 a4, Action5 a5, Action6 a6,
typedef typename ::testing::internal::Function<F>::ArgumentTuple\
args_type;\
gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
p3##_type gmock_p3, p4##_type gmock_p4) : p0(gmock_p0), \
p1(gmock_p1), p2(gmock_p2), p3(gmock_p3), p4(gmock_p4) {}\
p3##_type gmock_p3, \
p4##_type gmock_p4) : p0(::testing::internal::forward<p0##_type>(gmock_p0)), \
p1(::testing::internal::forward<p1##_type>(gmock_p1)), \
p2(::testing::internal::forward<p2##_type>(gmock_p2)), \
p3(::testing::internal::forward<p3##_type>(gmock_p3)), \
p4(::testing::internal::forward<p4##_type>(gmock_p4)) {}\
virtual return_type Perform(const args_type& args) {\
return ::testing::internal::ActionHelper<return_type, gmock_Impl>::\
Perform(this, args);\
@ -1657,8 +1791,12 @@ DoAll(Action1 a1, Action2 a2, Action3 a3, Action4 a4, Action5 a5, Action6 a6,
public:\
name##ActionP6(p0##_type gmock_p0, p1##_type gmock_p1, \
p2##_type gmock_p2, p3##_type gmock_p3, p4##_type gmock_p4, \
p5##_type gmock_p5) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), \
p3(gmock_p3), p4(gmock_p4), p5(gmock_p5) {}\
p5##_type gmock_p5) : p0(::testing::internal::forward<p0##_type>(gmock_p0)), \
p1(::testing::internal::forward<p1##_type>(gmock_p1)), \
p2(::testing::internal::forward<p2##_type>(gmock_p2)), \
p3(::testing::internal::forward<p3##_type>(gmock_p3)), \
p4(::testing::internal::forward<p4##_type>(gmock_p4)), \
p5(::testing::internal::forward<p5##_type>(gmock_p5)) {}\
template <typename F>\
class gmock_Impl : public ::testing::ActionInterface<F> {\
public:\
@ -1668,8 +1806,12 @@ DoAll(Action1 a1, Action2 a2, Action3 a3, Action4 a4, Action5 a5, Action6 a6,
args_type;\
gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
p3##_type gmock_p3, p4##_type gmock_p4, \
p5##_type gmock_p5) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), \
p3(gmock_p3), p4(gmock_p4), p5(gmock_p5) {}\
p5##_type gmock_p5) : p0(::testing::internal::forward<p0##_type>(gmock_p0)), \
p1(::testing::internal::forward<p1##_type>(gmock_p1)), \
p2(::testing::internal::forward<p2##_type>(gmock_p2)), \
p3(::testing::internal::forward<p3##_type>(gmock_p3)), \
p4(::testing::internal::forward<p4##_type>(gmock_p4)), \
p5(::testing::internal::forward<p5##_type>(gmock_p5)) {}\
virtual return_type Perform(const args_type& args) {\
return ::testing::internal::ActionHelper<return_type, gmock_Impl>::\
Perform(this, args);\
@ -1731,9 +1873,14 @@ DoAll(Action1 a1, Action2 a2, Action3 a3, Action4 a4, Action5 a5, Action6 a6,
public:\
name##ActionP7(p0##_type gmock_p0, p1##_type gmock_p1, \
p2##_type gmock_p2, p3##_type gmock_p3, p4##_type gmock_p4, \
p5##_type gmock_p5, p6##_type gmock_p6) : p0(gmock_p0), p1(gmock_p1), \
p2(gmock_p2), p3(gmock_p3), p4(gmock_p4), p5(gmock_p5), \
p6(gmock_p6) {}\
p5##_type gmock_p5, \
p6##_type gmock_p6) : p0(::testing::internal::forward<p0##_type>(gmock_p0)), \
p1(::testing::internal::forward<p1##_type>(gmock_p1)), \
p2(::testing::internal::forward<p2##_type>(gmock_p2)), \
p3(::testing::internal::forward<p3##_type>(gmock_p3)), \
p4(::testing::internal::forward<p4##_type>(gmock_p4)), \
p5(::testing::internal::forward<p5##_type>(gmock_p5)), \
p6(::testing::internal::forward<p6##_type>(gmock_p6)) {}\
template <typename F>\
class gmock_Impl : public ::testing::ActionInterface<F> {\
public:\
@ -1743,8 +1890,13 @@ DoAll(Action1 a1, Action2 a2, Action3 a3, Action4 a4, Action5 a5, Action6 a6,
args_type;\
gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \
p6##_type gmock_p6) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), \
p3(gmock_p3), p4(gmock_p4), p5(gmock_p5), p6(gmock_p6) {}\
p6##_type gmock_p6) : p0(::testing::internal::forward<p0##_type>(gmock_p0)), \
p1(::testing::internal::forward<p1##_type>(gmock_p1)), \
p2(::testing::internal::forward<p2##_type>(gmock_p2)), \
p3(::testing::internal::forward<p3##_type>(gmock_p3)), \
p4(::testing::internal::forward<p4##_type>(gmock_p4)), \
p5(::testing::internal::forward<p5##_type>(gmock_p5)), \
p6(::testing::internal::forward<p6##_type>(gmock_p6)) {}\
virtual return_type Perform(const args_type& args) {\
return ::testing::internal::ActionHelper<return_type, gmock_Impl>::\
Perform(this, args);\
@ -1813,9 +1965,14 @@ DoAll(Action1 a1, Action2 a2, Action3 a3, Action4 a4, Action5 a5, Action6 a6,
name##ActionP8(p0##_type gmock_p0, p1##_type gmock_p1, \
p2##_type gmock_p2, p3##_type gmock_p3, p4##_type gmock_p4, \
p5##_type gmock_p5, p6##_type gmock_p6, \
p7##_type gmock_p7) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), \
p3(gmock_p3), p4(gmock_p4), p5(gmock_p5), p6(gmock_p6), \
p7(gmock_p7) {}\
p7##_type gmock_p7) : p0(::testing::internal::forward<p0##_type>(gmock_p0)), \
p1(::testing::internal::forward<p1##_type>(gmock_p1)), \
p2(::testing::internal::forward<p2##_type>(gmock_p2)), \
p3(::testing::internal::forward<p3##_type>(gmock_p3)), \
p4(::testing::internal::forward<p4##_type>(gmock_p4)), \
p5(::testing::internal::forward<p5##_type>(gmock_p5)), \
p6(::testing::internal::forward<p6##_type>(gmock_p6)), \
p7(::testing::internal::forward<p7##_type>(gmock_p7)) {}\
template <typename F>\
class gmock_Impl : public ::testing::ActionInterface<F> {\
public:\
@ -1825,9 +1982,15 @@ DoAll(Action1 a1, Action2 a2, Action3 a3, Action4 a4, Action5 a5, Action6 a6,
args_type;\
gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \
p6##_type gmock_p6, p7##_type gmock_p7) : p0(gmock_p0), \
p1(gmock_p1), p2(gmock_p2), p3(gmock_p3), p4(gmock_p4), \
p5(gmock_p5), p6(gmock_p6), p7(gmock_p7) {}\
p6##_type gmock_p6, \
p7##_type gmock_p7) : p0(::testing::internal::forward<p0##_type>(gmock_p0)), \
p1(::testing::internal::forward<p1##_type>(gmock_p1)), \
p2(::testing::internal::forward<p2##_type>(gmock_p2)), \
p3(::testing::internal::forward<p3##_type>(gmock_p3)), \
p4(::testing::internal::forward<p4##_type>(gmock_p4)), \
p5(::testing::internal::forward<p5##_type>(gmock_p5)), \
p6(::testing::internal::forward<p6##_type>(gmock_p6)), \
p7(::testing::internal::forward<p7##_type>(gmock_p7)) {}\
virtual return_type Perform(const args_type& args) {\
return ::testing::internal::ActionHelper<return_type, gmock_Impl>::\
Perform(this, args);\
@ -1900,9 +2063,15 @@ DoAll(Action1 a1, Action2 a2, Action3 a3, Action4 a4, Action5 a5, Action6 a6,
name##ActionP9(p0##_type gmock_p0, p1##_type gmock_p1, \
p2##_type gmock_p2, p3##_type gmock_p3, p4##_type gmock_p4, \
p5##_type gmock_p5, p6##_type gmock_p6, p7##_type gmock_p7, \
p8##_type gmock_p8) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), \
p3(gmock_p3), p4(gmock_p4), p5(gmock_p5), p6(gmock_p6), p7(gmock_p7), \
p8(gmock_p8) {}\
p8##_type gmock_p8) : p0(::testing::internal::forward<p0##_type>(gmock_p0)), \
p1(::testing::internal::forward<p1##_type>(gmock_p1)), \
p2(::testing::internal::forward<p2##_type>(gmock_p2)), \
p3(::testing::internal::forward<p3##_type>(gmock_p3)), \
p4(::testing::internal::forward<p4##_type>(gmock_p4)), \
p5(::testing::internal::forward<p5##_type>(gmock_p5)), \
p6(::testing::internal::forward<p6##_type>(gmock_p6)), \
p7(::testing::internal::forward<p7##_type>(gmock_p7)), \
p8(::testing::internal::forward<p8##_type>(gmock_p8)) {}\
template <typename F>\
class gmock_Impl : public ::testing::ActionInterface<F> {\
public:\
@ -1913,9 +2082,15 @@ DoAll(Action1 a1, Action2 a2, Action3 a3, Action4 a4, Action5 a5, Action6 a6,
gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \
p6##_type gmock_p6, p7##_type gmock_p7, \
p8##_type gmock_p8) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), \
p3(gmock_p3), p4(gmock_p4), p5(gmock_p5), p6(gmock_p6), \
p7(gmock_p7), p8(gmock_p8) {}\
p8##_type gmock_p8) : p0(::testing::internal::forward<p0##_type>(gmock_p0)), \
p1(::testing::internal::forward<p1##_type>(gmock_p1)), \
p2(::testing::internal::forward<p2##_type>(gmock_p2)), \
p3(::testing::internal::forward<p3##_type>(gmock_p3)), \
p4(::testing::internal::forward<p4##_type>(gmock_p4)), \
p5(::testing::internal::forward<p5##_type>(gmock_p5)), \
p6(::testing::internal::forward<p6##_type>(gmock_p6)), \
p7(::testing::internal::forward<p7##_type>(gmock_p7)), \
p8(::testing::internal::forward<p8##_type>(gmock_p8)) {}\
virtual return_type Perform(const args_type& args) {\
return ::testing::internal::ActionHelper<return_type, gmock_Impl>::\
Perform(this, args);\
@ -1992,9 +2167,17 @@ DoAll(Action1 a1, Action2 a2, Action3 a3, Action4 a4, Action5 a5, Action6 a6,
name##ActionP10(p0##_type gmock_p0, p1##_type gmock_p1, \
p2##_type gmock_p2, p3##_type gmock_p3, p4##_type gmock_p4, \
p5##_type gmock_p5, p6##_type gmock_p6, p7##_type gmock_p7, \
p8##_type gmock_p8, p9##_type gmock_p9) : p0(gmock_p0), p1(gmock_p1), \
p2(gmock_p2), p3(gmock_p3), p4(gmock_p4), p5(gmock_p5), p6(gmock_p6), \
p7(gmock_p7), p8(gmock_p8), p9(gmock_p9) {}\
p8##_type gmock_p8, \
p9##_type gmock_p9) : p0(::testing::internal::forward<p0##_type>(gmock_p0)), \
p1(::testing::internal::forward<p1##_type>(gmock_p1)), \
p2(::testing::internal::forward<p2##_type>(gmock_p2)), \
p3(::testing::internal::forward<p3##_type>(gmock_p3)), \
p4(::testing::internal::forward<p4##_type>(gmock_p4)), \
p5(::testing::internal::forward<p5##_type>(gmock_p5)), \
p6(::testing::internal::forward<p6##_type>(gmock_p6)), \
p7(::testing::internal::forward<p7##_type>(gmock_p7)), \
p8(::testing::internal::forward<p8##_type>(gmock_p8)), \
p9(::testing::internal::forward<p9##_type>(gmock_p9)) {}\
template <typename F>\
class gmock_Impl : public ::testing::ActionInterface<F> {\
public:\
@ -2005,9 +2188,16 @@ DoAll(Action1 a1, Action2 a2, Action3 a3, Action4 a4, Action5 a5, Action6 a6,
gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \
p6##_type gmock_p6, p7##_type gmock_p7, p8##_type gmock_p8, \
p9##_type gmock_p9) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), \
p3(gmock_p3), p4(gmock_p4), p5(gmock_p5), p6(gmock_p6), \
p7(gmock_p7), p8(gmock_p8), p9(gmock_p9) {}\
p9##_type gmock_p9) : p0(::testing::internal::forward<p0##_type>(gmock_p0)), \
p1(::testing::internal::forward<p1##_type>(gmock_p1)), \
p2(::testing::internal::forward<p2##_type>(gmock_p2)), \
p3(::testing::internal::forward<p3##_type>(gmock_p3)), \
p4(::testing::internal::forward<p4##_type>(gmock_p4)), \
p5(::testing::internal::forward<p5##_type>(gmock_p5)), \
p6(::testing::internal::forward<p6##_type>(gmock_p6)), \
p7(::testing::internal::forward<p7##_type>(gmock_p7)), \
p8(::testing::internal::forward<p8##_type>(gmock_p8)), \
p9(::testing::internal::forward<p9##_type>(gmock_p9)) {}\
virtual return_type Perform(const args_type& args) {\
return ::testing::internal::ActionHelper<return_type, gmock_Impl>::\
Perform(this, args);\
@ -2369,7 +2559,7 @@ ACTION_TEMPLATE(ReturnNew,
} // namespace testing
// Include any custom actions added by the local installation.
// Include any custom callback actions added by the local installation.
// We must include this header at the end to make sure it can use the
// declarations from this file.
#include "gmock/internal/custom/gmock-generated-actions.h"

View File

@ -32,13 +32,14 @@ $$}} This meta comment fixes auto-indentation in editors.
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Author: wan@google.com (Zhanyong Wan)
// Google Mock - a framework for writing C++ mock classes.
//
// This file implements some commonly used variadic actions.
// GOOGLETEST_CM0002 DO NOT DELETE
#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_ACTIONS_H_
#define GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_ACTIONS_H_
@ -49,12 +50,13 @@ namespace testing {
namespace internal {
// InvokeHelper<F> knows how to unpack an N-tuple and invoke an N-ary
// function or method with the unpacked values, where F is a function
// type that takes N arguments.
// function, method, or callback with the unpacked values, where F is
// a function type that takes N arguments.
template <typename Result, typename ArgumentTuple>
class InvokeHelper;
$var max_callback_arity = 5
$range i 0..n
$for i [[
$range j 1..i
@ -76,10 +78,47 @@ class InvokeHelper<R, ::testing::tuple<$as> > {
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) \
@ -486,7 +525,7 @@ _VALUE_PARAMS($for j, [[p$j]]) $for j [[, typename p$j##_type]]
$for i [[
$range j 0..i-1
#define GMOCK_INTERNAL_INIT_AND_$i[[]]_VALUE_PARAMS($for j, [[p$j]])\
($for j, [[p$j##_type gmock_p$j]])$if i>0 [[ : ]]$for j, [[p$j(gmock_p$j)]]
($for j, [[p$j##_type gmock_p$j]])$if i>0 [[ : ]]$for j, [[p$j(::testing::internal::move(gmock_p$j))]]
]]
@ -619,7 +658,7 @@ $var class_name = [[name##Action[[$if i==0 [[]] $elif i==1 [[P]]
$range j 0..i-1
$var ctor_param_list = [[$for j, [[p$j##_type gmock_p$j]]]]
$var param_types_and_names = [[$for j, [[p$j##_type p$j]]]]
$var inits = [[$if i==0 [[]] $else [[ : $for j, [[p$j(gmock_p$j)]]]]]]
$var inits = [[$if i==0 [[]] $else [[ : $for j, [[p$j(::testing::internal::forward<p$j##_type>(gmock_p$j))]]]]]]
$var param_field_decls = [[$for j
[[

View File

@ -30,13 +30,14 @@
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Author: wan@google.com (Zhanyong Wan)
// Google Mock - a framework for writing C++ mock classes.
//
// This file implements function mockers of various arities.
// GOOGLETEST_CM0002 DO NOT DELETE
#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_FUNCTION_MOCKERS_H_
#define GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_FUNCTION_MOCKERS_H_
@ -332,6 +333,58 @@ class FunctionMocker<R(A1, A2, A3, A4, A5, A6, A7, A8, A9, A10)> : public
}
};
// Removes the given pointer; this is a helper for the expectation setter method
// for parameterless matchers.
//
// We want to make sure that the user cannot set a parameterless expectation on
// overloaded methods, including methods which are overloaded on const. Example:
//
// class MockClass {
// MOCK_METHOD0(GetName, string&());
// MOCK_CONST_METHOD0(GetName, const string&());
// };
//
// TEST() {
// // This should be an error, as it's not clear which overload is expected.
// EXPECT_CALL(mock, GetName).WillOnce(ReturnRef(value));
// }
//
// Here are the generated expectation-setter methods:
//
// class MockClass {
// // Overload 1
// MockSpec<string&()> gmock_GetName() { ... }
// // Overload 2. Declared const so that the compiler will generate an
// // error when trying to resolve between this and overload 4 in
// // 'gmock_GetName(WithoutMatchers(), nullptr)'.
// MockSpec<string&()> gmock_GetName(
// const WithoutMatchers&, const Function<string&()>*) const {
// // Removes const from this, calls overload 1
// return AdjustConstness_(this)->gmock_GetName();
// }
//
// // Overload 3
// const string& gmock_GetName() const { ... }
// // Overload 4
// MockSpec<const string&()> gmock_GetName(
// const WithoutMatchers&, const Function<const string&()>*) const {
// // Does not remove const, calls overload 3
// return AdjustConstness_const(this)->gmock_GetName();
// }
// }
//
template <typename MockType>
const MockType* AdjustConstness_const(const MockType* mock) {
return mock;
}
// Removes const from and returns the given pointer; this is a helper for the
// expectation setter method for parameterless matchers.
template <typename MockType>
MockType* AdjustConstness_(const MockType* mock) {
return const_cast<MockType*>(mock);
}
} // namespace internal
// The style guide prohibits "using" statements in a namespace scope
@ -366,220 +419,301 @@ using internal::FunctionMocker;
// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!!
#define GMOCK_METHOD0_(tn, constness, ct, Method, ...) \
GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \
) constness { \
GTEST_COMPILE_ASSERT_((::testing::tuple_size< \
tn ::testing::internal::Function<__VA_ARGS__>::ArgumentTuple>::value \
== 0), \
GMOCK_RESULT_(tn, __VA_ARGS__) ct Method() constness { \
GTEST_COMPILE_ASSERT_( \
(::testing::tuple_size<tn ::testing::internal::Function< \
__VA_ARGS__>::ArgumentTuple>::value == 0), \
this_method_does_not_take_0_arguments); \
GMOCK_MOCKER_(0, constness, Method).SetOwnerAndName(this, #Method); \
return GMOCK_MOCKER_(0, constness, Method).Invoke(); \
} \
::testing::MockSpec<__VA_ARGS__> \
gmock_##Method() constness { \
::testing::MockSpec<__VA_ARGS__> gmock_##Method() constness { \
GMOCK_MOCKER_(0, constness, Method).RegisterOwner(this); \
return GMOCK_MOCKER_(0, constness, Method).With(); \
} \
::testing::MockSpec<__VA_ARGS__> gmock_##Method( \
const ::testing::internal::WithoutMatchers&, \
constness ::testing::internal::Function<__VA_ARGS__>*) const { \
return ::testing::internal::AdjustConstness_##constness(this) \
->gmock_##Method(); \
} \
mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(0, constness, \
Method)
// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!!
#define GMOCK_METHOD1_(tn, constness, ct, Method, ...) \
GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \
GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1) constness { \
GTEST_COMPILE_ASSERT_((::testing::tuple_size< \
tn ::testing::internal::Function<__VA_ARGS__>::ArgumentTuple>::value \
== 1), \
GMOCK_RESULT_(tn, __VA_ARGS__) \
ct Method(GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1) constness { \
GTEST_COMPILE_ASSERT_( \
(::testing::tuple_size<tn ::testing::internal::Function< \
__VA_ARGS__>::ArgumentTuple>::value == 1), \
this_method_does_not_take_1_argument); \
GMOCK_MOCKER_(1, constness, Method).SetOwnerAndName(this, #Method); \
return GMOCK_MOCKER_(1, constness, \
Method).Invoke(::testing::internal::forward<GMOCK_ARG_(tn, 1, \
__VA_ARGS__)>(gmock_a1)); \
return GMOCK_MOCKER_(1, constness, Method) \
.Invoke(::testing::internal::forward<GMOCK_ARG_(tn, 1, __VA_ARGS__)>( \
gmock_a1)); \
} \
::testing::MockSpec<__VA_ARGS__> \
gmock_##Method(GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1) constness { \
::testing::MockSpec<__VA_ARGS__> gmock_##Method( \
GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1) constness { \
GMOCK_MOCKER_(1, constness, Method).RegisterOwner(this); \
return GMOCK_MOCKER_(1, constness, Method).With(gmock_a1); \
} \
::testing::MockSpec<__VA_ARGS__> gmock_##Method( \
const ::testing::internal::WithoutMatchers&, \
constness ::testing::internal::Function<__VA_ARGS__>*) const { \
return ::testing::internal::AdjustConstness_##constness(this) \
->gmock_##Method(::testing::A<GMOCK_ARG_(tn, 1, __VA_ARGS__)>()); \
} \
mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(1, constness, \
Method)
// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!!
#define GMOCK_METHOD2_(tn, constness, ct, Method, ...) \
GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \
GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, GMOCK_ARG_(tn, 2, \
__VA_ARGS__) gmock_a2) constness { \
GTEST_COMPILE_ASSERT_((::testing::tuple_size< \
tn ::testing::internal::Function<__VA_ARGS__>::ArgumentTuple>::value \
== 2), \
GMOCK_RESULT_(tn, __VA_ARGS__) \
ct Method(GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, \
GMOCK_ARG_(tn, 2, __VA_ARGS__) gmock_a2) constness { \
GTEST_COMPILE_ASSERT_( \
(::testing::tuple_size<tn ::testing::internal::Function< \
__VA_ARGS__>::ArgumentTuple>::value == 2), \
this_method_does_not_take_2_arguments); \
GMOCK_MOCKER_(2, constness, Method).SetOwnerAndName(this, #Method); \
return GMOCK_MOCKER_(2, constness, \
Method).Invoke(::testing::internal::forward<GMOCK_ARG_(tn, 1, \
__VA_ARGS__)>(gmock_a1), \
::testing::internal::forward<GMOCK_ARG_(tn, 2, __VA_ARGS__)>(gmock_a2)); \
return GMOCK_MOCKER_(2, constness, Method) \
.Invoke(::testing::internal::forward<GMOCK_ARG_(tn, 1, __VA_ARGS__)>( \
gmock_a1), \
::testing::internal::forward<GMOCK_ARG_(tn, 2, __VA_ARGS__)>( \
gmock_a2)); \
} \
::testing::MockSpec<__VA_ARGS__> \
gmock_##Method(GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1, \
::testing::MockSpec<__VA_ARGS__> gmock_##Method( \
GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1, \
GMOCK_MATCHER_(tn, 2, __VA_ARGS__) gmock_a2) constness { \
GMOCK_MOCKER_(2, constness, Method).RegisterOwner(this); \
return GMOCK_MOCKER_(2, constness, Method).With(gmock_a1, gmock_a2); \
} \
::testing::MockSpec<__VA_ARGS__> gmock_##Method( \
const ::testing::internal::WithoutMatchers&, \
constness ::testing::internal::Function<__VA_ARGS__>*) const { \
return ::testing::internal::AdjustConstness_##constness(this) \
->gmock_##Method(::testing::A<GMOCK_ARG_(tn, 1, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 2, __VA_ARGS__)>()); \
} \
mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(2, constness, \
Method)
// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!!
#define GMOCK_METHOD3_(tn, constness, ct, Method, ...) \
GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \
GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, GMOCK_ARG_(tn, 2, \
__VA_ARGS__) gmock_a2, GMOCK_ARG_(tn, 3, \
__VA_ARGS__) gmock_a3) constness { \
GTEST_COMPILE_ASSERT_((::testing::tuple_size< \
tn ::testing::internal::Function<__VA_ARGS__>::ArgumentTuple>::value \
== 3), \
GMOCK_RESULT_(tn, __VA_ARGS__) \
ct Method(GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, \
GMOCK_ARG_(tn, 2, __VA_ARGS__) gmock_a2, \
GMOCK_ARG_(tn, 3, __VA_ARGS__) gmock_a3) constness { \
GTEST_COMPILE_ASSERT_( \
(::testing::tuple_size<tn ::testing::internal::Function< \
__VA_ARGS__>::ArgumentTuple>::value == 3), \
this_method_does_not_take_3_arguments); \
GMOCK_MOCKER_(3, constness, Method).SetOwnerAndName(this, #Method); \
return GMOCK_MOCKER_(3, constness, \
Method).Invoke(::testing::internal::forward<GMOCK_ARG_(tn, 1, \
__VA_ARGS__)>(gmock_a1), \
::testing::internal::forward<GMOCK_ARG_(tn, 2, __VA_ARGS__)>(gmock_a2), \
::testing::internal::forward<GMOCK_ARG_(tn, 3, __VA_ARGS__)>(gmock_a3)); \
return GMOCK_MOCKER_(3, constness, Method) \
.Invoke(::testing::internal::forward<GMOCK_ARG_(tn, 1, __VA_ARGS__)>( \
gmock_a1), \
::testing::internal::forward<GMOCK_ARG_(tn, 2, __VA_ARGS__)>( \
gmock_a2), \
::testing::internal::forward<GMOCK_ARG_(tn, 3, __VA_ARGS__)>( \
gmock_a3)); \
} \
::testing::MockSpec<__VA_ARGS__> \
gmock_##Method(GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1, \
::testing::MockSpec<__VA_ARGS__> gmock_##Method( \
GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1, \
GMOCK_MATCHER_(tn, 2, __VA_ARGS__) gmock_a2, \
GMOCK_MATCHER_(tn, 3, __VA_ARGS__) gmock_a3) constness { \
GMOCK_MOCKER_(3, constness, Method).RegisterOwner(this); \
return GMOCK_MOCKER_(3, constness, Method).With(gmock_a1, gmock_a2, \
gmock_a3); \
return GMOCK_MOCKER_(3, constness, Method) \
.With(gmock_a1, gmock_a2, gmock_a3); \
} \
::testing::MockSpec<__VA_ARGS__> gmock_##Method( \
const ::testing::internal::WithoutMatchers&, \
constness ::testing::internal::Function<__VA_ARGS__>*) const { \
return ::testing::internal::AdjustConstness_##constness(this) \
->gmock_##Method(::testing::A<GMOCK_ARG_(tn, 1, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 2, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 3, __VA_ARGS__)>()); \
} \
mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(3, constness, \
Method)
// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!!
#define GMOCK_METHOD4_(tn, constness, ct, Method, ...) \
GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \
GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, GMOCK_ARG_(tn, 2, \
__VA_ARGS__) gmock_a2, GMOCK_ARG_(tn, 3, __VA_ARGS__) gmock_a3, \
GMOCK_RESULT_(tn, __VA_ARGS__) \
ct Method(GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, \
GMOCK_ARG_(tn, 2, __VA_ARGS__) gmock_a2, \
GMOCK_ARG_(tn, 3, __VA_ARGS__) gmock_a3, \
GMOCK_ARG_(tn, 4, __VA_ARGS__) gmock_a4) constness { \
GTEST_COMPILE_ASSERT_((::testing::tuple_size< \
tn ::testing::internal::Function<__VA_ARGS__>::ArgumentTuple>::value \
== 4), \
GTEST_COMPILE_ASSERT_( \
(::testing::tuple_size<tn ::testing::internal::Function< \
__VA_ARGS__>::ArgumentTuple>::value == 4), \
this_method_does_not_take_4_arguments); \
GMOCK_MOCKER_(4, constness, Method).SetOwnerAndName(this, #Method); \
return GMOCK_MOCKER_(4, constness, \
Method).Invoke(::testing::internal::forward<GMOCK_ARG_(tn, 1, \
__VA_ARGS__)>(gmock_a1), \
::testing::internal::forward<GMOCK_ARG_(tn, 2, __VA_ARGS__)>(gmock_a2), \
::testing::internal::forward<GMOCK_ARG_(tn, 3, __VA_ARGS__)>(gmock_a3), \
::testing::internal::forward<GMOCK_ARG_(tn, 4, __VA_ARGS__)>(gmock_a4)); \
return GMOCK_MOCKER_(4, constness, Method) \
.Invoke(::testing::internal::forward<GMOCK_ARG_(tn, 1, __VA_ARGS__)>( \
gmock_a1), \
::testing::internal::forward<GMOCK_ARG_(tn, 2, __VA_ARGS__)>( \
gmock_a2), \
::testing::internal::forward<GMOCK_ARG_(tn, 3, __VA_ARGS__)>( \
gmock_a3), \
::testing::internal::forward<GMOCK_ARG_(tn, 4, __VA_ARGS__)>( \
gmock_a4)); \
} \
::testing::MockSpec<__VA_ARGS__> \
gmock_##Method(GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1, \
::testing::MockSpec<__VA_ARGS__> gmock_##Method( \
GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1, \
GMOCK_MATCHER_(tn, 2, __VA_ARGS__) gmock_a2, \
GMOCK_MATCHER_(tn, 3, __VA_ARGS__) gmock_a3, \
GMOCK_MATCHER_(tn, 4, __VA_ARGS__) gmock_a4) constness { \
GMOCK_MOCKER_(4, constness, Method).RegisterOwner(this); \
return GMOCK_MOCKER_(4, constness, Method).With(gmock_a1, gmock_a2, \
gmock_a3, gmock_a4); \
return GMOCK_MOCKER_(4, constness, Method) \
.With(gmock_a1, gmock_a2, gmock_a3, gmock_a4); \
} \
::testing::MockSpec<__VA_ARGS__> gmock_##Method( \
const ::testing::internal::WithoutMatchers&, \
constness ::testing::internal::Function<__VA_ARGS__>*) const { \
return ::testing::internal::AdjustConstness_##constness(this) \
->gmock_##Method(::testing::A<GMOCK_ARG_(tn, 1, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 2, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 3, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 4, __VA_ARGS__)>()); \
} \
mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(4, constness, \
Method)
// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!!
#define GMOCK_METHOD5_(tn, constness, ct, Method, ...) \
GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \
GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, GMOCK_ARG_(tn, 2, \
__VA_ARGS__) gmock_a2, GMOCK_ARG_(tn, 3, __VA_ARGS__) gmock_a3, \
GMOCK_ARG_(tn, 4, __VA_ARGS__) gmock_a4, GMOCK_ARG_(tn, 5, \
__VA_ARGS__) gmock_a5) constness { \
GTEST_COMPILE_ASSERT_((::testing::tuple_size< \
tn ::testing::internal::Function<__VA_ARGS__>::ArgumentTuple>::value \
== 5), \
GMOCK_RESULT_(tn, __VA_ARGS__) \
ct Method(GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, \
GMOCK_ARG_(tn, 2, __VA_ARGS__) gmock_a2, \
GMOCK_ARG_(tn, 3, __VA_ARGS__) gmock_a3, \
GMOCK_ARG_(tn, 4, __VA_ARGS__) gmock_a4, \
GMOCK_ARG_(tn, 5, __VA_ARGS__) gmock_a5) constness { \
GTEST_COMPILE_ASSERT_( \
(::testing::tuple_size<tn ::testing::internal::Function< \
__VA_ARGS__>::ArgumentTuple>::value == 5), \
this_method_does_not_take_5_arguments); \
GMOCK_MOCKER_(5, constness, Method).SetOwnerAndName(this, #Method); \
return GMOCK_MOCKER_(5, constness, \
Method).Invoke(::testing::internal::forward<GMOCK_ARG_(tn, 1, \
__VA_ARGS__)>(gmock_a1), \
::testing::internal::forward<GMOCK_ARG_(tn, 2, __VA_ARGS__)>(gmock_a2), \
::testing::internal::forward<GMOCK_ARG_(tn, 3, __VA_ARGS__)>(gmock_a3), \
::testing::internal::forward<GMOCK_ARG_(tn, 4, __VA_ARGS__)>(gmock_a4), \
::testing::internal::forward<GMOCK_ARG_(tn, 5, __VA_ARGS__)>(gmock_a5)); \
return GMOCK_MOCKER_(5, constness, Method) \
.Invoke(::testing::internal::forward<GMOCK_ARG_(tn, 1, __VA_ARGS__)>( \
gmock_a1), \
::testing::internal::forward<GMOCK_ARG_(tn, 2, __VA_ARGS__)>( \
gmock_a2), \
::testing::internal::forward<GMOCK_ARG_(tn, 3, __VA_ARGS__)>( \
gmock_a3), \
::testing::internal::forward<GMOCK_ARG_(tn, 4, __VA_ARGS__)>( \
gmock_a4), \
::testing::internal::forward<GMOCK_ARG_(tn, 5, __VA_ARGS__)>( \
gmock_a5)); \
} \
::testing::MockSpec<__VA_ARGS__> \
gmock_##Method(GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1, \
::testing::MockSpec<__VA_ARGS__> gmock_##Method( \
GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1, \
GMOCK_MATCHER_(tn, 2, __VA_ARGS__) gmock_a2, \
GMOCK_MATCHER_(tn, 3, __VA_ARGS__) gmock_a3, \
GMOCK_MATCHER_(tn, 4, __VA_ARGS__) gmock_a4, \
GMOCK_MATCHER_(tn, 5, __VA_ARGS__) gmock_a5) constness { \
GMOCK_MOCKER_(5, constness, Method).RegisterOwner(this); \
return GMOCK_MOCKER_(5, constness, Method).With(gmock_a1, gmock_a2, \
gmock_a3, gmock_a4, gmock_a5); \
return GMOCK_MOCKER_(5, constness, Method) \
.With(gmock_a1, gmock_a2, gmock_a3, gmock_a4, gmock_a5); \
} \
::testing::MockSpec<__VA_ARGS__> gmock_##Method( \
const ::testing::internal::WithoutMatchers&, \
constness ::testing::internal::Function<__VA_ARGS__>*) const { \
return ::testing::internal::AdjustConstness_##constness(this) \
->gmock_##Method(::testing::A<GMOCK_ARG_(tn, 1, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 2, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 3, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 4, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 5, __VA_ARGS__)>()); \
} \
mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(5, constness, \
Method)
// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!!
#define GMOCK_METHOD6_(tn, constness, ct, Method, ...) \
GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \
GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, GMOCK_ARG_(tn, 2, \
__VA_ARGS__) gmock_a2, GMOCK_ARG_(tn, 3, __VA_ARGS__) gmock_a3, \
GMOCK_ARG_(tn, 4, __VA_ARGS__) gmock_a4, GMOCK_ARG_(tn, 5, \
__VA_ARGS__) gmock_a5, GMOCK_ARG_(tn, 6, \
__VA_ARGS__) gmock_a6) constness { \
GTEST_COMPILE_ASSERT_((::testing::tuple_size< \
tn ::testing::internal::Function<__VA_ARGS__>::ArgumentTuple>::value \
== 6), \
GMOCK_RESULT_(tn, __VA_ARGS__) \
ct Method(GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, \
GMOCK_ARG_(tn, 2, __VA_ARGS__) gmock_a2, \
GMOCK_ARG_(tn, 3, __VA_ARGS__) gmock_a3, \
GMOCK_ARG_(tn, 4, __VA_ARGS__) gmock_a4, \
GMOCK_ARG_(tn, 5, __VA_ARGS__) gmock_a5, \
GMOCK_ARG_(tn, 6, __VA_ARGS__) gmock_a6) constness { \
GTEST_COMPILE_ASSERT_( \
(::testing::tuple_size<tn ::testing::internal::Function< \
__VA_ARGS__>::ArgumentTuple>::value == 6), \
this_method_does_not_take_6_arguments); \
GMOCK_MOCKER_(6, constness, Method).SetOwnerAndName(this, #Method); \
return GMOCK_MOCKER_(6, constness, \
Method).Invoke(::testing::internal::forward<GMOCK_ARG_(tn, 1, \
__VA_ARGS__)>(gmock_a1), \
::testing::internal::forward<GMOCK_ARG_(tn, 2, __VA_ARGS__)>(gmock_a2), \
::testing::internal::forward<GMOCK_ARG_(tn, 3, __VA_ARGS__)>(gmock_a3), \
::testing::internal::forward<GMOCK_ARG_(tn, 4, __VA_ARGS__)>(gmock_a4), \
::testing::internal::forward<GMOCK_ARG_(tn, 5, __VA_ARGS__)>(gmock_a5), \
::testing::internal::forward<GMOCK_ARG_(tn, 6, __VA_ARGS__)>(gmock_a6)); \
return GMOCK_MOCKER_(6, constness, Method) \
.Invoke(::testing::internal::forward<GMOCK_ARG_(tn, 1, __VA_ARGS__)>( \
gmock_a1), \
::testing::internal::forward<GMOCK_ARG_(tn, 2, __VA_ARGS__)>( \
gmock_a2), \
::testing::internal::forward<GMOCK_ARG_(tn, 3, __VA_ARGS__)>( \
gmock_a3), \
::testing::internal::forward<GMOCK_ARG_(tn, 4, __VA_ARGS__)>( \
gmock_a4), \
::testing::internal::forward<GMOCK_ARG_(tn, 5, __VA_ARGS__)>( \
gmock_a5), \
::testing::internal::forward<GMOCK_ARG_(tn, 6, __VA_ARGS__)>( \
gmock_a6)); \
} \
::testing::MockSpec<__VA_ARGS__> \
gmock_##Method(GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1, \
::testing::MockSpec<__VA_ARGS__> gmock_##Method( \
GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1, \
GMOCK_MATCHER_(tn, 2, __VA_ARGS__) gmock_a2, \
GMOCK_MATCHER_(tn, 3, __VA_ARGS__) gmock_a3, \
GMOCK_MATCHER_(tn, 4, __VA_ARGS__) gmock_a4, \
GMOCK_MATCHER_(tn, 5, __VA_ARGS__) gmock_a5, \
GMOCK_MATCHER_(tn, 6, __VA_ARGS__) gmock_a6) constness { \
GMOCK_MOCKER_(6, constness, Method).RegisterOwner(this); \
return GMOCK_MOCKER_(6, constness, Method).With(gmock_a1, gmock_a2, \
gmock_a3, gmock_a4, gmock_a5, gmock_a6); \
return GMOCK_MOCKER_(6, constness, Method) \
.With(gmock_a1, gmock_a2, gmock_a3, gmock_a4, gmock_a5, gmock_a6); \
} \
::testing::MockSpec<__VA_ARGS__> gmock_##Method( \
const ::testing::internal::WithoutMatchers&, \
constness ::testing::internal::Function<__VA_ARGS__>*) const { \
return ::testing::internal::AdjustConstness_##constness(this) \
->gmock_##Method(::testing::A<GMOCK_ARG_(tn, 1, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 2, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 3, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 4, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 5, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 6, __VA_ARGS__)>()); \
} \
mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(6, constness, \
Method)
// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!!
#define GMOCK_METHOD7_(tn, constness, ct, Method, ...) \
GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \
GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, GMOCK_ARG_(tn, 2, \
__VA_ARGS__) gmock_a2, GMOCK_ARG_(tn, 3, __VA_ARGS__) gmock_a3, \
GMOCK_ARG_(tn, 4, __VA_ARGS__) gmock_a4, GMOCK_ARG_(tn, 5, \
__VA_ARGS__) gmock_a5, GMOCK_ARG_(tn, 6, __VA_ARGS__) gmock_a6, \
GMOCK_RESULT_(tn, __VA_ARGS__) \
ct Method(GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, \
GMOCK_ARG_(tn, 2, __VA_ARGS__) gmock_a2, \
GMOCK_ARG_(tn, 3, __VA_ARGS__) gmock_a3, \
GMOCK_ARG_(tn, 4, __VA_ARGS__) gmock_a4, \
GMOCK_ARG_(tn, 5, __VA_ARGS__) gmock_a5, \
GMOCK_ARG_(tn, 6, __VA_ARGS__) gmock_a6, \
GMOCK_ARG_(tn, 7, __VA_ARGS__) gmock_a7) constness { \
GTEST_COMPILE_ASSERT_((::testing::tuple_size< \
tn ::testing::internal::Function<__VA_ARGS__>::ArgumentTuple>::value \
== 7), \
GTEST_COMPILE_ASSERT_( \
(::testing::tuple_size<tn ::testing::internal::Function< \
__VA_ARGS__>::ArgumentTuple>::value == 7), \
this_method_does_not_take_7_arguments); \
GMOCK_MOCKER_(7, constness, Method).SetOwnerAndName(this, #Method); \
return GMOCK_MOCKER_(7, constness, \
Method).Invoke(::testing::internal::forward<GMOCK_ARG_(tn, 1, \
__VA_ARGS__)>(gmock_a1), \
::testing::internal::forward<GMOCK_ARG_(tn, 2, __VA_ARGS__)>(gmock_a2), \
::testing::internal::forward<GMOCK_ARG_(tn, 3, __VA_ARGS__)>(gmock_a3), \
::testing::internal::forward<GMOCK_ARG_(tn, 4, __VA_ARGS__)>(gmock_a4), \
::testing::internal::forward<GMOCK_ARG_(tn, 5, __VA_ARGS__)>(gmock_a5), \
::testing::internal::forward<GMOCK_ARG_(tn, 6, __VA_ARGS__)>(gmock_a6), \
::testing::internal::forward<GMOCK_ARG_(tn, 7, __VA_ARGS__)>(gmock_a7)); \
return GMOCK_MOCKER_(7, constness, Method) \
.Invoke(::testing::internal::forward<GMOCK_ARG_(tn, 1, __VA_ARGS__)>( \
gmock_a1), \
::testing::internal::forward<GMOCK_ARG_(tn, 2, __VA_ARGS__)>( \
gmock_a2), \
::testing::internal::forward<GMOCK_ARG_(tn, 3, __VA_ARGS__)>( \
gmock_a3), \
::testing::internal::forward<GMOCK_ARG_(tn, 4, __VA_ARGS__)>( \
gmock_a4), \
::testing::internal::forward<GMOCK_ARG_(tn, 5, __VA_ARGS__)>( \
gmock_a5), \
::testing::internal::forward<GMOCK_ARG_(tn, 6, __VA_ARGS__)>( \
gmock_a6), \
::testing::internal::forward<GMOCK_ARG_(tn, 7, __VA_ARGS__)>( \
gmock_a7)); \
} \
::testing::MockSpec<__VA_ARGS__> \
gmock_##Method(GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1, \
::testing::MockSpec<__VA_ARGS__> gmock_##Method( \
GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1, \
GMOCK_MATCHER_(tn, 2, __VA_ARGS__) gmock_a2, \
GMOCK_MATCHER_(tn, 3, __VA_ARGS__) gmock_a3, \
GMOCK_MATCHER_(tn, 4, __VA_ARGS__) gmock_a4, \
@ -587,39 +721,61 @@ using internal::FunctionMocker;
GMOCK_MATCHER_(tn, 6, __VA_ARGS__) gmock_a6, \
GMOCK_MATCHER_(tn, 7, __VA_ARGS__) gmock_a7) constness { \
GMOCK_MOCKER_(7, constness, Method).RegisterOwner(this); \
return GMOCK_MOCKER_(7, constness, Method).With(gmock_a1, gmock_a2, \
gmock_a3, gmock_a4, gmock_a5, gmock_a6, gmock_a7); \
return GMOCK_MOCKER_(7, constness, Method) \
.With(gmock_a1, gmock_a2, gmock_a3, gmock_a4, gmock_a5, gmock_a6, \
gmock_a7); \
} \
::testing::MockSpec<__VA_ARGS__> gmock_##Method( \
const ::testing::internal::WithoutMatchers&, \
constness ::testing::internal::Function<__VA_ARGS__>*) const { \
return ::testing::internal::AdjustConstness_##constness(this) \
->gmock_##Method(::testing::A<GMOCK_ARG_(tn, 1, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 2, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 3, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 4, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 5, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 6, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 7, __VA_ARGS__)>()); \
} \
mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(7, constness, \
Method)
// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!!
#define GMOCK_METHOD8_(tn, constness, ct, Method, ...) \
GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \
GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, GMOCK_ARG_(tn, 2, \
__VA_ARGS__) gmock_a2, GMOCK_ARG_(tn, 3, __VA_ARGS__) gmock_a3, \
GMOCK_ARG_(tn, 4, __VA_ARGS__) gmock_a4, GMOCK_ARG_(tn, 5, \
__VA_ARGS__) gmock_a5, GMOCK_ARG_(tn, 6, __VA_ARGS__) gmock_a6, \
GMOCK_ARG_(tn, 7, __VA_ARGS__) gmock_a7, GMOCK_ARG_(tn, 8, \
__VA_ARGS__) gmock_a8) constness { \
GTEST_COMPILE_ASSERT_((::testing::tuple_size< \
tn ::testing::internal::Function<__VA_ARGS__>::ArgumentTuple>::value \
== 8), \
GMOCK_RESULT_(tn, __VA_ARGS__) \
ct Method(GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, \
GMOCK_ARG_(tn, 2, __VA_ARGS__) gmock_a2, \
GMOCK_ARG_(tn, 3, __VA_ARGS__) gmock_a3, \
GMOCK_ARG_(tn, 4, __VA_ARGS__) gmock_a4, \
GMOCK_ARG_(tn, 5, __VA_ARGS__) gmock_a5, \
GMOCK_ARG_(tn, 6, __VA_ARGS__) gmock_a6, \
GMOCK_ARG_(tn, 7, __VA_ARGS__) gmock_a7, \
GMOCK_ARG_(tn, 8, __VA_ARGS__) gmock_a8) constness { \
GTEST_COMPILE_ASSERT_( \
(::testing::tuple_size<tn ::testing::internal::Function< \
__VA_ARGS__>::ArgumentTuple>::value == 8), \
this_method_does_not_take_8_arguments); \
GMOCK_MOCKER_(8, constness, Method).SetOwnerAndName(this, #Method); \
return GMOCK_MOCKER_(8, constness, \
Method).Invoke(::testing::internal::forward<GMOCK_ARG_(tn, 1, \
__VA_ARGS__)>(gmock_a1), \
::testing::internal::forward<GMOCK_ARG_(tn, 2, __VA_ARGS__)>(gmock_a2), \
::testing::internal::forward<GMOCK_ARG_(tn, 3, __VA_ARGS__)>(gmock_a3), \
::testing::internal::forward<GMOCK_ARG_(tn, 4, __VA_ARGS__)>(gmock_a4), \
::testing::internal::forward<GMOCK_ARG_(tn, 5, __VA_ARGS__)>(gmock_a5), \
::testing::internal::forward<GMOCK_ARG_(tn, 6, __VA_ARGS__)>(gmock_a6), \
::testing::internal::forward<GMOCK_ARG_(tn, 7, __VA_ARGS__)>(gmock_a7), \
::testing::internal::forward<GMOCK_ARG_(tn, 8, __VA_ARGS__)>(gmock_a8)); \
return GMOCK_MOCKER_(8, constness, Method) \
.Invoke(::testing::internal::forward<GMOCK_ARG_(tn, 1, __VA_ARGS__)>( \
gmock_a1), \
::testing::internal::forward<GMOCK_ARG_(tn, 2, __VA_ARGS__)>( \
gmock_a2), \
::testing::internal::forward<GMOCK_ARG_(tn, 3, __VA_ARGS__)>( \
gmock_a3), \
::testing::internal::forward<GMOCK_ARG_(tn, 4, __VA_ARGS__)>( \
gmock_a4), \
::testing::internal::forward<GMOCK_ARG_(tn, 5, __VA_ARGS__)>( \
gmock_a5), \
::testing::internal::forward<GMOCK_ARG_(tn, 6, __VA_ARGS__)>( \
gmock_a6), \
::testing::internal::forward<GMOCK_ARG_(tn, 7, __VA_ARGS__)>( \
gmock_a7), \
::testing::internal::forward<GMOCK_ARG_(tn, 8, __VA_ARGS__)>( \
gmock_a8)); \
} \
::testing::MockSpec<__VA_ARGS__> \
gmock_##Method(GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1, \
::testing::MockSpec<__VA_ARGS__> gmock_##Method( \
GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1, \
GMOCK_MATCHER_(tn, 2, __VA_ARGS__) gmock_a2, \
GMOCK_MATCHER_(tn, 3, __VA_ARGS__) gmock_a3, \
GMOCK_MATCHER_(tn, 4, __VA_ARGS__) gmock_a4, \
@ -628,41 +784,65 @@ using internal::FunctionMocker;
GMOCK_MATCHER_(tn, 7, __VA_ARGS__) gmock_a7, \
GMOCK_MATCHER_(tn, 8, __VA_ARGS__) gmock_a8) constness { \
GMOCK_MOCKER_(8, constness, Method).RegisterOwner(this); \
return GMOCK_MOCKER_(8, constness, Method).With(gmock_a1, gmock_a2, \
gmock_a3, gmock_a4, gmock_a5, gmock_a6, gmock_a7, gmock_a8); \
return GMOCK_MOCKER_(8, constness, Method) \
.With(gmock_a1, gmock_a2, gmock_a3, gmock_a4, gmock_a5, gmock_a6, \
gmock_a7, gmock_a8); \
} \
::testing::MockSpec<__VA_ARGS__> gmock_##Method( \
const ::testing::internal::WithoutMatchers&, \
constness ::testing::internal::Function<__VA_ARGS__>*) const { \
return ::testing::internal::AdjustConstness_##constness(this) \
->gmock_##Method(::testing::A<GMOCK_ARG_(tn, 1, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 2, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 3, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 4, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 5, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 6, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 7, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 8, __VA_ARGS__)>()); \
} \
mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(8, constness, \
Method)
// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!!
#define GMOCK_METHOD9_(tn, constness, ct, Method, ...) \
GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \
GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, GMOCK_ARG_(tn, 2, \
__VA_ARGS__) gmock_a2, GMOCK_ARG_(tn, 3, __VA_ARGS__) gmock_a3, \
GMOCK_ARG_(tn, 4, __VA_ARGS__) gmock_a4, GMOCK_ARG_(tn, 5, \
__VA_ARGS__) gmock_a5, GMOCK_ARG_(tn, 6, __VA_ARGS__) gmock_a6, \
GMOCK_ARG_(tn, 7, __VA_ARGS__) gmock_a7, GMOCK_ARG_(tn, 8, \
__VA_ARGS__) gmock_a8, GMOCK_ARG_(tn, 9, \
__VA_ARGS__) gmock_a9) constness { \
GTEST_COMPILE_ASSERT_((::testing::tuple_size< \
tn ::testing::internal::Function<__VA_ARGS__>::ArgumentTuple>::value \
== 9), \
GMOCK_RESULT_(tn, __VA_ARGS__) \
ct Method(GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, \
GMOCK_ARG_(tn, 2, __VA_ARGS__) gmock_a2, \
GMOCK_ARG_(tn, 3, __VA_ARGS__) gmock_a3, \
GMOCK_ARG_(tn, 4, __VA_ARGS__) gmock_a4, \
GMOCK_ARG_(tn, 5, __VA_ARGS__) gmock_a5, \
GMOCK_ARG_(tn, 6, __VA_ARGS__) gmock_a6, \
GMOCK_ARG_(tn, 7, __VA_ARGS__) gmock_a7, \
GMOCK_ARG_(tn, 8, __VA_ARGS__) gmock_a8, \
GMOCK_ARG_(tn, 9, __VA_ARGS__) gmock_a9) constness { \
GTEST_COMPILE_ASSERT_( \
(::testing::tuple_size<tn ::testing::internal::Function< \
__VA_ARGS__>::ArgumentTuple>::value == 9), \
this_method_does_not_take_9_arguments); \
GMOCK_MOCKER_(9, constness, Method).SetOwnerAndName(this, #Method); \
return GMOCK_MOCKER_(9, constness, \
Method).Invoke(::testing::internal::forward<GMOCK_ARG_(tn, 1, \
__VA_ARGS__)>(gmock_a1), \
::testing::internal::forward<GMOCK_ARG_(tn, 2, __VA_ARGS__)>(gmock_a2), \
::testing::internal::forward<GMOCK_ARG_(tn, 3, __VA_ARGS__)>(gmock_a3), \
::testing::internal::forward<GMOCK_ARG_(tn, 4, __VA_ARGS__)>(gmock_a4), \
::testing::internal::forward<GMOCK_ARG_(tn, 5, __VA_ARGS__)>(gmock_a5), \
::testing::internal::forward<GMOCK_ARG_(tn, 6, __VA_ARGS__)>(gmock_a6), \
::testing::internal::forward<GMOCK_ARG_(tn, 7, __VA_ARGS__)>(gmock_a7), \
::testing::internal::forward<GMOCK_ARG_(tn, 8, __VA_ARGS__)>(gmock_a8), \
::testing::internal::forward<GMOCK_ARG_(tn, 9, __VA_ARGS__)>(gmock_a9)); \
return GMOCK_MOCKER_(9, constness, Method) \
.Invoke(::testing::internal::forward<GMOCK_ARG_(tn, 1, __VA_ARGS__)>( \
gmock_a1), \
::testing::internal::forward<GMOCK_ARG_(tn, 2, __VA_ARGS__)>( \
gmock_a2), \
::testing::internal::forward<GMOCK_ARG_(tn, 3, __VA_ARGS__)>( \
gmock_a3), \
::testing::internal::forward<GMOCK_ARG_(tn, 4, __VA_ARGS__)>( \
gmock_a4), \
::testing::internal::forward<GMOCK_ARG_(tn, 5, __VA_ARGS__)>( \
gmock_a5), \
::testing::internal::forward<GMOCK_ARG_(tn, 6, __VA_ARGS__)>( \
gmock_a6), \
::testing::internal::forward<GMOCK_ARG_(tn, 7, __VA_ARGS__)>( \
gmock_a7), \
::testing::internal::forward<GMOCK_ARG_(tn, 8, __VA_ARGS__)>( \
gmock_a8), \
::testing::internal::forward<GMOCK_ARG_(tn, 9, __VA_ARGS__)>( \
gmock_a9)); \
} \
::testing::MockSpec<__VA_ARGS__> \
gmock_##Method(GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1, \
::testing::MockSpec<__VA_ARGS__> gmock_##Method( \
GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1, \
GMOCK_MATCHER_(tn, 2, __VA_ARGS__) gmock_a2, \
GMOCK_MATCHER_(tn, 3, __VA_ARGS__) gmock_a3, \
GMOCK_MATCHER_(tn, 4, __VA_ARGS__) gmock_a4, \
@ -672,43 +852,69 @@ using internal::FunctionMocker;
GMOCK_MATCHER_(tn, 8, __VA_ARGS__) gmock_a8, \
GMOCK_MATCHER_(tn, 9, __VA_ARGS__) gmock_a9) constness { \
GMOCK_MOCKER_(9, constness, Method).RegisterOwner(this); \
return GMOCK_MOCKER_(9, constness, Method).With(gmock_a1, gmock_a2, \
gmock_a3, gmock_a4, gmock_a5, gmock_a6, gmock_a7, gmock_a8, \
gmock_a9); \
return GMOCK_MOCKER_(9, constness, Method) \
.With(gmock_a1, gmock_a2, gmock_a3, gmock_a4, gmock_a5, gmock_a6, \
gmock_a7, gmock_a8, gmock_a9); \
} \
::testing::MockSpec<__VA_ARGS__> gmock_##Method( \
const ::testing::internal::WithoutMatchers&, \
constness ::testing::internal::Function<__VA_ARGS__>*) const { \
return ::testing::internal::AdjustConstness_##constness(this) \
->gmock_##Method(::testing::A<GMOCK_ARG_(tn, 1, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 2, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 3, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 4, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 5, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 6, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 7, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 8, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 9, __VA_ARGS__)>()); \
} \
mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(9, constness, \
Method)
// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!!
#define GMOCK_METHOD10_(tn, constness, ct, Method, ...) \
GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \
GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, GMOCK_ARG_(tn, 2, \
__VA_ARGS__) gmock_a2, GMOCK_ARG_(tn, 3, __VA_ARGS__) gmock_a3, \
GMOCK_ARG_(tn, 4, __VA_ARGS__) gmock_a4, GMOCK_ARG_(tn, 5, \
__VA_ARGS__) gmock_a5, GMOCK_ARG_(tn, 6, __VA_ARGS__) gmock_a6, \
GMOCK_ARG_(tn, 7, __VA_ARGS__) gmock_a7, GMOCK_ARG_(tn, 8, \
__VA_ARGS__) gmock_a8, GMOCK_ARG_(tn, 9, __VA_ARGS__) gmock_a9, \
GMOCK_RESULT_(tn, __VA_ARGS__) \
ct Method(GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, \
GMOCK_ARG_(tn, 2, __VA_ARGS__) gmock_a2, \
GMOCK_ARG_(tn, 3, __VA_ARGS__) gmock_a3, \
GMOCK_ARG_(tn, 4, __VA_ARGS__) gmock_a4, \
GMOCK_ARG_(tn, 5, __VA_ARGS__) gmock_a5, \
GMOCK_ARG_(tn, 6, __VA_ARGS__) gmock_a6, \
GMOCK_ARG_(tn, 7, __VA_ARGS__) gmock_a7, \
GMOCK_ARG_(tn, 8, __VA_ARGS__) gmock_a8, \
GMOCK_ARG_(tn, 9, __VA_ARGS__) gmock_a9, \
GMOCK_ARG_(tn, 10, __VA_ARGS__) gmock_a10) constness { \
GTEST_COMPILE_ASSERT_((::testing::tuple_size< \
tn ::testing::internal::Function<__VA_ARGS__>::ArgumentTuple>::value \
== 10), \
GTEST_COMPILE_ASSERT_( \
(::testing::tuple_size<tn ::testing::internal::Function< \
__VA_ARGS__>::ArgumentTuple>::value == 10), \
this_method_does_not_take_10_arguments); \
GMOCK_MOCKER_(10, constness, Method).SetOwnerAndName(this, #Method); \
return GMOCK_MOCKER_(10, constness, \
Method).Invoke(::testing::internal::forward<GMOCK_ARG_(tn, 1, \
__VA_ARGS__)>(gmock_a1), \
::testing::internal::forward<GMOCK_ARG_(tn, 2, __VA_ARGS__)>(gmock_a2), \
::testing::internal::forward<GMOCK_ARG_(tn, 3, __VA_ARGS__)>(gmock_a3), \
::testing::internal::forward<GMOCK_ARG_(tn, 4, __VA_ARGS__)>(gmock_a4), \
::testing::internal::forward<GMOCK_ARG_(tn, 5, __VA_ARGS__)>(gmock_a5), \
::testing::internal::forward<GMOCK_ARG_(tn, 6, __VA_ARGS__)>(gmock_a6), \
::testing::internal::forward<GMOCK_ARG_(tn, 7, __VA_ARGS__)>(gmock_a7), \
::testing::internal::forward<GMOCK_ARG_(tn, 8, __VA_ARGS__)>(gmock_a8), \
::testing::internal::forward<GMOCK_ARG_(tn, 9, __VA_ARGS__)>(gmock_a9), \
::testing::internal::forward<GMOCK_ARG_(tn, 10, __VA_ARGS__)>(gmock_a10)); \
return GMOCK_MOCKER_(10, constness, Method) \
.Invoke(::testing::internal::forward<GMOCK_ARG_(tn, 1, __VA_ARGS__)>( \
gmock_a1), \
::testing::internal::forward<GMOCK_ARG_(tn, 2, __VA_ARGS__)>( \
gmock_a2), \
::testing::internal::forward<GMOCK_ARG_(tn, 3, __VA_ARGS__)>( \
gmock_a3), \
::testing::internal::forward<GMOCK_ARG_(tn, 4, __VA_ARGS__)>( \
gmock_a4), \
::testing::internal::forward<GMOCK_ARG_(tn, 5, __VA_ARGS__)>( \
gmock_a5), \
::testing::internal::forward<GMOCK_ARG_(tn, 6, __VA_ARGS__)>( \
gmock_a6), \
::testing::internal::forward<GMOCK_ARG_(tn, 7, __VA_ARGS__)>( \
gmock_a7), \
::testing::internal::forward<GMOCK_ARG_(tn, 8, __VA_ARGS__)>( \
gmock_a8), \
::testing::internal::forward<GMOCK_ARG_(tn, 9, __VA_ARGS__)>( \
gmock_a9), \
::testing::internal::forward<GMOCK_ARG_(tn, 10, __VA_ARGS__)>( \
gmock_a10)); \
} \
::testing::MockSpec<__VA_ARGS__> \
gmock_##Method(GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1, \
::testing::MockSpec<__VA_ARGS__> gmock_##Method( \
GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1, \
GMOCK_MATCHER_(tn, 2, __VA_ARGS__) gmock_a2, \
GMOCK_MATCHER_(tn, 3, __VA_ARGS__) gmock_a3, \
GMOCK_MATCHER_(tn, 4, __VA_ARGS__) gmock_a4, \
@ -717,12 +923,26 @@ using internal::FunctionMocker;
GMOCK_MATCHER_(tn, 7, __VA_ARGS__) gmock_a7, \
GMOCK_MATCHER_(tn, 8, __VA_ARGS__) gmock_a8, \
GMOCK_MATCHER_(tn, 9, __VA_ARGS__) gmock_a9, \
GMOCK_MATCHER_(tn, 10, \
__VA_ARGS__) gmock_a10) constness { \
GMOCK_MATCHER_(tn, 10, __VA_ARGS__) gmock_a10) constness { \
GMOCK_MOCKER_(10, constness, Method).RegisterOwner(this); \
return GMOCK_MOCKER_(10, constness, Method).With(gmock_a1, gmock_a2, \
gmock_a3, gmock_a4, gmock_a5, gmock_a6, gmock_a7, gmock_a8, gmock_a9, \
gmock_a10); \
return GMOCK_MOCKER_(10, constness, Method) \
.With(gmock_a1, gmock_a2, gmock_a3, gmock_a4, gmock_a5, gmock_a6, \
gmock_a7, gmock_a8, gmock_a9, gmock_a10); \
} \
::testing::MockSpec<__VA_ARGS__> gmock_##Method( \
const ::testing::internal::WithoutMatchers&, \
constness ::testing::internal::Function<__VA_ARGS__>*) const { \
return ::testing::internal::AdjustConstness_##constness(this) \
->gmock_##Method(::testing::A<GMOCK_ARG_(tn, 1, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 2, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 3, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 4, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 5, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 6, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 7, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 8, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 9, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 10, __VA_ARGS__)>()); \
} \
mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(10, constness, \
Method)

View File

@ -31,13 +31,14 @@ $var n = 10 $$ The maximum arity we support.
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Author: wan@google.com (Zhanyong Wan)
// Google Mock - a framework for writing C++ mock classes.
//
// This file implements function mockers of various arities.
// GOOGLETEST_CM0002 DO NOT DELETE
#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_FUNCTION_MOCKERS_H_
#define GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_FUNCTION_MOCKERS_H_
@ -68,7 +69,7 @@ $for i [[
$range j 1..i
$var typename_As = [[$for j [[, typename A$j]]]]
$var As = [[$for j, [[A$j]]]]
$var as = [[$for j, [[a$j]]]]
$var as = [[$for j, [[internal::forward<A$j>(a$j)]]]]
$var Aas = [[$for j, [[A$j a$j]]]]
$var ms = [[$for j, [[m$j]]]]
$var matchers = [[$for j, [[const Matcher<A$j>& m$j]]]]
@ -79,13 +80,8 @@ class FunctionMocker<R($As)> : public
typedef R F($As);
typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
MockSpec<F>& With($matchers) {
$if i >= 1 [[
this->current_spec().SetMatchers(::testing::make_tuple($ms));
]]
return this->current_spec();
MockSpec<F> With($matchers) {
return MockSpec<F>(this, ::testing::make_tuple($ms));
}
R Invoke($Aas) {
@ -99,6 +95,58 @@ $if i >= 1 [[
]]
// Removes the given pointer; this is a helper for the expectation setter method
// for parameterless matchers.
//
// We want to make sure that the user cannot set a parameterless expectation on
// overloaded methods, including methods which are overloaded on const. Example:
//
// class MockClass {
// MOCK_METHOD0(GetName, string&());
// MOCK_CONST_METHOD0(GetName, const string&());
// };
//
// TEST() {
// // This should be an error, as it's not clear which overload is expected.
// EXPECT_CALL(mock, GetName).WillOnce(ReturnRef(value));
// }
//
// Here are the generated expectation-setter methods:
//
// class MockClass {
// // Overload 1
// MockSpec<string&()> gmock_GetName() { ... }
// // Overload 2. Declared const so that the compiler will generate an
// // error when trying to resolve between this and overload 4 in
// // 'gmock_GetName(WithoutMatchers(), nullptr)'.
// MockSpec<string&()> gmock_GetName(
// const WithoutMatchers&, const Function<string&()>*) const {
// // Removes const from this, calls overload 1
// return AdjustConstness_(this)->gmock_GetName();
// }
//
// // Overload 3
// const string& gmock_GetName() const { ... }
// // Overload 4
// MockSpec<const string&()> gmock_GetName(
// const WithoutMatchers&, const Function<const string&()>*) const {
// // Does not remove const, calls overload 3
// return AdjustConstness_const(this)->gmock_GetName();
// }
// }
//
template <typename MockType>
const MockType* AdjustConstness_const(const MockType* mock) {
return mock;
}
// Removes const from and returns the given pointer; this is a helper for the
// expectation setter method for parameterless matchers.
template <typename MockType>
MockType* AdjustConstness_(const MockType* mock) {
return const_cast<MockType*>(mock);
}
} // namespace internal
// The style guide prohibits "using" statements in a namespace scope
@ -134,11 +182,14 @@ using internal::FunctionMocker;
$for i [[
$range j 1..i
$var arg_as = [[$for j, \
[[GMOCK_ARG_(tn, $j, __VA_ARGS__) gmock_a$j]]]]
$var as = [[$for j, [[gmock_a$j]]]]
$var matcher_as = [[$for j, \
$var arg_as = [[$for j, [[GMOCK_ARG_(tn, $j, __VA_ARGS__) gmock_a$j]]]]
$var as = [[$for j, \
[[::testing::internal::forward<GMOCK_ARG_(tn, $j, __VA_ARGS__)>(gmock_a$j)]]]]
$var matcher_arg_as = [[$for j, \
[[GMOCK_MATCHER_(tn, $j, __VA_ARGS__) gmock_a$j]]]]
$var matcher_as = [[$for j, [[gmock_a$j]]]]
$var anything_matchers = [[$for j, \
[[::testing::A<GMOCK_ARG_(tn, $j, __VA_ARGS__)>()]]]]
// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!!
#define GMOCK_METHOD$i[[]]_(tn, constness, ct, Method, ...) \
GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \
@ -149,10 +200,16 @@ $var matcher_as = [[$for j, \
GMOCK_MOCKER_($i, constness, Method).SetOwnerAndName(this, #Method); \
return GMOCK_MOCKER_($i, constness, Method).Invoke($as); \
} \
::testing::MockSpec<__VA_ARGS__>& \
gmock_##Method($matcher_as) constness { \
::testing::MockSpec<__VA_ARGS__> \
gmock_##Method($matcher_arg_as) constness { \
GMOCK_MOCKER_($i, constness, Method).RegisterOwner(this); \
return GMOCK_MOCKER_($i, constness, Method).With($as); \
return GMOCK_MOCKER_($i, constness, Method).With($matcher_as); \
} \
::testing::MockSpec<__VA_ARGS__> gmock_##Method( \
const ::testing::internal::WithoutMatchers&, \
constness ::testing::internal::Function<__VA_ARGS__>* ) const { \
return ::testing::internal::AdjustConstness_##constness(this)-> \
gmock_##Method($anything_matchers); \
} \
mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_($i, constness, Method)
@ -263,7 +320,7 @@ class MockFunction;
$for i [[
$range j 0..i-1
$var ArgTypes = [[$for j, [[A$j]]]]
$var ArgNames = [[$for j, [[a$j]]]]
$var ArgValues = [[$for j, [[::std::move(a$j)]]]]
$var ArgDecls = [[$for j, [[A$j a$j]]]]
template <typename R$for j [[, typename A$j]]>
class MockFunction<R($ArgTypes)> {
@ -273,9 +330,9 @@ class MockFunction<R($ArgTypes)> {
MOCK_METHOD$i[[]]_T(Call, R($ArgTypes));
#if GTEST_HAS_STD_FUNCTION_
std::function<R($ArgTypes)> AsStdFunction() {
::std::function<R($ArgTypes)> AsStdFunction() {
return [this]($ArgDecls) -> R {
return this->Call($ArgNames);
return this->Call($ArgValues);
};
}
#endif // GTEST_HAS_STD_FUNCTION_

File diff suppressed because it is too large Load Diff

View File

@ -1,6 +1,6 @@
$$ -*- mode: c++; -*-
$$ This is a Pump source file. Please use Pump to convert it to
$$ gmock-generated-actions.h.
$$ This is a Pump source file. Please use Pump to convert
$$ it to gmock-generated-matchers.h.
$$
$var n = 10 $$ The maximum arity we support.
$$ }} This line fixes auto-indentation of the following code in Emacs.
@ -37,6 +37,8 @@ $$ }} This line fixes auto-indentation of the following code in Emacs.
//
// This file implements some commonly used variadic matchers.
// GOOGLETEST_CM0002 DO NOT DELETE
#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_MATCHERS_H_
#define GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_MATCHERS_H_
@ -303,6 +305,9 @@ $for 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 [[
@ -479,7 +484,7 @@ $$ // show up in the generated code.
// using testing::PrintToString;
//
// MATCHER_P2(InClosedRange, low, hi,
// string(negation ? "is not" : "is") + " in range [" +
// std::string(negation ? "is not" : "is") + " in range [" +
// PrintToString(low) + ", " + PrintToString(hi) + "]") {
// return low <= arg && arg <= hi;
// }
@ -604,32 +609,34 @@ $var template = [[$if i==0 [[]] $else [[
]]]]
$var ctor_param_list = [[$for j, [[p$j##_type gmock_p$j]]]]
$var impl_ctor_param_list = [[$for j, [[p$j##_type gmock_p$j]]]]
$var impl_inits = [[$if i==0 [[]] $else [[ : $for j, [[p$j(gmock_p$j)]]]]]]
$var inits = [[$if i==0 [[]] $else [[ : $for j, [[p$j(gmock_p$j)]]]]]]
$var impl_inits = [[$if i==0 [[]] $else [[ : $for j, [[p$j(::testing::internal::move(gmock_p$j))]]]]]]
$var inits = [[$if i==0 [[]] $else [[ : $for j, [[p$j(::testing::internal::move(gmock_p$j))]]]]]]
$var params = [[$for j, [[p$j]]]]
$var param_types = [[$if i==0 [[]] $else [[<$for j, [[p$j##_type]]>]]]]
$var param_types_and_names = [[$for j, [[p$j##_type p$j]]]]
$var param_field_decls = [[$for j
[[
p$j##_type p$j;\
p$j##_type const p$j;\
]]]]
$var param_field_decls2 = [[$for j
[[
p$j##_type p$j;\
p$j##_type const p$j;\
]]]]
#define $macro_name(name$for j [[, p$j]], description)\$template
class $class_name {\
public:\
template <typename arg_type>\
class gmock_Impl : public ::testing::MatcherInterface<arg_type> {\
class gmock_Impl : public ::testing::MatcherInterface<\
GTEST_REFERENCE_TO_CONST_(arg_type)> {\
public:\
[[$if i==1 [[explicit ]]]]gmock_Impl($impl_ctor_param_list)\
$impl_inits {}\
virtual bool MatchAndExplain(\
arg_type arg, ::testing::MatchResultListener* result_listener) const;\
GTEST_REFERENCE_TO_CONST_(arg_type) arg,\
::testing::MatchResultListener* result_listener) const;\
virtual void DescribeTo(::std::ostream* gmock_os) const {\
*gmock_os << FormatDescription(false);\
}\
@ -637,17 +644,15 @@ $var param_field_decls2 = [[$for j
*gmock_os << FormatDescription(true);\
}\$param_field_decls
private:\
::testing::internal::string FormatDescription(bool negation) const {\
const ::testing::internal::string gmock_description = (description);\
if (!gmock_description.empty()) {\
::std::string FormatDescription(bool negation) const {\
::std::string gmock_description = (description);\
if (!gmock_description.empty())\
return gmock_description;\
}\
return ::testing::internal::FormatMatcherDescription(\
negation, #name, \
::testing::internal::UniversalTersePrintTupleFieldsToStrings(\
::testing::tuple<$for j, [[p$j##_type]]>($for j, [[p$j]])));\
}\
GTEST_DISALLOW_ASSIGN_(gmock_Impl);\
};\
template <typename arg_type>\
operator ::testing::Matcher<arg_type>() const {\
@ -657,14 +662,13 @@ $var param_field_decls2 = [[$for j
[[$if i==1 [[explicit ]]]]$class_name($ctor_param_list)$inits {\
}\$param_field_decls2
private:\
GTEST_DISALLOW_ASSIGN_($class_name);\
};\$template
inline $class_name$param_types name($param_types_and_names) {\
return $class_name$param_types($params);\
}\$template
template <typename arg_type>\
bool $class_name$param_types::gmock_Impl<arg_type>::MatchAndExplain(\
arg_type arg, \
GTEST_REFERENCE_TO_CONST_(arg_type) arg,\
::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\
const
]]

View File

@ -30,8 +30,7 @@
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Author: wan@google.com (Zhanyong Wan)
// Implements class templates NiceMock, NaggyMock, and StrictMock.
//
@ -63,6 +62,8 @@
// 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_
@ -71,25 +72,13 @@
namespace testing {
namespace internal {
// NiceMockBase serves as a mix-in to establish the "uninteresting call"
// behavior for NiceMock on construction. It accomplishes this via CRTP to get
// access to the derived MockClass.
template <class MockClass>
class NiceMockBase {
protected:
NiceMockBase();
~NiceMockBase();
};
} // namespace internal
template <class MockClass>
class NiceMock : public MockClass, public internal::NiceMockBase<MockClass> {
class NiceMock : public MockClass {
public:
NiceMock() : MockClass() {}
NiceMock() : MockClass() {
::testing::Mock::AllowUninterestingCalls(
internal::ImplicitCast_<MockClass*>(this));
}
#if GTEST_LANG_CXX11
// Ideally, we would inherit base class's constructors through a using
@ -100,103 +89,114 @@ class NiceMock : public MockClass, public internal::NiceMockBase<MockClass> {
// 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)) {}
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)...) {}
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) {}
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) {}
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) {}
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) {}
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) {}
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) {}
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) {}
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) {}
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) {}
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) {}
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);
};
namespace internal {
template <typename MockClass>
NiceMockBase<MockClass>::NiceMockBase() {
::testing::Mock::AllowUninterestingCalls(
internal::ImplicitCast_<MockClass*>(
static_cast<NiceMock<MockClass> *>(this)));
}
template <typename MockClass>
NiceMockBase<MockClass>::~NiceMockBase() {
::testing::Mock::UnregisterCallReaction(
internal::ImplicitCast_<MockClass*>(
static_cast<NiceMock<MockClass>*>(this)));
}
} // namespace internal
namespace internal {
// NaggyMockBase serves as a mix-in to establish the "uninteresting call"
// behavior for NaggyMock on construction. It accomplishes this via CRTP to get
// access to the derived MockClass.
template <class MockClass>
class NaggyMockBase {
protected:
NaggyMockBase();
~NaggyMockBase();
};
} // namespace internal
template <class MockClass>
class NaggyMock : public MockClass, public internal::NaggyMockBase<MockClass> {
class NaggyMock : public MockClass {
public:
NaggyMock() : MockClass() {}
NaggyMock() : MockClass() {
::testing::Mock::WarnUninterestingCalls(
internal::ImplicitCast_<MockClass*>(this));
}
#if GTEST_LANG_CXX11
// Ideally, we would inherit base class's constructors through a using
@ -207,104 +207,114 @@ class NaggyMock : public MockClass, public internal::NaggyMockBase<MockClass> {
// 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)) {}
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)...) {}
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) {}
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) {}
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) {}
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) {}
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) {}
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) {}
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) {}
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) {}
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) {}
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) {}
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);
};
namespace internal {
template <typename MockClass>
NaggyMockBase<MockClass>::NaggyMockBase() {
::testing::Mock::WarnUninterestingCalls(
internal::ImplicitCast_<MockClass*>(
static_cast<NaggyMock<MockClass> *>(this)));
}
template <typename MockClass>
NaggyMockBase<MockClass>::~NaggyMockBase() {
::testing::Mock::UnregisterCallReaction(
internal::ImplicitCast_<MockClass*>(
static_cast<NaggyMock<MockClass>*>(this)));
}
} // namespace internal
namespace internal {
// StrictMockBase serves as a mix-in to establish the "uninteresting call"
// behavior for StrictMock on construction. It accomplishes this via CRTP to get
// access to the derived MockClass.
template <class MockClass>
class StrictMockBase {
protected:
StrictMockBase();
~StrictMockBase();
};
} // namespace internal
template <class MockClass>
class StrictMock : public MockClass,
public internal::StrictMockBase<MockClass> {
class StrictMock : public MockClass {
public:
StrictMock() : MockClass() {}
StrictMock() : MockClass() {
::testing::Mock::FailUninterestingCalls(
internal::ImplicitCast_<MockClass*>(this));
}
#if GTEST_LANG_CXX11
// Ideally, we would inherit base class's constructors through a using
@ -315,85 +325,107 @@ class StrictMock : public MockClass,
// 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)) {}
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)...) {}
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) {}
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) {}
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) {}
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) {}
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) {}
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) {}
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) {}
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) {}
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) {}
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) {}
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);
};
namespace internal {
template <typename MockClass>
StrictMockBase<MockClass>::StrictMockBase() {
::testing::Mock::FailUninterestingCalls(
internal::ImplicitCast_<MockClass*>(
static_cast<StrictMock<MockClass> *>(this)));
}
template <typename MockClass>
StrictMockBase<MockClass>::~StrictMockBase() {
::testing::Mock::UnregisterCallReaction(
internal::ImplicitCast_<MockClass*>(
static_cast<StrictMock<MockClass>*>(this)));
}
} // namespace internal
// The following specializations catch some (relatively more common)
// user errors of nesting nice and strict mocks. They do NOT catch
// all possible errors.

View File

@ -1,6 +1,6 @@
$$ -*- mode: c++; -*-
$$ This is a Pump source file. Please use Pump to convert it to
$$ gmock-generated-nice-strict.h.
$$ This is a Pump source file. Please use Pump to convert
$$ it to gmock-generated-nice-strict.h.
$$
$var n = 10 $$ The maximum arity we support.
// Copyright 2008, Google Inc.
@ -31,8 +31,7 @@ $var n = 10 $$ The maximum arity we support.
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Author: wan@google.com (Zhanyong Wan)
// Implements class templates NiceMock, NaggyMock, and StrictMock.
//
@ -52,10 +51,9 @@ $var n = 10 $$ The maximum arity we support.
// NiceMock<MockFoo>.
//
// NiceMock, NaggyMock, and StrictMock "inherit" the constructors of
// their respective base class, with up-to $n arguments. Therefore
// you can write NiceMock<MockFoo>(5, "a") to construct a nice mock
// where MockFoo has a constructor that accepts (int, const char*),
// for example.
// their respective base class. Therefore you can write
// NiceMock<MockFoo>(5, "a") to construct a nice mock where MockFoo
// has a constructor that accepts (int, const char*), for example.
//
// A known limitation is that NiceMock<MockFoo>, NaggyMock<MockFoo>,
// and StrictMock<MockFoo> only works for mock methods defined using
@ -64,10 +62,8 @@ $var n = 10 $$ The maximum arity we support.
// or "strict" modifier may not affect it, depending on the compiler.
// In particular, nesting NiceMock, NaggyMock, and StrictMock is NOT
// supported.
//
// Another known limitation is that the constructors of the base mock
// cannot have arguments passed by non-const reference, which are
// banned by the Google C++ style guide anyway.
// GOOGLETEST_CM0002 DO NOT DELETE
#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_NICE_STRICT_H_
#define GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_NICE_STRICT_H_
@ -91,15 +87,35 @@ $var method=[[$if kind==0 [[AllowUninterestingCalls]]
template <class MockClass>
class $clazz : public MockClass {
public:
// We don't factor out the constructor body to a common method, as
// we have to avoid a possible clash with members of MockClass.
$clazz() {
$clazz() : MockClass() {
::testing::Mock::$method(
internal::ImplicitCast_<MockClass*>(this));
}
// C++ doesn't (yet) allow inheritance of constructors, so we have
// to define it for each arity.
#if GTEST_LANG_CXX11
// Ideally, we would inherit base class's constructors through a using
// declaration, which would preserve their visibility. However, many existing
// tests rely on the fact that current implementation reexports protected
// constructors as public. These tests would need to be cleaned up first.
// Single argument constructor is special-cased so that it can be
// made explicit.
template <typename A>
explicit $clazz(A&& arg) : MockClass(std::forward<A>(arg)) {
::testing::Mock::$method(
internal::ImplicitCast_<MockClass*>(this));
}
template <typename A1, typename A2, typename... An>
$clazz(A1&& arg1, A2&& arg2, An&&... args)
: MockClass(std::forward<A1>(arg1), std::forward<A2>(arg2),
std::forward<An>(args)...) {
::testing::Mock::$method(
internal::ImplicitCast_<MockClass*>(this));
}
#else
// C++98 doesn't have variadic templates, so we have to define one
// for each arity.
template <typename A1>
explicit $clazz(const A1& a1) : MockClass(a1) {
::testing::Mock::$method(
@ -117,7 +133,9 @@ $range j 1..i
]]
virtual ~$clazz() {
#endif // GTEST_LANG_CXX11
~$clazz() {
::testing::Mock::UnregisterCallReaction(
internal::ImplicitCast_<MockClass*>(this));
}

View File

@ -26,8 +26,7 @@
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Author: wan@google.com (Zhanyong Wan)
// Google Mock - a framework for writing C++ mock classes.
//
@ -35,6 +34,8 @@
// matchers can be defined by the user implementing the
// MatcherInterface<T> interface if necessary.
// GOOGLETEST_CM0002 DO NOT DELETE
#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_
#define GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_
@ -72,7 +73,7 @@ namespace testing {
// MatchResultListener is an abstract class. Its << operator can be
// used by a matcher to explain why a value matches or doesn't match.
//
// TODO(wan@google.com): add method
// FIXME: add method
// bool InterestedInWhy(bool result) const;
// to indicate whether the listener is interested in why the match
// result is 'result'.
@ -921,7 +922,7 @@ class TuplePrefix {
GTEST_REFERENCE_TO_CONST_(Value) value = get<N - 1>(values);
StringMatchResultListener listener;
if (!matcher.MatchAndExplain(value, &listener)) {
// TODO(wan): include in the message the name of the parameter
// FIXME: include in the message the name of the parameter
// as used in MOCK_METHOD*() when possible.
*os << " Expected arg #" << N - 1 << ": ";
get<N - 1>(matchers).DescribeTo(os);
@ -1718,25 +1719,27 @@ class NotMatcher {
// that will prevent different instantiations of BothOfMatcher from
// sharing the same BothOfMatcherImpl<T> class.
template <typename T>
class BothOfMatcherImpl
class AllOfMatcherImpl
: public MatcherInterface<GTEST_REFERENCE_TO_CONST_(T)> {
public:
BothOfMatcherImpl(const Matcher<T>& matcher1, const Matcher<T>& matcher2)
: matcher1_(matcher1), matcher2_(matcher2) {}
explicit AllOfMatcherImpl(std::vector<Matcher<T> > matchers)
: matchers_(internal::move(matchers)) {}
virtual void DescribeTo(::std::ostream* os) const {
*os << "(";
matcher1_.DescribeTo(os);
*os << ") and (";
matcher2_.DescribeTo(os);
for (size_t i = 0; i < matchers_.size(); ++i) {
if (i != 0) *os << ") and (";
matchers_[i].DescribeTo(os);
}
*os << ")";
}
virtual void DescribeNegationTo(::std::ostream* os) const {
*os << "(";
matcher1_.DescribeNegationTo(os);
*os << ") or (";
matcher2_.DescribeNegationTo(os);
for (size_t i = 0; i < matchers_.size(); ++i) {
if (i != 0) *os << ") or (";
matchers_[i].DescribeNegationTo(os);
}
*os << ")";
}
@ -1744,93 +1747,38 @@ class BothOfMatcherImpl
MatchResultListener* listener) const {
// If either matcher1_ or matcher2_ doesn't match x, we only need
// to explain why one of them fails.
StringMatchResultListener listener1;
if (!matcher1_.MatchAndExplain(x, &listener1)) {
*listener << listener1.str();
std::string all_match_result;
for (size_t i = 0; i < matchers_.size(); ++i) {
StringMatchResultListener slistener;
if (matchers_[i].MatchAndExplain(x, &slistener)) {
if (all_match_result.empty()) {
all_match_result = slistener.str();
} else {
std::string result = slistener.str();
if (!result.empty()) {
all_match_result += ", and ";
all_match_result += result;
}
}
} else {
*listener << slistener.str();
return false;
}
StringMatchResultListener listener2;
if (!matcher2_.MatchAndExplain(x, &listener2)) {
*listener << listener2.str();
return false;
}
// Otherwise we need to explain why *both* of them match.
const std::string s1 = listener1.str();
const std::string s2 = listener2.str();
if (s1 == "") {
*listener << s2;
} else {
*listener << s1;
if (s2 != "") {
*listener << ", and " << s2;
}
}
*listener << all_match_result;
return true;
}
private:
const Matcher<T> matcher1_;
const Matcher<T> matcher2_;
const std::vector<Matcher<T> > matchers_;
GTEST_DISALLOW_ASSIGN_(BothOfMatcherImpl);
GTEST_DISALLOW_ASSIGN_(AllOfMatcherImpl);
};
#if GTEST_LANG_CXX11
// MatcherList provides mechanisms for storing a variable number of matchers in
// a list structure (ListType) and creating a combining matcher from such a
// list.
// The template is defined recursively using the following template parameters:
// * kSize is the length of the MatcherList.
// * Head is the type of the first matcher of the list.
// * Tail denotes the types of the remaining matchers of the list.
template <int kSize, typename Head, typename... Tail>
struct MatcherList {
typedef MatcherList<kSize - 1, Tail...> MatcherListTail;
typedef ::std::pair<Head, typename MatcherListTail::ListType> ListType;
// BuildList stores variadic type values in a nested pair structure.
// Example:
// MatcherList<3, int, string, float>::BuildList(5, "foo", 2.0) will return
// the corresponding result of type pair<int, pair<string, float>>.
static ListType BuildList(const Head& matcher, const Tail&... tail) {
return ListType(matcher, MatcherListTail::BuildList(tail...));
}
// CreateMatcher<T> creates a Matcher<T> from a given list of matchers (built
// by BuildList()). CombiningMatcher<T> is used to combine the matchers of the
// list. CombiningMatcher<T> must implement MatcherInterface<T> and have a
// constructor taking two Matcher<T>s as input.
template <typename T, template <typename /* T */> class CombiningMatcher>
static Matcher<T> CreateMatcher(const ListType& matchers) {
return Matcher<T>(new CombiningMatcher<T>(
SafeMatcherCast<T>(matchers.first),
MatcherListTail::template CreateMatcher<T, CombiningMatcher>(
matchers.second)));
}
};
// The following defines the base case for the recursive definition of
// MatcherList.
template <typename Matcher1, typename Matcher2>
struct MatcherList<2, Matcher1, Matcher2> {
typedef ::std::pair<Matcher1, Matcher2> ListType;
static ListType BuildList(const Matcher1& matcher1,
const Matcher2& matcher2) {
return ::std::pair<Matcher1, Matcher2>(matcher1, matcher2);
}
template <typename T, template <typename /* T */> class CombiningMatcher>
static Matcher<T> CreateMatcher(const ListType& matchers) {
return Matcher<T>(new CombiningMatcher<T>(
SafeMatcherCast<T>(matchers.first),
SafeMatcherCast<T>(matchers.second)));
}
};
// VariadicMatcher is used for the variadic implementation of
// AllOf(m_1, m_2, ...) and AnyOf(m_1, m_2, ...).
// CombiningMatcher<T> is used to recursively combine the provided matchers
@ -1839,27 +1787,40 @@ template <template <typename T> class CombiningMatcher, typename... Args>
class VariadicMatcher {
public:
VariadicMatcher(const Args&... matchers) // NOLINT
: matchers_(MatcherListType::BuildList(matchers...)) {}
: matchers_(matchers...) {
static_assert(sizeof...(Args) > 0, "Must have at least one matcher.");
}
// This template type conversion operator allows an
// VariadicMatcher<Matcher1, Matcher2...> object to match any type that
// all of the provided matchers (Matcher1, Matcher2, ...) can match.
template <typename T>
operator Matcher<T>() const {
return MatcherListType::template CreateMatcher<T, CombiningMatcher>(
matchers_);
std::vector<Matcher<T> > values;
CreateVariadicMatcher<T>(&values, std::integral_constant<size_t, 0>());
return Matcher<T>(new CombiningMatcher<T>(internal::move(values)));
}
private:
typedef MatcherList<sizeof...(Args), Args...> MatcherListType;
template <typename T, size_t I>
void CreateVariadicMatcher(std::vector<Matcher<T> >* values,
std::integral_constant<size_t, I>) const {
values->push_back(SafeMatcherCast<T>(std::get<I>(matchers_)));
CreateVariadicMatcher<T>(values, std::integral_constant<size_t, I + 1>());
}
const typename MatcherListType::ListType matchers_;
template <typename T>
void CreateVariadicMatcher(
std::vector<Matcher<T> >*,
std::integral_constant<size_t, sizeof...(Args)>) const {}
tuple<Args...> matchers_;
GTEST_DISALLOW_ASSIGN_(VariadicMatcher);
};
template <typename... Args>
using AllOfMatcher = VariadicMatcher<BothOfMatcherImpl, Args...>;
using AllOfMatcher = VariadicMatcher<AllOfMatcherImpl, Args...>;
#endif // GTEST_LANG_CXX11
@ -1876,8 +1837,10 @@ class BothOfMatcher {
// both Matcher1 and Matcher2 can match.
template <typename T>
operator Matcher<T>() const {
return Matcher<T>(new BothOfMatcherImpl<T>(SafeMatcherCast<T>(matcher1_),
SafeMatcherCast<T>(matcher2_)));
std::vector<Matcher<T> > values;
values.push_back(SafeMatcherCast<T>(matcher1_));
values.push_back(SafeMatcherCast<T>(matcher2_));
return Matcher<T>(new AllOfMatcherImpl<T>(internal::move(values)));
}
private:
@ -1892,70 +1855,69 @@ class BothOfMatcher {
// that will prevent different instantiations of AnyOfMatcher from
// sharing the same EitherOfMatcherImpl<T> class.
template <typename T>
class EitherOfMatcherImpl
class AnyOfMatcherImpl
: public MatcherInterface<GTEST_REFERENCE_TO_CONST_(T)> {
public:
EitherOfMatcherImpl(const Matcher<T>& matcher1, const Matcher<T>& matcher2)
: matcher1_(matcher1), matcher2_(matcher2) {}
explicit AnyOfMatcherImpl(std::vector<Matcher<T> > matchers)
: matchers_(internal::move(matchers)) {}
virtual void DescribeTo(::std::ostream* os) const {
*os << "(";
matcher1_.DescribeTo(os);
*os << ") or (";
matcher2_.DescribeTo(os);
for (size_t i = 0; i < matchers_.size(); ++i) {
if (i != 0) *os << ") or (";
matchers_[i].DescribeTo(os);
}
*os << ")";
}
virtual void DescribeNegationTo(::std::ostream* os) const {
*os << "(";
matcher1_.DescribeNegationTo(os);
*os << ") and (";
matcher2_.DescribeNegationTo(os);
for (size_t i = 0; i < matchers_.size(); ++i) {
if (i != 0) *os << ") and (";
matchers_[i].DescribeNegationTo(os);
}
*os << ")";
}
virtual bool MatchAndExplain(GTEST_REFERENCE_TO_CONST_(T) x,
MatchResultListener* listener) const {
std::string no_match_result;
// If either matcher1_ or matcher2_ matches x, we just need to
// explain why *one* of them matches.
StringMatchResultListener listener1;
if (matcher1_.MatchAndExplain(x, &listener1)) {
*listener << listener1.str();
for (size_t i = 0; i < matchers_.size(); ++i) {
StringMatchResultListener slistener;
if (matchers_[i].MatchAndExplain(x, &slistener)) {
*listener << slistener.str();
return true;
} else {
if (no_match_result.empty()) {
no_match_result = slistener.str();
} else {
std::string result = slistener.str();
if (!result.empty()) {
no_match_result += ", and ";
no_match_result += result;
}
}
}
StringMatchResultListener listener2;
if (matcher2_.MatchAndExplain(x, &listener2)) {
*listener << listener2.str();
return true;
}
// Otherwise we need to explain why *both* of them fail.
const std::string s1 = listener1.str();
const std::string s2 = listener2.str();
if (s1 == "") {
*listener << s2;
} else {
*listener << s1;
if (s2 != "") {
*listener << ", and " << s2;
}
}
*listener << no_match_result;
return false;
}
private:
const Matcher<T> matcher1_;
const Matcher<T> matcher2_;
const std::vector<Matcher<T> > matchers_;
GTEST_DISALLOW_ASSIGN_(EitherOfMatcherImpl);
GTEST_DISALLOW_ASSIGN_(AnyOfMatcherImpl);
};
#if GTEST_LANG_CXX11
// AnyOfMatcher is used for the variadic implementation of AnyOf(m_1, m_2, ...).
template <typename... Args>
using AnyOfMatcher = VariadicMatcher<EitherOfMatcherImpl, Args...>;
using AnyOfMatcher = VariadicMatcher<AnyOfMatcherImpl, Args...>;
#endif // GTEST_LANG_CXX11
@ -1973,8 +1935,10 @@ class EitherOfMatcher {
// both Matcher1 and Matcher2 can match.
template <typename T>
operator Matcher<T>() const {
return Matcher<T>(new EitherOfMatcherImpl<T>(
SafeMatcherCast<T>(matcher1_), SafeMatcherCast<T>(matcher2_)));
std::vector<Matcher<T> > values;
values.push_back(SafeMatcherCast<T>(matcher1_));
values.push_back(SafeMatcherCast<T>(matcher2_));
return Matcher<T>(new AnyOfMatcherImpl<T>(internal::move(values)));
}
private:
@ -2408,6 +2372,7 @@ class PointeeMatcher {
GTEST_DISALLOW_ASSIGN_(PointeeMatcher);
};
#if GTEST_HAS_RTTI
// Implements the WhenDynamicCastTo<T>(m) matcher that matches a pointer or
// reference that matches inner_matcher when dynamic_cast<T> is applied.
// The result of dynamic_cast<To> is forwarded to the inner matcher.
@ -2434,11 +2399,7 @@ class WhenDynamicCastToMatcherBase {
const Matcher<To> matcher_;
static std::string GetToName() {
#if GTEST_HAS_RTTI
return GetTypeName<To>();
#else // GTEST_HAS_RTTI
return "the target type";
#endif // GTEST_HAS_RTTI
}
private:
@ -2459,7 +2420,7 @@ class WhenDynamicCastToMatcher : public WhenDynamicCastToMatcherBase<To> {
template <typename From>
bool MatchAndExplain(From from, MatchResultListener* listener) const {
// TODO(sbenza): Add more detail on failures. ie did the dyn_cast fail?
// FIXME: Add more detail on failures. ie did the dyn_cast fail?
To to = dynamic_cast<To>(from);
return MatchPrintAndExplain(to, this->matcher_, listener);
}
@ -2484,6 +2445,7 @@ class WhenDynamicCastToMatcher<To&> : public WhenDynamicCastToMatcherBase<To&> {
return MatchPrintAndExplain(*to, this->matcher_, listener);
}
};
#endif // GTEST_HAS_RTTI
// Implements the Field() matcher for matching a field (i.e. member
// variable) of an object.
@ -4140,7 +4102,8 @@ class VariantMatcher {
private:
static std::string GetTypeName() {
#if GTEST_HAS_RTTI
return internal::GetTypeName<T>();
GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(
return internal::GetTypeName<T>());
#endif
return "the element type";
}
@ -4200,7 +4163,8 @@ class AnyCastMatcher {
private:
static std::string GetTypeName() {
#if GTEST_HAS_RTTI
return internal::GetTypeName<T>();
GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(
return internal::GetTypeName<T>());
#endif
return "the element type";
}
@ -4476,6 +4440,7 @@ inline internal::PointeeMatcher<InnerMatcher> Pointee(
return internal::PointeeMatcher<InnerMatcher>(inner_matcher);
}
#if GTEST_HAS_RTTI
// Creates a matcher that matches a pointer or reference that matches
// inner_matcher when dynamic_cast<To> is applied.
// The result of dynamic_cast<To> is forwarded to the inner matcher.
@ -4488,6 +4453,7 @@ WhenDynamicCastTo(const Matcher<To>& inner_matcher) {
return MakePolymorphicMatcher(
internal::WhenDynamicCastToMatcher<To>(inner_matcher));
}
#endif // GTEST_HAS_RTTI
// Creates a matcher that matches an object whose given field matches
// 'matcher'. For example,
@ -4564,6 +4530,20 @@ Property(PropertyType (Class::*property)() const &,
property,
MatcherCast<GTEST_REFERENCE_TO_CONST_(PropertyType)>(matcher)));
}
// Three-argument form for reference-qualified member functions.
template <typename Class, typename PropertyType, typename PropertyMatcher>
inline PolymorphicMatcher<internal::PropertyMatcher<
Class, PropertyType, PropertyType (Class::*)() const &> >
Property(const std::string& property_name,
PropertyType (Class::*property)() const &,
const PropertyMatcher& matcher) {
return MakePolymorphicMatcher(
internal::PropertyMatcher<Class, PropertyType,
PropertyType (Class::*)() const &>(
property_name, property,
MatcherCast<GTEST_REFERENCE_TO_CONST_(PropertyType)>(matcher)));
}
#endif
// Creates a matcher that matches an object iff the result of applying
@ -5200,13 +5180,34 @@ std::string DescribeMatcher(const M& matcher, bool negation = false) {
// Define variadic matcher versions. They are overloaded in
// gmock-generated-matchers.h for the cases supported by pre C++11 compilers.
template <typename... Args>
inline internal::AllOfMatcher<Args...> AllOf(const Args&... matchers) {
return internal::AllOfMatcher<Args...>(matchers...);
internal::AllOfMatcher<typename std::decay<const Args&>::type...> AllOf(
const Args&... matchers) {
return internal::AllOfMatcher<typename std::decay<const Args&>::type...>(
matchers...);
}
template <typename... Args>
inline internal::AnyOfMatcher<Args...> AnyOf(const Args&... matchers) {
return internal::AnyOfMatcher<Args...>(matchers...);
internal::AnyOfMatcher<typename std::decay<const Args&>::type...> AnyOf(
const Args&... matchers) {
return internal::AnyOfMatcher<typename std::decay<const Args&>::type...>(
matchers...);
}
template <typename... Args>
internal::ElementsAreMatcher<tuple<typename std::decay<const Args&>::type...>>
ElementsAre(const Args&... matchers) {
return internal::ElementsAreMatcher<
tuple<typename std::decay<const Args&>::type...>>(
make_tuple(matchers...));
}
template <typename... Args>
internal::UnorderedElementsAreMatcher<
tuple<typename std::decay<const Args&>::type...>>
UnorderedElementsAre(const Args&... matchers) {
return internal::UnorderedElementsAreMatcher<
tuple<typename std::decay<const Args&>::type...>>(
make_tuple(matchers...));
}
#endif // GTEST_LANG_CXX11

View File

@ -26,13 +26,14 @@
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Author: wan@google.com (Zhanyong Wan)
// Google Mock - a framework for writing C++ mock classes.
//
// This file implements some actions that depend on gmock-generated-actions.h.
// GOOGLETEST_CM0002 DO NOT DELETE
#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_MORE_ACTIONS_H_
#define GMOCK_INCLUDE_GMOCK_GMOCK_MORE_ACTIONS_H_

View File

@ -26,8 +26,7 @@
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Author: marcus.boerger@google.com (Marcus Boerger)
// Google Mock - a framework for writing C++ mock classes.
//
@ -36,6 +35,8 @@
// Note that tests are implemented in gmock-matchers_test.cc rather than
// gmock-more-matchers-test.cc.
// GOOGLETEST_CM0002 DO NOT DELETE
#ifndef GMOCK_GMOCK_MORE_MATCHERS_H_
#define GMOCK_GMOCK_MORE_MATCHERS_H_
@ -46,8 +47,11 @@ namespace testing {
// Silence C4100 (unreferenced formal
// parameter) for MSVC
#ifdef _MSC_VER
# pragma warning(push)
# pragma warning(disable:4100)
#if (_MSC_VER == 1900)
// and silence C4800 (C4800: 'int *const ': forcing value
// to bool 'true' or 'false') for MSVC 14
# pragma warning(disable:4800)
#endif
#endif
@ -78,6 +82,11 @@ MATCHER(IsFalse, negation ? "is true" : "is false") {
return !static_cast<bool>(arg);
}
#ifdef _MSC_VER
# pragma warning(pop)
#endif
} // namespace testing
#endif // GMOCK_GMOCK_MORE_MATCHERS_H_

View File

@ -26,8 +26,7 @@
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Author: wan@google.com (Zhanyong Wan)
// Google Mock - a framework for writing C++ mock classes.
//
@ -57,6 +56,8 @@
// where all clauses are optional, and .InSequence()/.After()/
// .WillOnce() can appear any number of times.
// GOOGLETEST_CM0002 DO NOT DELETE
#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_
#define GMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_
@ -103,11 +104,6 @@ class ExpectationTester;
// Base class for function mockers.
template <typename F> class FunctionMockerBase;
// Uninteresting call behavior mixins.
template <typename M> class NiceMockBase;
template <typename M> class NaggyMockBase;
template <typename M> class StrictMockBase;
// Protects the mock object registry (in class Mock), all function
// mockers, and all expectations.
//
@ -188,7 +184,7 @@ class GTEST_API_ UntypedFunctionMockerBase {
// this information in the global mock registry. Will be called
// whenever an EXPECT_CALL() or ON_CALL() is executed on this mock
// method.
// TODO(wan@google.com): rename to SetAndRegisterOwner().
// FIXME: rename to SetAndRegisterOwner().
void RegisterOwner(const void* mock_obj)
GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
@ -408,13 +404,13 @@ class GTEST_API_ Mock {
friend class internal::FunctionMockerBase;
template <typename M>
friend class internal::NiceMockBase;
friend class NiceMock;
template <typename M>
friend class internal::NaggyMockBase;
friend class NaggyMock;
template <typename M>
friend class internal::StrictMockBase;
friend class StrictMock;
// Tells Google Mock to allow uninteresting calls on the given mock
// object.
@ -1211,7 +1207,7 @@ class TypedExpectation : public ExpectationBase {
mocker->DescribeDefaultActionTo(args, what);
DescribeCallCountTo(why);
// TODO(wan@google.com): allow the user to control whether
// FIXME: allow the user to control whether
// unexpected calls should fail immediately or continue using a
// flag --gmock_unexpected_calls_are_fatal.
return NULL;
@ -1287,6 +1283,13 @@ class MockSpec {
file, line, source_text, matchers_);
}
// This operator overload is used to swallow the superfluous parameter list
// introduced by the ON/EXPECT_CALL macros. See the macro comments for more
// explanation.
MockSpec<F>& operator()(const internal::WithoutMatchers&, void* const) {
return *this;
}
private:
template <typename Function>
friend class internal::FunctionMocker;
@ -1841,17 +1844,76 @@ inline Expectation::Expectation(internal::ExpectationBase& exp) // NOLINT
} // namespace testing
// A separate macro is required to avoid compile errors when the name
// of the method used in call is a result of macro expansion.
// See CompilesWithMethodNameExpandedFromMacro tests in
// internal/gmock-spec-builders_test.cc for more details.
#define GMOCK_ON_CALL_IMPL_(obj, call) \
((obj).gmock_##call).InternalDefaultActionSetAt(__FILE__, __LINE__, \
#obj, #call)
#define ON_CALL(obj, call) GMOCK_ON_CALL_IMPL_(obj, call)
// Implementation for ON_CALL and EXPECT_CALL macros. A separate macro is
// required to avoid compile errors when the name of the method used in call is
// a result of macro expansion. See CompilesWithMethodNameExpandedFromMacro
// tests in internal/gmock-spec-builders_test.cc for more details.
//
// This macro supports statements both with and without parameter matchers. If
// the parameter list is omitted, gMock will accept any parameters, which allows
// tests to be written that don't need to encode the number of method
// parameter. This technique may only be used for non-overloaded methods.
//
// // These are the same:
// ON_CALL(mock, NoArgsMethod()).WillByDefault(...);
// ON_CALL(mock, NoArgsMethod).WillByDefault(...);
//
// // As are these:
// ON_CALL(mock, TwoArgsMethod(_, _)).WillByDefault(...);
// ON_CALL(mock, TwoArgsMethod).WillByDefault(...);
//
// // Can also specify args if you want, of course:
// ON_CALL(mock, TwoArgsMethod(_, 45)).WillByDefault(...);
//
// // Overloads work as long as you specify parameters:
// ON_CALL(mock, OverloadedMethod(_)).WillByDefault(...);
// ON_CALL(mock, OverloadedMethod(_, _)).WillByDefault(...);
//
// // Oops! Which overload did you want?
// ON_CALL(mock, OverloadedMethod).WillByDefault(...);
// => ERROR: call to member function 'gmock_OverloadedMethod' is ambiguous
//
// How this works: The mock class uses two overloads of the gmock_Method
// expectation setter method plus an operator() overload on the MockSpec object.
// In the matcher list form, the macro expands to:
//
// // This statement:
// ON_CALL(mock, TwoArgsMethod(_, 45))...
//
// // ...expands to:
// mock.gmock_TwoArgsMethod(_, 45)(WithoutMatchers(), nullptr)...
// |-------------v---------------||------------v-------------|
// invokes first overload swallowed by operator()
//
// // ...which is essentially:
// mock.gmock_TwoArgsMethod(_, 45)...
//
// Whereas the form without a matcher list:
//
// // This statement:
// ON_CALL(mock, TwoArgsMethod)...
//
// // ...expands to:
// mock.gmock_TwoArgsMethod(WithoutMatchers(), nullptr)...
// |-----------------------v--------------------------|
// invokes second overload
//
// // ...which is essentially:
// mock.gmock_TwoArgsMethod(_, _)...
//
// The WithoutMatchers() argument is used to disambiguate overloads and to
// block the caller from accidentally invoking the second overload directly. The
// second argument is an internal type derived from the method signature. The
// failure to disambiguate two overloads of this method in the ON_CALL statement
// is how we block callers from setting expectations on overloaded methods.
#define GMOCK_ON_CALL_IMPL_(mock_expr, Setter, call) \
((mock_expr).gmock_##call)(::testing::internal::GetWithoutMatchers(), NULL) \
.Setter(__FILE__, __LINE__, #mock_expr, #call)
#define GMOCK_EXPECT_CALL_IMPL_(obj, call) \
((obj).gmock_##call).InternalExpectedAt(__FILE__, __LINE__, #obj, #call)
#define EXPECT_CALL(obj, call) GMOCK_EXPECT_CALL_IMPL_(obj, call)
#define ON_CALL(obj, call) \
GMOCK_ON_CALL_IMPL_(obj, InternalDefaultActionSetAt, call)
#define EXPECT_CALL(obj, call) \
GMOCK_ON_CALL_IMPL_(obj, InternalExpectedAt, call)
#endif // GMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_

View File

@ -26,13 +26,14 @@
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Author: wan@google.com (Zhanyong Wan)
// Google Mock - a framework for writing C++ mock classes.
//
// This is the main header file a user should include.
// GOOGLETEST_CM0002 DO NOT DELETE
#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_H_
#define GMOCK_INCLUDE_GMOCK_GMOCK_H_

View File

@ -0,0 +1,16 @@
# Customization Points
The custom directory is an injection point for custom user configurations.
## Header `gmock-port.h`
The following macros can be defined:
### Flag related macros:
* `GMOCK_DECLARE_bool_(name)`
* `GMOCK_DECLARE_int32_(name)`
* `GMOCK_DECLARE_string_(name)`
* `GMOCK_DEFINE_bool_(name, default_val, doc)`
* `GMOCK_DEFINE_int32_(name, default_val, doc)`
* `GMOCK_DEFINE_string_(name, default_val, doc)`

View File

@ -2,6 +2,8 @@
// pump.py gmock-generated-actions.h.pump
// DO NOT EDIT BY HAND!!!
// GOOGLETEST_CM0002 DO NOT DELETE
#ifndef GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_GENERATED_ACTIONS_H_
#define GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_GENERATED_ACTIONS_H_

View File

@ -1,9 +1,11 @@
$$ -*- mode: c++; -*-
$$ This is a Pump source file (http://go/pump). Please use Pump to convert
$$ This is a Pump source file. Please use Pump to convert
$$ it to callback-actions.h.
$$
$var max_callback_arity = 5
$$}} This meta comment fixes auto-indentation in editors.
// GOOGLETEST_CM0002 DO NOT DELETE
#ifndef GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_GENERATED_ACTIONS_H_
#define GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_GENERATED_ACTIONS_H_

View File

@ -27,12 +27,10 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// ============================================================
// An installation-specific extension point for gmock-matchers.h.
// ============================================================
//
// Adds google3 callback support to CallableTraits.
// Injection point for custom user configurations. See README for details
//
// GOOGLETEST_CM0002 DO NOT DELETE
#ifndef GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_MATCHERS_H_
#define GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_MATCHERS_H_
#endif // GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_MATCHERS_H_

View File

@ -27,19 +27,12 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Injection point for custom user configurations.
// The following macros can be defined:
//
// Flag related macros:
// GMOCK_DECLARE_bool_(name)
// GMOCK_DECLARE_int32_(name)
// GMOCK_DECLARE_string_(name)
// GMOCK_DEFINE_bool_(name, default_val, doc)
// GMOCK_DEFINE_int32_(name, default_val, doc)
// GMOCK_DEFINE_string_(name, default_val, doc)
// Injection point for custom user configurations. See README for details
//
// ** Custom implementation starts here **
// GOOGLETEST_CM0002 DO NOT DELETE
#ifndef GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_PORT_H_
#define GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_PORT_H_

View File

@ -30,14 +30,15 @@
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Author: wan@google.com (Zhanyong Wan)
// Google Mock - a framework for writing C++ mock classes.
//
// This file contains template meta-programming utility classes needed
// for implementing Google Mock.
// GOOGLETEST_CM0002 DO NOT DELETE
#ifndef GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_GENERATED_INTERNAL_UTILS_H_
#define GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_GENERATED_INTERNAL_UTILS_H_

View File

@ -31,14 +31,15 @@ $var n = 10 $$ The maximum arity we support.
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Author: wan@google.com (Zhanyong Wan)
// Google Mock - a framework for writing C++ mock classes.
//
// This file contains template meta-programming utility classes needed
// for implementing Google Mock.
// GOOGLETEST_CM0002 DO NOT DELETE
#ifndef GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_GENERATED_INTERNAL_UTILS_H_
#define GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_GENERATED_INTERNAL_UTILS_H_

View File

@ -26,8 +26,7 @@
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Author: wan@google.com (Zhanyong Wan)
// Google Mock - a framework for writing C++ mock classes.
//
@ -35,6 +34,8 @@
// Mock. They are subject to change without notice, so please DO NOT
// USE THEM IN USER CODE.
// GOOGLETEST_CM0002 DO NOT DELETE
#ifndef GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_INTERNAL_UTILS_H_
#define GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_INTERNAL_UTILS_H_
@ -48,6 +49,14 @@
namespace testing {
namespace internal {
// Silence MSVC C4100 (unreferenced formal parameter) and
// C4805('==': unsafe mix of type 'const int' and type 'const bool')
#ifdef _MSC_VER
# pragma warning(push)
# pragma warning(disable:4100)
# pragma warning(disable:4805)
#endif
// Joins a vector of strings as if they are fields of a tuple; returns
// the joined string.
GTEST_API_ std::string JoinAsTuple(const Strings& fields);
@ -336,7 +345,22 @@ GTEST_API_ bool LogIsVisible(LogSeverity severity);
GTEST_API_ void Log(LogSeverity severity, const std::string& message,
int stack_frames_to_skip);
// TODO(wan@google.com): group all type utilities together.
// A marker class that is used to resolve parameterless expectations to the
// correct overload. This must not be instantiable, to prevent client code from
// accidentally resolving to the overload; for example:
//
// ON_CALL(mock, Method({}, nullptr))...
//
class WithoutMatchers {
private:
WithoutMatchers() {}
friend GTEST_API_ WithoutMatchers GetWithoutMatchers();
};
// Internal use only: access the singleton instance of WithoutMatchers.
GTEST_API_ WithoutMatchers GetWithoutMatchers();
// FIXME: group all type utilities together.
// Type traits.
@ -510,7 +534,7 @@ struct BooleanConstant {};
// Emit an assertion failure due to incorrect DoDefault() usage. Out-of-lined to
// reduce code size.
void IllegalDoDefault(const char* file, int line);
GTEST_API_ void IllegalDoDefault(const char* file, int line);
#if GTEST_LANG_CXX11
// Helper types for Apply() below.
@ -539,6 +563,12 @@ auto Apply(F&& f, Tuple&& args)
make_int_pack<std::tuple_size<Tuple>::value>());
}
#endif
#ifdef _MSC_VER
# pragma warning(pop)
#endif
} // namespace internal
} // namespace testing

View File

@ -26,8 +26,7 @@
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Author: vadimb@google.com (Vadim Berman)
//
// Low-level types and utilities for porting Google Mock to various
// platforms. All macros ending with _ and symbols defined in an
@ -36,6 +35,8 @@
// end with _ are part of Google Mock's public API and can be used by
// code outside Google Mock.
// GOOGLETEST_CM0002 DO NOT DELETE
#ifndef GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_PORT_H_
#define GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_PORT_H_

View File

@ -1,11 +1,10 @@
The Google Mock class generator is an application that is part of cppclean.
For more information about cppclean, see the README.cppclean file or
visit http://code.google.com/p/cppclean/
For more information about cppclean, visit http://code.google.com/p/cppclean/
cppclean requires Python 2.3.5 or later. If you don't have Python installed
on your system, you will also need to install it. You can download Python
from: http://www.python.org/download/releases/
The mock generator requires Python 2.3.5 or later. If you don't have Python
installed on your system, you will also need to install it. You can download
Python from: http://www.python.org/download/releases/
To use the Google Mock class generator, you need to call it
on the command line passing the header file and class for which you want

View File

@ -242,7 +242,7 @@ class AbstractRpcServer(object):
The authentication process works as follows:
1) We get a username and password from the user
2) We use ClientLogin to obtain an AUTH token for the user
(see http://code.google.com/apis/accounts/AuthForInstalledApps.html).
(see https://developers.google.com/identity/protocols/AuthForInstalledApps).
3) We pass the auth token to /_ah/login on the server to obtain an
authentication cookie. If login was successful, it tries to redirect
us to the URL we provided.
@ -506,7 +506,7 @@ def EncodeMultipartFormData(fields, files):
(content_type, body) ready for httplib.HTTP instance.
Source:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/146306
https://web.archive.org/web/20160116052001/code.activestate.com/recipes/146306
"""
BOUNDARY = '-M-A-G-I-C---B-O-U-N-D-A-R-Y-'
CRLF = '\r\n'
@ -807,7 +807,7 @@ class SubversionVCS(VersionControlSystem):
# svn cat translates keywords but svn diff doesn't. As a result of this
# behavior patching.PatchChunks() fails with a chunk mismatch error.
# This part was originally written by the Review Board development team
# who had the same problem (http://reviews.review-board.org/r/276/).
# who had the same problem (https://reviews.reviewboard.org/r/276/).
# Mapping of keywords to known aliases
svn_keywords = {
# Standard keywords
@ -860,7 +860,7 @@ class SubversionVCS(VersionControlSystem):
status_lines = status.splitlines()
# If file is in a cl, the output will begin with
# "\n--- Changelist 'cl_name':\n". See
# http://svn.collab.net/repos/svn/trunk/notes/changelist-design.txt
# https://web.archive.org/web/20090918234815/svn.collab.net/repos/svn/trunk/notes/changelist-design.txt
if (len(status_lines) == 3 and
not status_lines[0] and
status_lines[1].startswith("--- Changelist")):

View File

@ -26,8 +26,7 @@
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Author: wan@google.com (Zhanyong Wan)
//
// Google C++ Mocking Framework (Google Mock)
//

View File

@ -26,8 +26,7 @@
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Author: wan@google.com (Zhanyong Wan)
// Google Mock - a framework for writing C++ mock classes.
//

View File

@ -26,8 +26,7 @@
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Author: wan@google.com (Zhanyong Wan)
// Google Mock - a framework for writing C++ mock classes.
//
@ -188,7 +187,9 @@ GTEST_API_ void Log(LogSeverity severity, const std::string& message,
std::cout << ::std::flush;
}
void IllegalDoDefault(const char* file, int line) {
GTEST_API_ WithoutMatchers GetWithoutMatchers() { return WithoutMatchers(); }
GTEST_API_ void IllegalDoDefault(const char* file, int line) {
internal::Assert(
false, file, line,
"You are using DoDefault() inside a composite action like "

View File

@ -26,8 +26,7 @@
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Author: wan@google.com (Zhanyong Wan)
// Google Mock - a framework for writing C++ mock classes.
//

View File

@ -26,8 +26,7 @@
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Author: wan@google.com (Zhanyong Wan)
// Google Mock - a framework for writing C++ mock classes.
//
@ -49,6 +48,15 @@
# include <unistd.h> // NOLINT
#endif
// Silence C4800 (C4800: 'int *const ': forcing value
// to bool 'true' or 'false') for MSVC 14,15
#ifdef _MSC_VER
#if _MSC_VER <= 1900
# pragma warning(push)
# pragma warning(disable:4800)
#endif
#endif
namespace testing {
namespace internal {
@ -598,7 +606,7 @@ class MockObjectRegistry {
if (it->second.leakable) // The user said it's fine to leak this object.
continue;
// TODO(wan@google.com): Print the type of the leaked object.
// FIXME: Print the type of the leaked object.
// This can help the user identify the leaked object.
std::cout << "\n";
const MockObjectState& state = it->second;
@ -774,7 +782,7 @@ void Mock::RegisterUseByOnCallOrExpectCall(const void* mock_obj,
const TestInfo* const test_info =
UnitTest::GetInstance()->current_test_info();
if (test_info != NULL) {
// TODO(wan@google.com): record the test case name when the
// 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();
@ -866,3 +874,9 @@ InSequence::~InSequence() {
}
} // namespace testing
#ifdef _MSC_VER
#if _MSC_VER <= 1900
# pragma warning(pop)
#endif
#endif

View File

@ -26,15 +26,14 @@
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Author: wan@google.com (Zhanyong Wan)
#include "gmock/gmock.h"
#include "gmock/internal/gmock-port.h"
namespace testing {
// TODO(wan@google.com): support using environment variables to
// FIXME: support using environment variables to
// control the flag values, like what Google Test does.
GMOCK_DEFINE_bool_(catch_leaked_mocks, true,

View File

@ -26,8 +26,7 @@
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Author: wan@google.com (Zhanyong Wan)
#include <iostream>
#include "gmock/gmock.h"
@ -37,7 +36,8 @@
// causes a link error when _tmain is defined in a static library and UNICODE
// is enabled. For this reason instead of _tmain, main function is used on
// Windows. See the following link to track the current status of this bug:
// http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=394464 // NOLINT
// https://web.archive.org/web/20170912203238/connect.microsoft.com/VisualStudio/feedback/details/394464/wmain-link-error-in-the-static-library
// // NOLINT
#if GTEST_OS_WINDOWS_MOBILE
# include <tchar.h> // NOLINT

View File

@ -26,13 +26,21 @@
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Author: wan@google.com (Zhanyong Wan)
// Google Mock - a framework for writing C++ mock classes.
//
// This file tests the built-in actions.
// Silence C4800 (C4800: 'int *const ': forcing value
// to bool 'true' or 'false') for MSVC 14,15
#ifdef _MSC_VER
#if _MSC_VER <= 1900
# pragma warning(push)
# pragma warning(disable:4800)
#endif
#endif
#include "gmock/gmock-actions.h"
#include <algorithm>
#include <iterator>
@ -65,6 +73,7 @@ using testing::ReturnRef;
using testing::ReturnRefOfCopy;
using testing::SetArgPointee;
using testing::SetArgumentPointee;
using testing::Unused;
using testing::_;
using testing::get;
using testing::internal::BuiltInDefaultValue;
@ -78,10 +87,6 @@ using testing::tuple_element;
using testing::SetErrnoAndReturn;
#endif
#if GTEST_HAS_PROTOBUF_
using testing::internal::TestMessage;
#endif // GTEST_HAS_PROTOBUF_
// Tests that BuiltInDefaultValue<T*>::Get() returns NULL.
TEST(BuiltInDefaultValueTest, IsNullForPointerTypes) {
EXPECT_TRUE(BuiltInDefaultValue<int*>::Get() == NULL);
@ -705,6 +710,8 @@ class MockClass {
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:
@ -756,7 +763,7 @@ TEST(DoDefaultDeathTest, DiesIfUsedInCompositeAction) {
}
// Tests that DoDefault() returns the default value set by
// DefaultValue<T>::Set() when it's not overridden by an ON_CALL().
// DefaultValue<T>::Set() when it's not overriden by an ON_CALL().
TEST(DoDefaultTest, ReturnsUserSpecifiedPerTypeDefaultValueWhenThereIsOne) {
DefaultValue<int>::Set(1);
MockClass mock;
@ -883,105 +890,6 @@ TEST(SetArgPointeeTest, AcceptsWideCharPointer) {
# endif
}
#if GTEST_HAS_PROTOBUF_
// Tests that SetArgPointee<N>(proto_buffer) sets the v1 protobuf
// variable pointed to by the N-th (0-based) argument to proto_buffer.
TEST(SetArgPointeeTest, SetsTheNthPointeeOfProtoBufferType) {
TestMessage* const msg = new TestMessage;
msg->set_member("yes");
TestMessage orig_msg;
orig_msg.CopyFrom(*msg);
Action<void(bool, TestMessage*)> a = SetArgPointee<1>(*msg);
// SetArgPointee<N>(proto_buffer) makes a copy of proto_buffer
// s.t. the action works even when the original proto_buffer has
// died. We ensure this behavior by deleting msg before using the
// action.
delete msg;
TestMessage dest;
EXPECT_FALSE(orig_msg.Equals(dest));
a.Perform(make_tuple(true, &dest));
EXPECT_TRUE(orig_msg.Equals(dest));
}
// Tests that SetArgPointee<N>(proto_buffer) sets the
// ::ProtocolMessage variable pointed to by the N-th (0-based)
// argument to proto_buffer.
TEST(SetArgPointeeTest, SetsTheNthPointeeOfProtoBufferBaseType) {
TestMessage* const msg = new TestMessage;
msg->set_member("yes");
TestMessage orig_msg;
orig_msg.CopyFrom(*msg);
Action<void(bool, ::ProtocolMessage*)> a = SetArgPointee<1>(*msg);
// SetArgPointee<N>(proto_buffer) makes a copy of proto_buffer
// s.t. the action works even when the original proto_buffer has
// died. We ensure this behavior by deleting msg before using the
// action.
delete msg;
TestMessage dest;
::ProtocolMessage* const dest_base = &dest;
EXPECT_FALSE(orig_msg.Equals(dest));
a.Perform(make_tuple(true, dest_base));
EXPECT_TRUE(orig_msg.Equals(dest));
}
// Tests that SetArgPointee<N>(proto2_buffer) sets the v2
// protobuf variable pointed to by the N-th (0-based) argument to
// proto2_buffer.
TEST(SetArgPointeeTest, SetsTheNthPointeeOfProto2BufferType) {
using testing::internal::FooMessage;
FooMessage* const msg = new FooMessage;
msg->set_int_field(2);
msg->set_string_field("hi");
FooMessage orig_msg;
orig_msg.CopyFrom(*msg);
Action<void(bool, FooMessage*)> a = SetArgPointee<1>(*msg);
// SetArgPointee<N>(proto2_buffer) makes a copy of
// proto2_buffer s.t. the action works even when the original
// proto2_buffer has died. We ensure this behavior by deleting msg
// before using the action.
delete msg;
FooMessage dest;
dest.set_int_field(0);
a.Perform(make_tuple(true, &dest));
EXPECT_EQ(2, dest.int_field());
EXPECT_EQ("hi", dest.string_field());
}
// Tests that SetArgPointee<N>(proto2_buffer) sets the
// proto2::Message variable pointed to by the N-th (0-based) argument
// to proto2_buffer.
TEST(SetArgPointeeTest, SetsTheNthPointeeOfProto2BufferBaseType) {
using testing::internal::FooMessage;
FooMessage* const msg = new FooMessage;
msg->set_int_field(2);
msg->set_string_field("hi");
FooMessage orig_msg;
orig_msg.CopyFrom(*msg);
Action<void(bool, ::proto2::Message*)> a = SetArgPointee<1>(*msg);
// SetArgPointee<N>(proto2_buffer) makes a copy of
// proto2_buffer s.t. the action works even when the original
// proto2_buffer has died. We ensure this behavior by deleting msg
// before using the action.
delete msg;
FooMessage dest;
dest.set_int_field(0);
::proto2::Message* const dest_base = &dest;
a.Perform(make_tuple(true, dest_base));
EXPECT_EQ(2, dest.int_field());
EXPECT_EQ("hi", dest.string_field());
}
#endif // GTEST_HAS_PROTOBUF_
// Tests that SetArgumentPointee<N>(v) sets the variable pointed to by
// the N-th (0-based) argument to v.
TEST(SetArgumentPointeeTest, SetsTheNthPointee) {
@ -1002,105 +910,6 @@ TEST(SetArgumentPointeeTest, SetsTheNthPointee) {
EXPECT_EQ('a', ch);
}
#if GTEST_HAS_PROTOBUF_
// Tests that SetArgumentPointee<N>(proto_buffer) sets the v1 protobuf
// variable pointed to by the N-th (0-based) argument to proto_buffer.
TEST(SetArgumentPointeeTest, SetsTheNthPointeeOfProtoBufferType) {
TestMessage* const msg = new TestMessage;
msg->set_member("yes");
TestMessage orig_msg;
orig_msg.CopyFrom(*msg);
Action<void(bool, TestMessage*)> a = SetArgumentPointee<1>(*msg);
// SetArgumentPointee<N>(proto_buffer) makes a copy of proto_buffer
// s.t. the action works even when the original proto_buffer has
// died. We ensure this behavior by deleting msg before using the
// action.
delete msg;
TestMessage dest;
EXPECT_FALSE(orig_msg.Equals(dest));
a.Perform(make_tuple(true, &dest));
EXPECT_TRUE(orig_msg.Equals(dest));
}
// Tests that SetArgumentPointee<N>(proto_buffer) sets the
// ::ProtocolMessage variable pointed to by the N-th (0-based)
// argument to proto_buffer.
TEST(SetArgumentPointeeTest, SetsTheNthPointeeOfProtoBufferBaseType) {
TestMessage* const msg = new TestMessage;
msg->set_member("yes");
TestMessage orig_msg;
orig_msg.CopyFrom(*msg);
Action<void(bool, ::ProtocolMessage*)> a = SetArgumentPointee<1>(*msg);
// SetArgumentPointee<N>(proto_buffer) makes a copy of proto_buffer
// s.t. the action works even when the original proto_buffer has
// died. We ensure this behavior by deleting msg before using the
// action.
delete msg;
TestMessage dest;
::ProtocolMessage* const dest_base = &dest;
EXPECT_FALSE(orig_msg.Equals(dest));
a.Perform(make_tuple(true, dest_base));
EXPECT_TRUE(orig_msg.Equals(dest));
}
// Tests that SetArgumentPointee<N>(proto2_buffer) sets the v2
// protobuf variable pointed to by the N-th (0-based) argument to
// proto2_buffer.
TEST(SetArgumentPointeeTest, SetsTheNthPointeeOfProto2BufferType) {
using testing::internal::FooMessage;
FooMessage* const msg = new FooMessage;
msg->set_int_field(2);
msg->set_string_field("hi");
FooMessage orig_msg;
orig_msg.CopyFrom(*msg);
Action<void(bool, FooMessage*)> a = SetArgumentPointee<1>(*msg);
// SetArgumentPointee<N>(proto2_buffer) makes a copy of
// proto2_buffer s.t. the action works even when the original
// proto2_buffer has died. We ensure this behavior by deleting msg
// before using the action.
delete msg;
FooMessage dest;
dest.set_int_field(0);
a.Perform(make_tuple(true, &dest));
EXPECT_EQ(2, dest.int_field());
EXPECT_EQ("hi", dest.string_field());
}
// Tests that SetArgumentPointee<N>(proto2_buffer) sets the
// proto2::Message variable pointed to by the N-th (0-based) argument
// to proto2_buffer.
TEST(SetArgumentPointeeTest, SetsTheNthPointeeOfProto2BufferBaseType) {
using testing::internal::FooMessage;
FooMessage* const msg = new FooMessage;
msg->set_int_field(2);
msg->set_string_field("hi");
FooMessage orig_msg;
orig_msg.CopyFrom(*msg);
Action<void(bool, ::proto2::Message*)> a = SetArgumentPointee<1>(*msg);
// SetArgumentPointee<N>(proto2_buffer) makes a copy of
// proto2_buffer s.t. the action works even when the original
// proto2_buffer has died. We ensure this behavior by deleting msg
// before using the action.
delete msg;
FooMessage dest;
dest.set_int_field(0);
::proto2::Message* const dest_base = &dest;
a.Perform(make_tuple(true, dest_base));
EXPECT_EQ(2, dest.int_field());
EXPECT_EQ("hi", dest.string_field());
}
#endif // GTEST_HAS_PROTOBUF_
// Sample functions and functors for testing Invoke() and etc.
int Nullary() { return 1; }
@ -1411,6 +1220,153 @@ TEST(MockMethodTest, CanReturnMoveOnlyValue_Invoke) {
EXPECT_EQ(7, *vresult[0]);
}
TEST(MockMethodTest, CanTakeMoveOnlyValue) {
MockClass mock;
auto make = [](int i) { return std::unique_ptr<int>(new int(i)); };
EXPECT_CALL(mock, TakeUnique(_)).WillRepeatedly([](std::unique_ptr<int> i) {
return *i;
});
// DoAll() does not compile, since it would move from its arguments twice.
// EXPECT_CALL(mock, TakeUnique(_, _))
// .WillRepeatedly(DoAll(Invoke([](std::unique_ptr<int> j) {}),
// Return(1)));
EXPECT_CALL(mock, TakeUnique(testing::Pointee(7)))
.WillOnce(Return(-7))
.RetiresOnSaturation();
EXPECT_CALL(mock, TakeUnique(testing::IsNull()))
.WillOnce(Return(-1))
.RetiresOnSaturation();
EXPECT_EQ(5, mock.TakeUnique(make(5)));
EXPECT_EQ(-7, mock.TakeUnique(make(7)));
EXPECT_EQ(7, mock.TakeUnique(make(7)));
EXPECT_EQ(7, mock.TakeUnique(make(7)));
EXPECT_EQ(-1, mock.TakeUnique({}));
// Some arguments are moved, some passed by reference.
auto lvalue = make(6);
EXPECT_CALL(mock, TakeUnique(_, _))
.WillOnce([](const std::unique_ptr<int>& i, std::unique_ptr<int> j) {
return *i * *j;
});
EXPECT_EQ(42, mock.TakeUnique(lvalue, make(7)));
// The unique_ptr can be saved by the action.
std::unique_ptr<int> saved;
EXPECT_CALL(mock, TakeUnique(_)).WillOnce([&saved](std::unique_ptr<int> i) {
saved = std::move(i);
return 0;
});
EXPECT_EQ(0, mock.TakeUnique(make(42)));
EXPECT_EQ(42, *saved);
}
#endif // GTEST_HAS_STD_UNIQUE_PTR_
#if GTEST_LANG_CXX11
// Tests for std::function based action.
int Add(int val, int& ref, int* ptr) { // NOLINT
int result = val + ref + *ptr;
ref = 42;
*ptr = 43;
return result;
}
int Deref(std::unique_ptr<int> ptr) { return *ptr; }
struct Double {
template <typename T>
T operator()(T t) { return 2 * t; }
};
std::unique_ptr<int> UniqueInt(int i) {
return std::unique_ptr<int>(new int(i));
}
TEST(FunctorActionTest, ActionFromFunction) {
Action<int(int, int&, int*)> a = &Add;
int x = 1, y = 2, z = 3;
EXPECT_EQ(6, a.Perform(std::forward_as_tuple(x, y, &z)));
EXPECT_EQ(42, y);
EXPECT_EQ(43, z);
Action<int(std::unique_ptr<int>)> a1 = &Deref;
EXPECT_EQ(7, a1.Perform(std::make_tuple(UniqueInt(7))));
}
TEST(FunctorActionTest, ActionFromLambda) {
Action<int(bool, int)> a1 = [](bool b, int i) { return b ? i : 0; };
EXPECT_EQ(5, a1.Perform(make_tuple(true, 5)));
EXPECT_EQ(0, a1.Perform(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)));
EXPECT_EQ(5, *saved);
}
TEST(FunctorActionTest, PolymorphicFunctor) {
Action<int(int)> ai = Double();
EXPECT_EQ(2, ai.Perform(make_tuple(1)));
Action<double(double)> ad = Double(); // Double? Double double!
EXPECT_EQ(3.0, ad.Perform(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)));
// 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")));
// Also between the lambda and the action itself.
const Action<bool(std::string)> x = [](Unused) { return 42; };
EXPECT_TRUE(x.Perform(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);
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)));
a = testing::WithoutArgs([]() { return 7; });
EXPECT_EQ(7, a.Perform(make_tuple(nullptr)));
Action<void(std::unique_ptr<int>, int*)> a2 = testing::SetArgPointee<1>(3);
int x = 0;
a2.Perform(make_tuple(nullptr, &x));
EXPECT_EQ(x, 3);
}
#endif // GTEST_LANG_CXX11
} // Unnamed namespace
#ifdef _MSC_VER
#if _MSC_VER == 1900
# pragma warning(pop)
#endif
#endif

View File

@ -26,8 +26,7 @@
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Author: wan@google.com (Zhanyong Wan)
// Google Mock - a framework for writing C++ mock classes.
//

View File

@ -26,8 +26,7 @@
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Author: wan@google.com (Zhanyong Wan)
// Google Mock - a framework for writing C++ mock classes.
//
@ -374,10 +373,10 @@ class SubstractAction : public ActionInterface<int(int, int)> { // NOLINT
};
TEST(WithArgsTest, NonInvokeAction) {
Action<int(const string&, int, int)> a = // NOLINT
Action<int(const std::string&, int, int)> a = // NOLINT
WithArgs<2, 1>(MakeAction(new SubstractAction));
string s("hello");
EXPECT_EQ(8, a.Perform(tuple<const string&, int, int>(s, 2, 10)));
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.
@ -754,7 +753,8 @@ TEST(ActionPMacroTest, CanReferenceArgumentAndParameterTypes) {
TEST(ActionPMacroTest, WorksInCompatibleMockFunction) {
Action<std::string(const std::string& s)> a1 = Plus("tail");
const std::string re = "re";
EXPECT_EQ("retail", a1.Perform(tuple<const std::string&>(re)));
tuple<const std::string> dummy = make_tuple(re);
EXPECT_EQ("retail", a1.Perform(dummy));
}
// Tests that we can use ACTION*() to define actions overloaded on the
@ -796,7 +796,8 @@ TEST(ActionPnMacroTest, WorksFor3Parameters) {
Action<std::string(const std::string& s)> a2 = Plus("tail", "-", ">");
const std::string re = "re";
EXPECT_EQ("retail->", a2.Perform(tuple<const std::string&>(re)));
tuple<const std::string> dummy = make_tuple(re);
EXPECT_EQ("retail->", a2.Perform(dummy));
}
ACTION_P4(Plus, p0, p1, p2, p3) { return arg0 + p0 + p1 + p2 + p3; }
@ -1120,7 +1121,7 @@ TEST(ActionTemplateTest, WorksForIntegralTemplateParams) {
EXPECT_FALSE(b); // Verifies that resetter is deleted.
}
// Tests that ACTION_TEMPLATE works for a template with template parameters.
// Tests that ACTION_TEMPLATES works for template template parameters.
ACTION_TEMPLATE(ReturnSmartPointer,
HAS_1_TEMPLATE_PARAMS(template <typename Pointee> class,
Pointer),

View File

@ -26,8 +26,7 @@
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Author: wan@google.com (Zhanyong Wan)
// Google Mock - a framework for writing C++ mock classes.
//
@ -620,5 +619,28 @@ TEST(MockFunctionTest, AsStdFunctionReturnsReference) {
}
#endif // GTEST_HAS_STD_FUNCTION_
struct MockMethodSizes0 {
MOCK_METHOD0(func, void());
};
struct MockMethodSizes1 {
MOCK_METHOD1(func, void(int));
};
struct MockMethodSizes2 {
MOCK_METHOD2(func, void(int, int));
};
struct MockMethodSizes3 {
MOCK_METHOD3(func, void(int, int, int));
};
struct MockMethodSizes4 {
MOCK_METHOD4(func, void(int, int, int, int));
};
TEST(MockFunctionTest, MockMethodSizeOverhead) {
EXPECT_EQ(sizeof(MockMethodSizes0), sizeof(MockMethodSizes1));
EXPECT_EQ(sizeof(MockMethodSizes0), sizeof(MockMethodSizes2));
EXPECT_EQ(sizeof(MockMethodSizes0), sizeof(MockMethodSizes3));
EXPECT_EQ(sizeof(MockMethodSizes0), sizeof(MockMethodSizes4));
}
} // namespace gmock_generated_function_mockers_test
} // namespace testing

View File

@ -26,8 +26,7 @@
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Author: wan@google.com (Zhanyong Wan)
// Google Mock - a framework for writing C++ mock classes.
//
@ -63,10 +62,10 @@ TEST(MatcherTupleTest, ForSize2) {
}
TEST(MatcherTupleTest, ForSize5) {
CompileAssertTypesEqual<tuple<Matcher<int>, Matcher<char>, Matcher<bool>,
Matcher<double>, Matcher<char*> >,
MatcherTuple<tuple<int, char, bool, double, char*>
>::type>();
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.
@ -97,7 +96,8 @@ TEST(FunctionTest, Binary) {
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
CompileAssertTypesEqual<
tuple<Matcher<bool>, Matcher<const long&> >, // NOLINT
F::ArgumentMatcherTuple>();
CompileAssertTypesEqual<void(bool, const long&), F::MakeResultVoid>(); // NOLINT
CompileAssertTypesEqual<IgnoredValue(bool, const long&), // NOLINT
@ -114,8 +114,9 @@ TEST(FunctionTest, LongArgumentList) {
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
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>();

View File

@ -31,10 +31,19 @@
//
// This file tests the built-in matchers generated by a script.
// Silence warning C4244: 'initializing': conversion from 'int' to 'short',
// possible loss of data and C4100, unreferenced local parameter
#ifdef _MSC_VER
# pragma warning(push)
# pragma warning(disable:4244)
# pragma warning(disable:4100)
#endif
#include "gmock/gmock-generated-matchers.h"
#include <list>
#include <map>
#include <memory>
#include <set>
#include <sstream>
#include <string>
@ -57,6 +66,8 @@ using testing::get;
using testing::make_tuple;
using testing::tuple;
using testing::_;
using testing::AllOf;
using testing::AnyOf;
using testing::Args;
using testing::Contains;
using testing::ElementsAre;
@ -120,7 +131,7 @@ TEST(ArgsTest, AcceptsOneTemplateArg) {
}
TEST(ArgsTest, AcceptsTwoTemplateArgs) {
const tuple<short, int, long> t(static_cast<short>(4), 5, 6L); // NOLINT
const tuple<short, int, long> t(4, 5, 6L); // NOLINT
EXPECT_THAT(t, (Args<0, 1>(Lt())));
EXPECT_THAT(t, (Args<1, 2>(Lt())));
@ -128,13 +139,13 @@ TEST(ArgsTest, AcceptsTwoTemplateArgs) {
}
TEST(ArgsTest, AcceptsRepeatedTemplateArgs) {
const tuple<short, int, long> t(static_cast<short>(4), 5, 6L); // NOLINT
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(static_cast<short>(4), 5, 6L); // NOLINT
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())));
}
@ -159,7 +170,7 @@ TEST(ArgsTest, AcceptsMoreTemplateArgsThanArityOfOriginalTuple) {
}
TEST(ArgsTest, CanBeNested) {
const tuple<short, int, long, int> t(static_cast<short>(4), 5, 6L, 6); // NOLINT
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()))));
}
@ -1283,4 +1294,48 @@ TEST(AnyOfTest, DoesNotCallAnyOfUnqualified) {
# pragma warning(pop)
#endif
#if GTEST_LANG_CXX11
TEST(AllOfTest, WorksOnMoveOnlyType) {
std::unique_ptr<int> p(new int(3));
EXPECT_THAT(p, AllOf(Pointee(Eq(3)), Pointee(Gt(0)), Pointee(Lt(5))));
EXPECT_THAT(p, Not(AllOf(Pointee(Eq(3)), Pointee(Gt(0)), Pointee(Lt(3)))));
}
TEST(AnyOfTest, WorksOnMoveOnlyType) {
std::unique_ptr<int> p(new int(3));
EXPECT_THAT(p, AnyOf(Pointee(Eq(5)), Pointee(Lt(0)), Pointee(Lt(5))));
EXPECT_THAT(p, Not(AnyOf(Pointee(Eq(5)), Pointee(Lt(0)), Pointee(Gt(5)))));
}
MATCHER(IsNotNull, "") {
return arg != nullptr;
}
// Verifies that a matcher defined using MATCHER() can work on
// move-only types.
TEST(MatcherMacroTest, WorksOnMoveOnlyType) {
std::unique_ptr<int> p(new int(3));
EXPECT_THAT(p, IsNotNull());
EXPECT_THAT(std::unique_ptr<int>(), Not(IsNotNull()));
}
MATCHER_P(UniquePointee, pointee, "") {
return *arg == pointee;
}
// Verifies that a matcher defined using MATCHER_P*() can work on
// move-only types.
TEST(MatcherPMacroTest, WorksOnMoveOnlyType) {
std::unique_ptr<int> p(new int(3));
EXPECT_THAT(p, UniquePointee(3));
EXPECT_THAT(p, Not(UniquePointee(2)));
}
#endif // GTEST_LASNG_CXX11
} // namespace
#ifdef _MSC_VER
# pragma warning(pop)
#endif

View File

@ -26,8 +26,7 @@
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Author: wan@google.com (Zhanyong Wan)
// Google Mock - a framework for writing C++ mock classes.
//

View File

@ -26,8 +26,7 @@
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Author: wan@google.com (Zhanyong Wan)
// Google Mock - a framework for writing C++ mock classes.
//
@ -59,12 +58,6 @@
# include <forward_list> // NOLINT
#endif
// Disable MSVC2015 warning for std::pair:
// "decorated name length exceeded, name was truncated".
#if defined(_MSC_VER) && (_MSC_VER == 1900)
# pragma warning(disable:4503)
#endif
#if GTEST_LANG_CXX11
# include <type_traits>
#endif
@ -748,6 +741,13 @@ TEST(MatcherCastTest, NonImplicitlyConstructibleTypeWithOperatorEq) {
EXPECT_FALSE(m3.Matches(239));
}
// ConvertibleFromAny does not work with MSVC. resulting in
// error C2440: 'initializing': cannot convert from 'Eq' to 'M'
// No constructor could take the source type, or constructor overload
// resolution was ambiguous
#if !defined _MSC_VER
// The below ConvertibleFromAny struct is implicitly constructible from anything
// and when in the same namespace can interact with other tests. In particular,
// if it is in the same namespace as other tests and one removes
@ -760,7 +760,7 @@ namespace convertible_from_any {
struct ConvertibleFromAny {
ConvertibleFromAny(int a_value) : value(a_value) {}
template <typename T>
explicit ConvertibleFromAny(const T& /*a_value*/) : value(-1) {
ConvertibleFromAny(const T& /*a_value*/) : value(-1) {
ADD_FAILURE() << "Conversion constructor called";
}
int value;
@ -788,6 +788,8 @@ TEST(MatcherCastTest, FromConvertibleFromAny) {
}
} // namespace convertible_from_any
#endif // !defined _MSC_VER
struct IntReferenceWrapper {
IntReferenceWrapper(const int& a_value) : value(&a_value) {}
const int* value;
@ -892,6 +894,8 @@ TEST(SafeMatcherCastTest, FromSameType) {
EXPECT_FALSE(m2.Matches(1));
}
#if !defined _MSC_VER
namespace convertible_from_any {
TEST(SafeMatcherCastTest, ConversionConstructorIsUsed) {
Matcher<ConvertibleFromAny> m = SafeMatcherCast<ConvertibleFromAny>(1);
@ -907,6 +911,8 @@ TEST(SafeMatcherCastTest, FromConvertibleFromAny) {
}
} // namespace convertible_from_any
#endif // !defined _MSC_VER
TEST(SafeMatcherCastTest, ValueIsNotCopied) {
int n = 42;
Matcher<IntReferenceWrapper> m = SafeMatcherCast<IntReferenceWrapper>(n);
@ -2538,7 +2544,7 @@ TEST(AllOfTest, VariadicMatchesWhenAllMatch) {
::testing::AllOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
Matcher<int> m = AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8),
Ne(9), Ne(10), Ne(11));
EXPECT_THAT(Describe(m), EndsWith("and (isn't equal to 11))))))))))"));
EXPECT_THAT(Describe(m), EndsWith("and (isn't equal to 11)"));
AllOfMatches(11, m);
AllOfMatches(50, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8),
Ne(9), Ne(10), Ne(11), Ne(12), Ne(13), Ne(14), Ne(15),
@ -2673,7 +2679,7 @@ TEST(AllOfTest, ExplainsResult) {
}
// Helper to allow easy testing of AnyOf matchers with num parameters.
void AnyOfMatches(int num, const Matcher<int>& m) {
static void AnyOfMatches(int num, const Matcher<int>& m) {
SCOPED_TRACE(Describe(m));
EXPECT_FALSE(m.Matches(0));
for (int i = 1; i <= num; ++i) {
@ -2682,6 +2688,18 @@ void AnyOfMatches(int num, const Matcher<int>& m) {
EXPECT_FALSE(m.Matches(num + 1));
}
#if GTEST_LANG_CXX11
static void AnyOfStringMatches(int num, const Matcher<std::string>& m) {
SCOPED_TRACE(Describe(m));
EXPECT_FALSE(m.Matches(std::to_string(0)));
for (int i = 1; i <= num; ++i) {
EXPECT_TRUE(m.Matches(std::to_string(i)));
}
EXPECT_FALSE(m.Matches(std::to_string(num + 1)));
}
#endif
// Tests that AnyOf(m1, ..., mn) matches any value that matches at
// least one of the given matchers.
TEST(AnyOfTest, MatchesWhenAnyMatches) {
@ -2732,13 +2750,46 @@ TEST(AnyOfTest, VariadicMatchesWhenAnyMatches) {
// on ADL.
Matcher<int> m = ::testing::AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
EXPECT_THAT(Describe(m), EndsWith("or (is equal to 11))))))))))"));
EXPECT_THAT(Describe(m), EndsWith("or (is equal to 11)"));
AnyOfMatches(11, m);
AnyOfMatches(50, AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
21, 22, 23, 24, 25, 26, 27, 28, 29, 30,
31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
41, 42, 43, 44, 45, 46, 47, 48, 49, 50));
AnyOfStringMatches(
50, AnyOf("1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12",
"13", "14", "15", "16", "17", "18", "19", "20", "21", "22",
"23", "24", "25", "26", "27", "28", "29", "30", "31", "32",
"33", "34", "35", "36", "37", "38", "39", "40", "41", "42",
"43", "44", "45", "46", "47", "48", "49", "50"));
}
// Tests the variadic version of the ElementsAreMatcher
TEST(ElementsAreTest, HugeMatcher) {
vector<int> test_vector{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
EXPECT_THAT(test_vector,
ElementsAre(Eq(1), Eq(2), Lt(13), Eq(4), Eq(5), Eq(6), Eq(7),
Eq(8), Eq(9), Eq(10), Gt(1), Eq(12)));
}
// Tests the variadic version of the UnorderedElementsAreMatcher
TEST(ElementsAreTest, HugeMatcherStr) {
vector<string> test_vector{
"literal_string", "", "", "", "", "", "", "", "", "", "", ""};
EXPECT_THAT(test_vector, UnorderedElementsAre("literal_string", _, _, _, _, _,
_, _, _, _, _, _));
}
// Tests the variadic version of the UnorderedElementsAreMatcher
TEST(ElementsAreTest, HugeMatcherUnordered) {
vector<int> test_vector{2, 1, 8, 5, 4, 6, 7, 3, 9, 12, 11, 10};
EXPECT_THAT(test_vector, UnorderedElementsAre(
Eq(2), Eq(1), Gt(7), Eq(5), Eq(4), Eq(6), Eq(7),
Eq(3), Eq(9), Eq(12), Eq(11), Ne(122)));
}
#endif // GTEST_LANG_CXX11
@ -3065,6 +3116,44 @@ TEST(AllArgsTest, WorksInWithClause) {
EXPECT_EQ(2, helper.Helper('a', 1));
}
class OptionalMatchersHelper {
public:
OptionalMatchersHelper() {}
MOCK_METHOD0(NoArgs, int());
MOCK_METHOD1(OneArg, int(int y));
MOCK_METHOD2(TwoArgs, int(char x, int y));
MOCK_METHOD1(Overloaded, int(char x));
MOCK_METHOD2(Overloaded, int(char x, int y));
private:
GTEST_DISALLOW_COPY_AND_ASSIGN_(OptionalMatchersHelper);
};
TEST(AllArgsTest, WorksWithoutMatchers) {
OptionalMatchersHelper helper;
ON_CALL(helper, NoArgs).WillByDefault(Return(10));
ON_CALL(helper, OneArg).WillByDefault(Return(20));
ON_CALL(helper, TwoArgs).WillByDefault(Return(30));
EXPECT_EQ(10, helper.NoArgs());
EXPECT_EQ(20, helper.OneArg(1));
EXPECT_EQ(30, helper.TwoArgs('\1', 2));
EXPECT_CALL(helper, NoArgs).Times(1);
EXPECT_CALL(helper, OneArg).WillOnce(Return(100));
EXPECT_CALL(helper, OneArg(17)).WillOnce(Return(200));
EXPECT_CALL(helper, TwoArgs).Times(0);
EXPECT_EQ(10, helper.NoArgs());
EXPECT_EQ(100, helper.OneArg(1));
EXPECT_EQ(200, helper.OneArg(17));
}
// Tests that ASSERT_THAT() and EXPECT_THAT() work when the value
// matches the matcher.
TEST(MatcherAssertionTest, WorksWhenMatcherIsSatisfied) {
@ -3632,6 +3721,7 @@ MATCHER_P(FieldIIs, inner_matcher, "") {
return ExplainMatchResult(inner_matcher, arg.i, result_listener);
}
#if GTEST_HAS_RTTI
TEST(WhenDynamicCastToTest, SameType) {
Derived derived;
derived.i = 4;
@ -3689,12 +3779,8 @@ TEST(WhenDynamicCastToTest, AmbiguousCast) {
TEST(WhenDynamicCastToTest, Describe) {
Matcher<Base*> matcher = WhenDynamicCastTo<Derived*>(Pointee(_));
#if GTEST_HAS_RTTI
const std::string prefix =
"when dynamic_cast to " + internal::GetTypeName<Derived*>() + ", ";
#else // GTEST_HAS_RTTI
const std::string prefix = "when dynamic_cast, ";
#endif // GTEST_HAS_RTTI
EXPECT_EQ(prefix + "points to a value that is anything", Describe(matcher));
EXPECT_EQ(prefix + "does not point to a value that is anything",
DescribeNegation(matcher));
@ -3727,6 +3813,7 @@ TEST(WhenDynamicCastToTest, BadReference) {
Base& as_base_ref = derived;
EXPECT_THAT(as_base_ref, Not(WhenDynamicCastTo<const OtherDerived&>(_)));
}
#endif // GTEST_HAS_RTTI
// Minimal const-propagating pointer.
template <typename T>
@ -4150,13 +4237,17 @@ TEST(PropertyTest, WorksForReferenceToConstProperty) {
// ref-qualified.
TEST(PropertyTest, WorksForRefQualifiedProperty) {
Matcher<const AClass&> m = Property(&AClass::s_ref, StartsWith("hi"));
Matcher<const AClass&> m_with_name =
Property("s", &AClass::s_ref, StartsWith("hi"));
AClass a;
a.set_s("hill");
EXPECT_TRUE(m.Matches(a));
EXPECT_TRUE(m_with_name.Matches(a));
a.set_s("hole");
EXPECT_FALSE(m.Matches(a));
EXPECT_FALSE(m_with_name.Matches(a));
}
#endif
@ -4500,7 +4591,7 @@ TEST(ResultOfTest, WorksForFunctors) {
}
// Tests that ResultOf(f, ...) compiles and works as expected when f is a
// functor with more then one operator() defined. ResultOf() must work
// functor with more than one operator() defined. ResultOf() must work
// for each defined operator().
struct PolymorphicFunctor {
typedef int result_type;

View File

@ -26,8 +26,7 @@
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Author: wan@google.com (Zhanyong Wan)
// Google Mock - a framework for writing C++ mock classes.
//
@ -327,11 +326,10 @@ TEST(InvokeTest, FunctionThatTakes10Arguments) {
// Tests using Invoke() with functions with parameters declared as Unused.
TEST(InvokeTest, FunctionWithUnusedParameters) {
Action<int(int, int, double, const string&)> a1 =
Invoke(SumOfFirst2);
string s("hi");
EXPECT_EQ(12, a1.Perform(
tuple<int, int, double, const string&>(10, 2, 5.6, s)));
Action<int(int, int, double, const std::string&)> a1 = Invoke(SumOfFirst2);
tuple<int, int, double, std::string> dummy =
make_tuple(10, 2, 5.6, std::string("hi"));
EXPECT_EQ(12, a1.Perform(dummy));
Action<int(int, int, bool, int*)> a2 =
Invoke(SumOfFirst2);
@ -380,10 +378,10 @@ TEST(InvokeMethodTest, Unary) {
// Tests using Invoke() with a binary method.
TEST(InvokeMethodTest, Binary) {
Foo foo;
Action<string(const string&, char)> a = Invoke(&foo, &Foo::Binary);
string s("Hell");
EXPECT_EQ("Hello", a.Perform(
tuple<const string&, char>(s, 'o')));
Action<std::string(const std::string&, char)> a = Invoke(&foo, &Foo::Binary);
std::string s("Hell");
tuple<std::string, char> dummy = make_tuple(s, 'o');
EXPECT_EQ("Hello", a.Perform(dummy));
}
// Tests using Invoke() with a ternary method.

View File

@ -26,15 +26,15 @@
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Author: wan@google.com (Zhanyong Wan)
#include "gmock/gmock-generated-nice-strict.h"
#include <string>
#include <utility>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "gtest/gtest-spi.h"
#include "gtest/gtest.h"
// This must not be defined inside the ::testing namespace, or it will
// clash with ::testing::Mock.
@ -114,6 +114,24 @@ class MockBar {
GTEST_DISALLOW_COPY_AND_ASSIGN_(MockBar);
};
#if GTEST_GTEST_LANG_CXX11
class MockBaz {
public:
class MoveOnly {
MoveOnly() = default;
MoveOnly(const MoveOnly&) = delete;
operator=(const MoveOnly&) = delete;
MoveOnly(MoveOnly&&) = default;
operator=(MoveOnly&&) = default;
};
MockBaz(MoveOnly) {}
}
#endif // GTEST_GTEST_LANG_CXX11 && GTEST_HAS_STD_MOVE_
#if GTEST_HAS_STREAM_REDIRECTION
// Tests that a raw mock generates warnings for uninteresting calls.
@ -214,8 +232,9 @@ TEST(NiceMockTest, AllowsExpectedCall) {
nice_foo.DoThis();
}
// Tests that an unexpected call on a nice mock which returns a not-default-constructible
// type throws an exception and the exception contains the method's name.
// Tests that an unexpected call on a nice mock which returns a
// not-default-constructible type throws an exception and the exception contains
// the method's name.
TEST(NiceMockTest, ThrowsExceptionForUnknownReturnTypes) {
NiceMock<MockFoo> nice_foo;
#if GTEST_HAS_EXCEPTIONS
@ -259,6 +278,21 @@ TEST(NiceMockTest, NonDefaultConstructor10) {
nice_bar.That(5, true);
}
TEST(NiceMockTest, AllowLeak) {
NiceMock<MockFoo>* leaked = new NiceMock<MockFoo>;
Mock::AllowLeak(leaked);
EXPECT_CALL(*leaked, DoThis());
leaked->DoThis();
}
#if GTEST_GTEST_LANG_CXX11 && GTEST_HAS_STD_MOVE_
TEST(NiceMockTest, MoveOnlyConstructor) {
NiceMock<MockBaz> nice_baz(MockBaz::MoveOnly());
}
#endif // GTEST_LANG_CXX11 && GTEST_HAS_STD_MOVE_
#if !GTEST_OS_SYMBIAN && !GTEST_OS_WINDOWS_MOBILE
// Tests that NiceMock<Mock> compiles where Mock is a user-defined
// class (as opposed to ::testing::Mock). We had to work around an
@ -352,6 +386,21 @@ TEST(NaggyMockTest, NonDefaultConstructor10) {
naggy_bar.That(5, true);
}
TEST(NaggyMockTest, AllowLeak) {
NaggyMock<MockFoo>* leaked = new NaggyMock<MockFoo>;
Mock::AllowLeak(leaked);
EXPECT_CALL(*leaked, DoThis());
leaked->DoThis();
}
#if GTEST_GTEST_LANG_CXX11 && GTEST_HAS_STD_MOVE_
TEST(NaggyMockTest, MoveOnlyConstructor) {
NaggyMock<MockBaz> naggy_baz(MockBaz::MoveOnly());
}
#endif // GTEST_LANG_CXX11 && GTEST_HAS_STD_MOVE_
#if !GTEST_OS_SYMBIAN && !GTEST_OS_WINDOWS_MOBILE
// Tests that NaggyMock<Mock> compiles where Mock is a user-defined
// class (as opposed to ::testing::Mock). We had to work around an
@ -426,6 +475,21 @@ TEST(StrictMockTest, NonDefaultConstructor10) {
"Uninteresting mock function call");
}
TEST(StrictMockTest, AllowLeak) {
StrictMock<MockFoo>* leaked = new StrictMock<MockFoo>;
Mock::AllowLeak(leaked);
EXPECT_CALL(*leaked, DoThis());
leaked->DoThis();
}
#if GTEST_GTEST_LANG_CXX11 && GTEST_HAS_STD_MOVE_
TEST(StrictMockTest, MoveOnlyConstructor) {
StrictMock<MockBaz> strict_baz(MockBaz::MoveOnly());
}
#endif // GTEST_LANG_CXX11 && GTEST_HAS_STD_MOVE_
#if !GTEST_OS_SYMBIAN && !GTEST_OS_WINDOWS_MOBILE
// Tests that StrictMock<Mock> compiles where Mock is a user-defined
// class (as opposed to ::testing::Mock). We had to work around an

View File

@ -26,8 +26,7 @@
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Author: vladl@google.com (Vlad Losev)
// Google Mock - a framework for writing C++ mock classes.
//

View File

@ -26,8 +26,7 @@
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Author: wan@google.com (Zhanyong Wan)
// Google Mock - a framework for writing C++ mock classes.
//
@ -89,6 +88,7 @@ using testing::Mock;
using testing::NaggyMock;
using testing::Ne;
using testing::Return;
using testing::SaveArg;
using testing::Sequence;
using testing::SetArgPointee;
using testing::internal::ExpectationTester;
@ -1175,7 +1175,7 @@ TEST(UnexpectedCallTest, UnsatisifiedPrerequisites) {
TEST(UndefinedReturnValueTest,
ReturnValueIsMandatoryWhenNotDefaultConstructible) {
MockA a;
// TODO(wan@google.com): We should really verify the output message,
// FIXME: We should really verify the output message,
// but we cannot yet due to that EXPECT_DEATH only captures stderr
// while Google Mock logs to stdout.
#if GTEST_HAS_EXCEPTIONS
@ -2173,7 +2173,9 @@ class GMockVerboseFlagTest : public VerboseFlagPreservingFixture {
"NOTE: You can safely ignore the above warning unless this "
"call should not happen. Do not suppress it by blindly adding "
"an EXPECT_CALL() if you don't mean to enforce the call. "
"See https://github.com/google/googletest/blob/master/googlemock/docs/CookBook.md#"
"See "
"https://github.com/google/googletest/blob/master/googlemock/docs/"
"CookBook.md#"
"knowing-when-to-expect for details.";
// A void-returning function.
@ -2679,6 +2681,75 @@ TEST(SynchronizationTest, CanCallMockMethodInAction) {
// EXPECT_CALL() did not specify an action.
}
TEST(ParameterlessExpectationsTest, CanSetExpectationsWithoutMatchers) {
MockA a;
int do_a_arg0 = 0;
ON_CALL(a, DoA).WillByDefault(SaveArg<0>(&do_a_arg0));
int do_a_47_arg0 = 0;
ON_CALL(a, DoA(47)).WillByDefault(SaveArg<0>(&do_a_47_arg0));
a.DoA(17);
EXPECT_THAT(do_a_arg0, 17);
EXPECT_THAT(do_a_47_arg0, 0);
a.DoA(47);
EXPECT_THAT(do_a_arg0, 17);
EXPECT_THAT(do_a_47_arg0, 47);
ON_CALL(a, Binary).WillByDefault(Return(true));
ON_CALL(a, Binary(_, 14)).WillByDefault(Return(false));
EXPECT_THAT(a.Binary(14, 17), true);
EXPECT_THAT(a.Binary(17, 14), false);
}
TEST(ParameterlessExpectationsTest, CanSetExpectationsForOverloadedMethods) {
MockB b;
ON_CALL(b, DoB()).WillByDefault(Return(9));
ON_CALL(b, DoB(5)).WillByDefault(Return(11));
EXPECT_THAT(b.DoB(), 9);
EXPECT_THAT(b.DoB(1), 0); // default value
EXPECT_THAT(b.DoB(5), 11);
}
struct MockWithConstMethods {
public:
MOCK_CONST_METHOD1(Foo, int(int));
MOCK_CONST_METHOD2(Bar, int(int, const char*));
};
TEST(ParameterlessExpectationsTest, CanSetExpectationsForConstMethods) {
MockWithConstMethods mock;
ON_CALL(mock, Foo).WillByDefault(Return(7));
ON_CALL(mock, Bar).WillByDefault(Return(33));
EXPECT_THAT(mock.Foo(17), 7);
EXPECT_THAT(mock.Bar(27, "purple"), 33);
}
class MockConstOverload {
public:
MOCK_METHOD1(Overloaded, int(int));
MOCK_CONST_METHOD1(Overloaded, int(int));
};
TEST(ParameterlessExpectationsTest,
CanSetExpectationsForConstOverloadedMethods) {
MockConstOverload mock;
ON_CALL(mock, Overloaded(_)).WillByDefault(Return(7));
ON_CALL(mock, Overloaded(5)).WillByDefault(Return(9));
ON_CALL(Const(mock), Overloaded(5)).WillByDefault(Return(11));
ON_CALL(Const(mock), Overloaded(7)).WillByDefault(Return(13));
EXPECT_THAT(mock.Overloaded(1), 7);
EXPECT_THAT(mock.Overloaded(5), 9);
EXPECT_THAT(mock.Overloaded(7), 7);
const MockConstOverload& const_mock = mock;
EXPECT_THAT(const_mock.Overloaded(1), 0);
EXPECT_THAT(const_mock.Overloaded(5), 11);
EXPECT_THAT(const_mock.Overloaded(7), 13);
}
} // namespace
// Allows the user to define their own main and then invoke gmock_main

View File

@ -26,8 +26,7 @@
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Author: wan@google.com (Zhanyong Wan)
//
// Tests for Google C++ Mocking Framework (Google Mock)
//

View File

@ -26,17 +26,18 @@
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Author: wan@google.com (Zhanyong Wan)
// Tests Google Mock's functionality that depends on exceptions.
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#if GTEST_HAS_EXCEPTIONS
namespace {
using testing::HasSubstr;
using testing::internal::GoogleTestFailureException;
// A type that cannot be default constructed.
@ -52,8 +53,6 @@ class MockFoo {
MOCK_METHOD0(GetNonDefaultConstructible, NonDefaultConstructible());
};
#if GTEST_HAS_EXCEPTIONS
TEST(DefaultValueTest, ThrowsRuntimeErrorWhenNoDefaultValue) {
MockFoo mock;
try {
@ -76,6 +75,6 @@ TEST(DefaultValueTest, ThrowsRuntimeErrorWhenNoDefaultValue) {
}
}
#endif
} // unnamed namespace
#endif

View File

@ -31,12 +31,8 @@
"""Tests that leaked mock objects can be caught be Google Mock."""
__author__ = 'wan@google.com (Zhanyong Wan)'
import gmock_test_utils
PROGRAM_PATH = gmock_test_utils.GetTestExecutablePath('gmock_leak_test_')
TEST_WITH_EXPECT_CALL = [PROGRAM_PATH, '--gtest_filter=*ExpectCall*']
TEST_WITH_ON_CALL = [PROGRAM_PATH, '--gtest_filter=*OnCall*']

View File

@ -26,8 +26,7 @@
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Author: wan@google.com (Zhanyong Wan)
// Google Mock - a framework for writing C++ mock classes.
//

View File

@ -26,8 +26,7 @@
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Author: wan@google.com (Zhanyong Wan), vladl@google.com (Vlad Losev)
// Google Mock - a framework for writing C++ mock classes.
//

View File

@ -26,8 +26,7 @@
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Author: wan@google.com (Zhanyong Wan), vladl@google.com (Vlad Losev)
// Google Mock - a framework for writing C++ mock classes.
//

View File

@ -26,8 +26,7 @@
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Author: vladl@google.com (Vlad Losev)
// Google Mock - a framework for writing C++ mock classes.
//

View File

@ -29,21 +29,19 @@
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Tests the text output of Google C++ Mocking Framework.
r"""Tests the text output of Google C++ Mocking Framework.
To update the golden file:
gmock_output_test.py --build_dir=BUILD/DIR --gengolden
# where BUILD/DIR contains the built gmock_output_test_ file.
where BUILD/DIR contains the built gmock_output_test_ file.
gmock_output_test.py --gengolden
gmock_output_test.py
"""
__author__ = 'wan@google.com (Zhanyong Wan)'
"""
import os
import re
import sys
import gmock_test_utils

View File

@ -26,8 +26,7 @@
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Author: wan@google.com (Zhanyong Wan)
// Tests Google Mock's output in various scenarios. This ensures that
// Google Mock's messages are readable and useful.
@ -39,6 +38,12 @@
#include "gtest/gtest.h"
// Silence C4100 (unreferenced formal parameter)
#ifdef _MSC_VER
# pragma warning(push)
# pragma warning(disable:4100)
#endif
using testing::_;
using testing::AnyNumber;
using testing::Ge;
@ -298,3 +303,7 @@ int main(int argc, char **argv) {
TestCatchesLeakedMocksInAdHocTests();
return RUN_ALL_TESTS();
}
#ifdef _MSC_VER
# pragma warning(pop)
#endif

View File

@ -26,20 +26,18 @@
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Author: wan@google.com (Zhanyong Wan)
// Tests that Google Mock constructs can be used in a large number of
// threads concurrently.
#include "gmock/gmock.h"
#include "gtest/gtest.h"
namespace testing {
namespace {
// From "gtest/internal/gtest-port.h".
// From gtest-port.h.
using ::testing::internal::ThreadWithParam;
// The maximum number of test threads (not including helper threads)

View File

@ -26,8 +26,7 @@
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Author: wan@google.com (Zhanyong Wan)
// Google Mock - a framework for writing C++ mock classes.
//

View File

@ -29,8 +29,6 @@
"""Unit test utilities for Google C++ Mocking Framework."""
__author__ = 'wan@google.com (Zhanyong Wan)'
import os
import sys
@ -38,7 +36,7 @@ import sys
SCRIPT_DIR = os.path.dirname(__file__) or '.'
# isdir resolves symbolic links.
gtest_tests_util_dir = os.path.join(SCRIPT_DIR, '../googletest/test')
gtest_tests_util_dir = os.path.join(SCRIPT_DIR, '../../googletest/test')
if os.path.isdir(gtest_tests_util_dir):
GTEST_TESTS_UTIL_DIR = gtest_tests_util_dir
else:

View File

@ -136,13 +136,13 @@ if(INSTALL_GTEST)
# configure and install pkgconfig files
configure_file(
cmake/gtest.pc.in
"${CMAKE_BINARY_DIR}/gtest.pc"
"${gtest_BINARY_DIR}/gtest.pc"
@ONLY)
configure_file(
cmake/gtest_main.pc.in
"${CMAKE_BINARY_DIR}/gtest_main.pc"
"${gtest_BINARY_DIR}/gtest_main.pc"
@ONLY)
install(FILES "${CMAKE_BINARY_DIR}/gtest.pc" "${CMAKE_BINARY_DIR}/gtest_main.pc"
install(FILES "${gtest_BINARY_DIR}/gtest.pc" "${gtest_BINARY_DIR}/gtest_main.pc"
DESTINATION "${CMAKE_INSTALL_LIBDIR}/pkgconfig")
endif()
@ -186,28 +186,28 @@ if (gtest_build_tests)
############################################################
# C++ tests built with standard compiler flags.
cxx_test(gtest-death-test_test gtest_main)
cxx_test(googletest-death-test-test gtest_main)
cxx_test(gtest_environment_test gtest)
cxx_test(gtest-filepath_test gtest_main)
cxx_test(gtest-linked_ptr_test gtest_main)
cxx_test(gtest-listener_test gtest_main)
cxx_test(googletest-filepath-test gtest_main)
cxx_test(googletest-linked-ptr-test gtest_main)
cxx_test(googletest-listener-test gtest_main)
cxx_test(gtest_main_unittest gtest_main)
cxx_test(gtest-message_test gtest_main)
cxx_test(googletest-message-test gtest_main)
cxx_test(gtest_no_test_unittest gtest)
cxx_test(gtest-options_test gtest_main)
cxx_test(gtest-param-test_test gtest
test/gtest-param-test2_test.cc)
cxx_test(gtest-port_test gtest_main)
cxx_test(googletest-options-test gtest_main)
cxx_test(googletest-param-test-test gtest
test/googletest-param-test2-test.cc)
cxx_test(googletest-port-test gtest_main)
cxx_test(gtest_pred_impl_unittest gtest_main)
cxx_test(gtest_premature_exit_test gtest
test/gtest_premature_exit_test.cc)
cxx_test(gtest-printers_test gtest_main)
cxx_test(googletest-printers-test gtest_main)
cxx_test(gtest_prod_test gtest_main
test/production.cc)
cxx_test(gtest_repeat_test gtest)
cxx_test(gtest_sole_header_test gtest_main)
cxx_test(gtest_stress_test gtest)
cxx_test(gtest-test-part_test gtest_main)
cxx_test(googletest-test-part-test gtest_main)
cxx_test(gtest_throw_on_failure_ex_test gtest)
cxx_test(gtest-typed-test_test gtest_main
test/gtest-typed-test2_test.cc)
@ -229,10 +229,10 @@ if (gtest_build_tests)
cxx_test_with_flags(gtest-death-test_ex_nocatch_test
"${cxx_exception} -DGTEST_ENABLE_CATCH_EXCEPTIONS_=0"
gtest test/gtest-death-test_ex_test.cc)
gtest test/googletest-death-test_ex_test.cc)
cxx_test_with_flags(gtest-death-test_ex_catch_test
"${cxx_exception} -DGTEST_ENABLE_CATCH_EXCEPTIONS_=1"
gtest test/gtest-death-test_ex_test.cc)
gtest test/googletest-death-test_ex_test.cc)
cxx_test_with_flags(gtest_no_rtti_unittest "${cxx_no_rtti}"
gtest_main_no_rtti test/gtest_unittest.cc)
@ -253,75 +253,75 @@ if (gtest_build_tests)
cxx_library(gtest_main_use_own_tuple "${cxx_use_own_tuple}"
src/gtest-all.cc src/gtest_main.cc)
cxx_test_with_flags(gtest-tuple_test "${cxx_use_own_tuple}"
gtest_main_use_own_tuple test/gtest-tuple_test.cc)
cxx_test_with_flags(googletest-tuple-test "${cxx_use_own_tuple}"
gtest_main_use_own_tuple test/googletest-tuple-test.cc)
cxx_test_with_flags(gtest_use_own_tuple_test "${cxx_use_own_tuple}"
gtest_main_use_own_tuple
test/gtest-param-test_test.cc test/gtest-param-test2_test.cc)
test/googletest-param-test-test.cc test/googletest-param-test2-test.cc)
endif()
############################################################
# Python tests.
cxx_executable(gtest_break_on_failure_unittest_ test gtest)
py_test(gtest_break_on_failure_unittest)
cxx_executable(googletest-break-on-failure-unittest_ test gtest)
py_test(googletest-break-on-failure-unittest)
# Visual Studio .NET 2003 does not support STL with exceptions disabled.
if (NOT MSVC OR MSVC_VERSION GREATER 1310) # 1310 is Visual Studio .NET 2003
cxx_executable_with_flags(
gtest_catch_exceptions_no_ex_test_
googletest-catch-exceptions-no-ex-test_
"${cxx_no_exception}"
gtest_main_no_exception
test/gtest_catch_exceptions_test_.cc)
test/googletest-catch-exceptions-test_.cc)
endif()
cxx_executable_with_flags(
gtest_catch_exceptions_ex_test_
googletest-catch-exceptions-ex-test_
"${cxx_exception}"
gtest_main
test/gtest_catch_exceptions_test_.cc)
py_test(gtest_catch_exceptions_test)
test/googletest-catch-exceptions-test_.cc)
py_test(googletest-catch-exceptions-test)
cxx_executable(gtest_color_test_ test gtest)
py_test(gtest_color_test)
cxx_executable(googletest-color-test_ test gtest)
py_test(googletest-color-test)
cxx_executable(gtest_env_var_test_ test gtest)
py_test(gtest_env_var_test)
cxx_executable(googletest-env-var-test_ test gtest)
py_test(googletest-env-var-test)
cxx_executable(gtest_filter_unittest_ test gtest)
py_test(gtest_filter_unittest)
cxx_executable(googletest-filter-unittest_ test gtest)
py_test(googletest-filter-unittest)
cxx_executable(gtest_help_test_ test gtest_main)
py_test(gtest_help_test)
cxx_executable(gtest_list_tests_unittest_ test gtest)
py_test(gtest_list_tests_unittest)
cxx_executable(googletest-list-tests-unittest_ test gtest)
py_test(googletest-list-tests-unittest)
cxx_executable(gtest_output_test_ test gtest)
py_test(gtest_output_test)
cxx_executable(googletest-output-test_ test gtest)
py_test(googletest-output-test --no_stacktrace_support)
cxx_executable(gtest_shuffle_test_ test gtest)
py_test(gtest_shuffle_test)
cxx_executable(googletest-shuffle-test_ test gtest)
py_test(googletest-shuffle-test)
# MSVC 7.1 does not support STL with exceptions disabled.
if (NOT MSVC OR MSVC_VERSION GREATER 1310)
cxx_executable(gtest_throw_on_failure_test_ test gtest_no_exception)
set_target_properties(gtest_throw_on_failure_test_
cxx_executable(googletest-throw-on-failure-test_ test gtest_no_exception)
set_target_properties(googletest-throw-on-failure-test_
PROPERTIES
COMPILE_FLAGS "${cxx_no_exception}")
py_test(gtest_throw_on_failure_test)
py_test(googletest-throw-on-failure-test)
endif()
cxx_executable(gtest_uninitialized_test_ test gtest)
py_test(gtest_uninitialized_test)
cxx_executable(googletest-uninitialized-test_ test gtest)
py_test(googletest-uninitialized-test)
cxx_executable(gtest_xml_outfile1_test_ test gtest_main)
cxx_executable(gtest_xml_outfile2_test_ test gtest_main)
py_test(gtest_xml_outfiles_test)
py_test(gtest_json_outfiles_test)
py_test(googletest-json-outfiles-test)
cxx_executable(gtest_xml_output_unittest_ test gtest)
py_test(gtest_xml_output_unittest)
py_test(gtest_json_output_unittest)
py_test(gtest_xml_output_unittest --no_stacktrace_support)
py_test(googletest-json-output-unittest --no_stacktrace_support)
endif()

View File

@ -53,40 +53,40 @@ EXTRA_DIST += \
test/gtest-listener_test.cc \
test/gtest-message_test.cc \
test/gtest-options_test.cc \
test/gtest-param-test2_test.cc \
test/gtest-param-test2_test.cc \
test/gtest-param-test_test.cc \
test/gtest-param-test_test.cc \
test/googletest-param-test2-test.cc \
test/googletest-param-test2-test.cc \
test/googletest-param-test-test.cc \
test/googletest-param-test-test.cc \
test/gtest-param-test_test.h \
test/gtest-port_test.cc \
test/gtest_premature_exit_test.cc \
test/gtest-printers_test.cc \
test/gtest-test-part_test.cc \
test/gtest-tuple_test.cc \
test/googletest-tuple-test.cc \
test/gtest-typed-test2_test.cc \
test/gtest-typed-test_test.cc \
test/gtest-typed-test_test.h \
test/gtest-unittest-api_test.cc \
test/gtest_break_on_failure_unittest_.cc \
test/gtest_catch_exceptions_test_.cc \
test/gtest_color_test_.cc \
test/gtest_env_var_test_.cc \
test/googletest-break-on-failure-unittest_.cc \
test/googletest-catch-exceptions-test_.cc \
test/googletest-color-test_.cc \
test/googletest-env-var-test_.cc \
test/gtest_environment_test.cc \
test/gtest_filter_unittest_.cc \
test/googletest-filter-unittest_.cc \
test/gtest_help_test_.cc \
test/gtest_list_tests_unittest_.cc \
test/googletest-list-tests-unittest_.cc \
test/gtest_main_unittest.cc \
test/gtest_no_test_unittest.cc \
test/gtest_output_test_.cc \
test/googletest-output-test_.cc \
test/gtest_pred_impl_unittest.cc \
test/gtest_prod_test.cc \
test/gtest_repeat_test.cc \
test/gtest_shuffle_test_.cc \
test/googletest-shuffle-test_.cc \
test/gtest_sole_header_test.cc \
test/gtest_stress_test.cc \
test/gtest_throw_on_failure_ex_test.cc \
test/gtest_throw_on_failure_test_.cc \
test/gtest_uninitialized_test_.cc \
test/googletest-throw-on-failure-test_.cc \
test/googletest-uninitialized-test_.cc \
test/gtest_unittest.cc \
test/gtest_unittest.cc \
test/gtest_xml_outfile1_test_.cc \
@ -97,19 +97,19 @@ EXTRA_DIST += \
# Python tests that we don't run.
EXTRA_DIST += \
test/gtest_break_on_failure_unittest.py \
test/gtest_catch_exceptions_test.py \
test/gtest_color_test.py \
test/gtest_env_var_test.py \
test/gtest_filter_unittest.py \
test/googletest-break-on-failure-unittest.py \
test/googletest-catch-exceptions-test.py \
test/googletest-color-test.py \
test/googletest-env-var-test.py \
test/googletest-filter-unittest.py \
test/gtest_help_test.py \
test/gtest_list_tests_unittest.py \
test/gtest_output_test.py \
test/gtest_output_test_golden_lin.txt \
test/gtest_shuffle_test.py \
test/googletest-list-tests-unittest.py \
test/googletest-output-test.py \
test/googletest-output-test_golden_lin.txt \
test/googletest-shuffle-test.py \
test/gtest_test_utils.py \
test/gtest_throw_on_failure_test.py \
test/gtest_uninitialized_test.py \
test/googletest-throw-on-failure-test.py \
test/googletest-uninitialized-test.py \
test/gtest_xml_outfiles_test.py \
test/gtest_xml_output_unittest.py \
test/gtest_xml_test_utils.py

View File

@ -1,18 +1,16 @@
### Generic Build Instructions
### Generic Build Instructions ###
#### Setup
#### Setup ####
To build Google Test 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.
To build Google Test 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.
#### Build
#### Build ####
Suppose you put Google Test in directory `${GTEST_DIR}`. To build it,
create a library build target (or a project as called by Visual Studio
and Xcode) to compile
Suppose you put Google Test in directory `${GTEST_DIR}`. To build it, create a
library build target (or a project as called by Visual Studio and Xcode) to
compile
${GTEST_DIR}/src/gtest-all.cc
@ -26,98 +24,94 @@ something like the following will do:
(We need `-pthread` as Google Test uses threads.)
Next, you should compile your test source file with
`${GTEST_DIR}/include` in the system header search path, and link it
with gtest and any other necessary libraries:
Next, you should compile your test source file with `${GTEST_DIR}/include` in
the system header search path, and link it with gtest and any other necessary
libraries:
g++ -isystem ${GTEST_DIR}/include -pthread path/to/your_test.cc libgtest.a \
-o your_test
As an example, the make/ directory contains a Makefile that you can
use to build Google Test on systems where GNU make is available
(e.g. Linux, Mac OS X, and Cygwin). It doesn't try to build Google
Test's own tests. Instead, it just builds the Google Test library and
a sample test. You can use it as a starting point for your own build
script.
As an example, the make/ directory contains a Makefile that you can use to build
Google Test on systems where GNU make is available (e.g. Linux, Mac OS X, and
Cygwin). It doesn't try to build Google Test's own tests. Instead, it just
builds the Google Test 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:
If the default settings are correct for your environment, the following commands
should succeed:
cd ${GTEST_DIR}/make
make
./sample1_unittest
If you see errors, try to tweak the contents of `make/Makefile` to make
them go away. There are instructions in `make/Makefile` on how to do
it.
If you see errors, try to tweak the contents of `make/Makefile` to make them go
away. There are instructions in `make/Makefile` on how to do it.
### Using CMake ###
### Using CMake
Google Test comes with a CMake build script (
[CMakeLists.txt](CMakeLists.txt)) that can be used on a wide range of platforms ("C" stands for
cross-platform.). If you don't have CMake installed already, you can
download it for free from <http://www.cmake.org/>.
[CMakeLists.txt](https://github.com/google/googletest/blob/master/CMakeLists.txt))
that can be used on a wide range of platforms ("C" stands for cross-platform.).
If you don't have CMake installed already, you can download it for free from
<http://www.cmake.org/>.
CMake works by generating native makefiles or build projects that can
be used in the compiler environment of your choice. You can either
build Google Test as a standalone project or it can be incorporated
into an existing CMake build for another project.
CMake works by generating native makefiles or build projects that can be used in
the compiler environment of your choice. You can either build Google Test as a
standalone project or it can be incorporated into an existing CMake build for
another project.
#### Standalone CMake Project ####
#### Standalone CMake Project
When building Google Test as a standalone project, the typical
workflow starts with:
When building Google Test as a standalone project, the typical workflow starts
with:
mkdir mybuild # Create a directory to hold the build output.
cd mybuild
cmake ${GTEST_DIR} # Generate native build scripts.
If you want to build Google Test's samples, you should replace the
last command with
If you want to build Google Test's samples, you should replace the last command
with
cmake -Dgtest_build_samples=ON ${GTEST_DIR}
If you are on a \*nix system, you should now see a Makefile in the
current directory. Just type 'make' to build gtest.
If you are on a \*nix system, you should now see a Makefile in the current
directory. Just type 'make' to build gtest.
If you use Windows and have Visual Studio installed, a `gtest.sln` file
and several `.vcproj` files will be created. You can then build them
using Visual Studio.
If you use Windows and have Visual Studio installed, a `gtest.sln` file and
several `.vcproj` files will be created. You can then build them using Visual
Studio.
On Mac OS X with Xcode installed, a `.xcodeproj` file will be generated.
#### Incorporating Into An Existing CMake Project ####
#### Incorporating Into An Existing CMake Project
If you want to use gtest in a project which already uses CMake, then a
more robust and flexible approach is to build gtest as part of that
project directly. This is done by making the GoogleTest source code
available to the main build and adding it using CMake's
`add_subdirectory()` command. This has the significant advantage that
the same compiler and linker settings are used between gtest and the
rest of your project, so issues associated with using incompatible
libraries (eg debug/release), etc. are avoided. This is particularly
useful on Windows. Making GoogleTest's source code available to the
If you want to use gtest in a project which already uses CMake, then a more
robust and flexible approach is to build gtest as part of that project directly.
This is done by making the GoogleTest source code available to the main build
and adding it using CMake's `add_subdirectory()` command. This has the
significant advantage that the same compiler and linker settings are used
between gtest and the rest of your project, so issues associated with using
incompatible libraries (eg debug/release), etc. are avoided. This is
particularly useful on Windows. Making GoogleTest's source code available to the
main build can be done a few different ways:
* Download the GoogleTest source code manually and place it at a
known location. This is the least flexible approach and can make
it more difficult to use with continuous integration systems, etc.
* Embed the GoogleTest source code as a direct copy in the main
project's source tree. This is often the simplest approach, but is
also the hardest to keep up to date. Some organizations may not
permit this method.
* Add GoogleTest as a git submodule or equivalent. This may not
always be possible or appropriate. Git submodules, for example,
have their own set of advantages and drawbacks.
* Use CMake to download GoogleTest as part of the build's configure
step. This is just a little more complex, but doesn't have the
limitations of the other methods.
* Download the GoogleTest source code manually and place it at a known
location. This is the least flexible approach and can make it more difficult
to use with continuous integration systems, etc.
* Embed the GoogleTest source code as a direct copy in the main project's
source tree. This is often the simplest approach, but is also the hardest to
keep up to date. Some organizations may not permit this method.
* Add GoogleTest as a git submodule or equivalent. This may not always be
possible or appropriate. Git submodules, for example, have their own set of
advantages and drawbacks.
* Use CMake to download GoogleTest as part of the build's configure step. This
is just a little more complex, but doesn't have the limitations of the other
methods.
The last of the above methods is implemented with a small piece
of CMake code in a separate file (e.g. `CMakeLists.txt.in`) which
is copied to the build area and then invoked as a sub-build
_during the CMake stage_. That directory is then pulled into the
main build with `add_subdirectory()`. For example:
The last of the above methods is implemented with a small piece of CMake code in
a separate file (e.g. `CMakeLists.txt.in`) which is copied to the build area and
then invoked as a sub-build _during the CMake stage_. That directory is then
pulled into the main build with `add_subdirectory()`. For example:
New file `CMakeLists.txt.in`:
@ -176,101 +170,93 @@ Existing build's `CMakeLists.txt`:
target_link_libraries(example gtest_main)
add_test(NAME example_test COMMAND example)
Note that this approach requires CMake 2.8.2 or later due to
its use of the `ExternalProject_Add()` command. The above
technique is discussed in more detail in
[this separate article](http://crascit.com/2015/07/25/cmake-gtest/)
which also contains a link to a fully generalized implementation
of the technique.
Note that this approach requires CMake 2.8.2 or later due to its use of the
`ExternalProject_Add()` command. The above technique is discussed in more detail
in [this separate article](http://crascit.com/2015/07/25/cmake-gtest/) which
also contains a link to a fully generalized implementation of the technique.
##### Visual Studio Dynamic vs Static Runtimes #####
##### Visual Studio Dynamic vs Static Runtimes
By default, new Visual Studio projects link the C runtimes dynamically
but Google Test links them statically.
This will generate an error that looks something like the following:
gtest.lib(gtest-all.obj) : error LNK2038: mismatch detected for 'RuntimeLibrary': value 'MTd_StaticDebug' doesn't match value 'MDd_DynamicDebug' in main.obj
By default, new Visual Studio projects link the C runtimes dynamically but
Google Test links them statically. This will generate an error that looks
something like the following: gtest.lib(gtest-all.obj) : error LNK2038: mismatch
detected for 'RuntimeLibrary': value 'MTd_StaticDebug' doesn't match value
'MDd_DynamicDebug' in main.obj
Google Test already has a CMake option for this: `gtest_force_shared_crt`
Enabling this option will make gtest link the runtimes dynamically too,
and match the project in which it is included.
Enabling this option will make gtest link the runtimes dynamically too, and
match the project in which it is included.
### Legacy Build Scripts ###
### Legacy Build Scripts
Before settling on CMake, we have been providing hand-maintained build
projects/scripts for Visual Studio, Xcode, and Autotools. While we
continue to provide them for convenience, they are not actively
maintained any more. We highly recommend that you follow the
instructions in the above sections to integrate Google Test
with your existing build system.
projects/scripts for Visual Studio, Xcode, and Autotools. While we continue to
provide them for convenience, they are not actively maintained any more. We
highly recommend that you follow the instructions in the above sections to
integrate Google Test with your existing build system.
If you still need to use the legacy build scripts, here's how:
The msvc\ folder contains two solutions with Visual C++ projects.
Open the `gtest.sln` or `gtest-md.sln` file using Visual Studio, and you
are ready to build Google Test the same way you build any Visual
Studio project. Files that have names ending with -md use DLL
versions of Microsoft runtime libraries (the /MD or the /MDd compiler
option). Files without that suffix use static versions of the runtime
libraries (the /MT or the /MTd option). Please note that one must use
the same option to compile both gtest and the test code. If you use
Visual Studio 2005 or above, we recommend the -md version as /MD is
the default for new projects in these versions of Visual Studio.
The msvc\ folder contains two solutions with Visual C++ projects. Open the
`gtest.sln` or `gtest-md.sln` file using Visual Studio, and you are ready to
build Google Test the same way you build any Visual Studio project. Files that
have names ending with -md use DLL versions of Microsoft runtime libraries (the
/MD or the /MDd compiler option). Files without that suffix use static versions
of the runtime libraries (the /MT or the /MTd option). Please note that one must
use the same option to compile both gtest and the test code. If you use Visual
Studio 2005 or above, we recommend the -md version as /MD is the default for new
projects in these versions of Visual Studio.
On Mac OS X, open the `gtest.xcodeproj` in the `xcode/` folder using
Xcode. Build the "gtest" target. The universal binary framework will
end up in your selected build directory (selected in the Xcode
"Preferences..." -> "Building" pane and defaults to xcode/build).
Alternatively, at the command line, enter:
On Mac OS X, open the `gtest.xcodeproj` in the `xcode/` folder using Xcode.
Build the "gtest" target. The universal binary framework will end up in your
selected build directory (selected in the Xcode "Preferences..." -> "Building"
pane and defaults to xcode/build). Alternatively, at the command line, enter:
xcodebuild
This will build the "Release" configuration of gtest.framework in your
default build location. See the "xcodebuild" man page for more
information about building different configurations and building in
different locations.
This will build the "Release" configuration of gtest.framework in your default
build location. See the "xcodebuild" man page for more information about
building different configurations and building in different locations.
If you wish to use the Google Test Xcode project with Xcode 4.x and
above, you need to either:
If you wish to use the Google Test Xcode project with Xcode 4.x and above, you
need to either:
* update the SDK configuration options in xcode/Config/General.xconfig.
* update the SDK configuration options in xcode/Config/General.xconfig.
Comment options `SDKROOT`, `MACOS_DEPLOYMENT_TARGET`, and `GCC_VERSION`. If
you choose this route you lose the ability to target earlier versions
of MacOS X.
* Install an SDK for an earlier version. This doesn't appear to be
supported by Apple, but has been reported to work
you choose this route you lose the ability to target earlier versions of
MacOS X.
* Install an SDK for an earlier version. This doesn't appear to be supported
by Apple, but has been reported to work
(http://stackoverflow.com/questions/5378518).
### Tweaking Google Test ###
### Tweaking Google Test
Google Test 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 Test 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.
Google Test 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 Test 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 [include/gtest/internal/gtest-port.h](include/gtest/internal/gtest-port.h).
We list the most frequently used macros below. For a complete list, see file
[include/gtest/internal/gtest-port.h](https://github.com/google/googletest/blob/master/include/gtest/internal/gtest-port.h).
### Choosing a TR1 Tuple Library ###
### Choosing a TR1 Tuple Library
Some Google Test features require the C++ Technical Report 1 (TR1)
tuple library, which is not yet available with all compilers. The
good news is that Google Test implements a subset of TR1 tuple that's
enough for its own need, and will automatically use this when the
compiler doesn't provide TR1 tuple.
Some Google Test features require the C++ Technical Report 1 (TR1) tuple
library, which is not yet available with all compilers. The good news is that
Google Test implements a subset of TR1 tuple that's enough for its own need, and
will automatically use this when the compiler doesn't provide TR1 tuple.
Usually you don't need to care about which tuple library Google Test
uses. However, if your project already uses TR1 tuple, you need to
tell Google Test to use the same TR1 tuple library the rest of your
project uses, or the two tuple implementations will clash. To do
that, add
Usually you don't need to care about which tuple library Google Test uses.
However, if your project already uses TR1 tuple, you need to tell Google Test 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 and your tests. If
you want to force Google Test to use its own tuple library, just add
to the compiler flags while compiling Google Test and your tests. If you want to
force Google Test to use its own tuple library, just add
-DGTEST_USE_OWN_TR1_TUPLE=1
@ -282,15 +268,15 @@ If you don't want Google Test to use tuple at all, add
and all features using tuple will be disabled.
### Multi-threaded Tests ###
### Multi-threaded Tests
Google Test is thread-safe where the pthread library is available.
After `#include "gtest/gtest.h"`, you can check the `GTEST_IS_THREADSAFE`
macro to see whether this is the case (yes if the macro is `#defined` to
1, no if it's undefined.).
Google Test is thread-safe where the pthread library is available. After
`#include "gtest/gtest.h"`, you can check the `GTEST_IS_THREADSAFE` macro to see
whether this is the case (yes if the macro is `#defined` to 1, no if it's
undefined.).
If Google Test doesn't correctly detect whether pthread is available
in your environment, you can force it with
If Google Test doesn't correctly detect whether pthread is available in your
environment, you can force it with
-DGTEST_HAS_PTHREAD=1
@ -298,26 +284,24 @@ or
-DGTEST_HAS_PTHREAD=0
When Google Test uses pthread, you may need to add flags to your
compiler and/or linker to select the pthread library, or you'll get
link errors. If you use the CMake script or the deprecated Autotools
script, this is taken care of for you. If you use your own build
script, you'll need to read your compiler and linker's manual to
figure out what flags to add.
When Google Test uses pthread, you may need to add flags to your compiler and/or
linker to select the pthread library, or you'll get link errors. If you use the
CMake script or the deprecated Autotools script, this is taken care of for you.
If you use your own build script, you'll need to read your compiler and linker's
manual to figure out what flags to add.
### As a Shared Library (DLL) ###
### As a Shared Library (DLL)
Google Test is compact, so most users can build and link it as a
static library for the simplicity. You can choose to use Google Test
as a shared library (known as a DLL on Windows) if you prefer.
Google Test is compact, so most users can build and link it as a static library
for the simplicity. You can choose to use Google Test as a shared library (known
as a DLL on Windows) if you prefer.
To compile *gtest* as a shared library, add
-DGTEST_CREATE_SHARED_LIBRARY=1
to the compiler flags. You'll also need to tell the linker to produce
a shared library instead - consult your linker's manual for how to do
it.
to the compiler flags. You'll also need to tell the linker to produce a shared
library instead - consult your linker's manual for how to do it.
To compile your *tests* that use the gtest shared library, add
@ -325,31 +309,28 @@ To compile your *tests* that use the gtest shared library, add
to the compiler flags.
Note: while the above steps aren't technically necessary today when
using some compilers (e.g. GCC), they may become necessary in the
future, if we decide to improve the speed of loading the library (see
<http://gcc.gnu.org/wiki/Visibility> for details). Therefore you are
recommended to always add the above flags when using Google Test as a
shared library. Otherwise a future release of Google Test may break
your build script.
Note: while the above steps aren't technically necessary today when using some
compilers (e.g. GCC), they may become necessary in the future, if we decide to
improve the speed of loading the library (see
<http://gcc.gnu.org/wiki/Visibility> for details). Therefore you are recommended
to always add the above flags when using Google Test as a shared library.
Otherwise a future release of Google Test may break your build script.
### Avoiding Macro Name Clashes ###
### Avoiding Macro Name Clashes
In C++, macros don't obey namespaces. Therefore two libraries that
both define a macro of the same name will clash if you `#include` both
definitions. In case a Google Test macro clashes with another
library, you can force Google Test to rename its macro to avoid the
conflict.
In C++, macros don't obey namespaces. Therefore two libraries that both define a
macro of the same name will clash if you `#include` both definitions. In case a
Google Test macro clashes with another library, you can force Google Test to
rename its macro to avoid the conflict.
Specifically, if both Google Test and some other code define macro
FOO, you can add
Specifically, if both Google Test and some other code define macro FOO, you can
add
-DGTEST_DONT_DEFINE_FOO=1
to the compiler flags to tell Google Test to change the macro's name
from `FOO` to `GTEST_FOO`. Currently `FOO` can be `FAIL`, `SUCCEED`,
or `TEST`. For example, with `-DGTEST_DONT_DEFINE_TEST=1`, you'll
need to write
to the compiler flags to tell Google Test to change the macro's name from `FOO`
to `GTEST_FOO`. Currently `FOO` can be `FAIL`, `SUCCEED`, or `TEST`. For
example, with `-DGTEST_DONT_DEFINE_TEST=1`, you'll need to write
GTEST_TEST(SomeTest, DoesThis) { ... }

View File

@ -20,7 +20,7 @@ macro(fix_default_compiler_settings_)
if (MSVC)
# For MSVC, CMake sets certain flags to defaults we want to override.
# This replacement code is taken from sample in the CMake Wiki at
# http://www.cmake.org/Wiki/CMake_FAQ#Dynamic_Replace.
# https://gitlab.kitware.com/cmake/community/wikis/FAQ#dynamic-replace.
foreach (flag_var
CMAKE_CXX_FLAGS CMAKE_CXX_FLAGS_DEBUG CMAKE_CXX_FLAGS_RELEASE
CMAKE_CXX_FLAGS_MINSIZEREL CMAKE_CXX_FLAGS_RELWITHDEBINFO)
@ -230,7 +230,7 @@ find_package(PythonInterp)
# from the given source files with the given compiler flags.
function(cxx_test_with_flags name cxx_flags libs)
cxx_executable_with_flags(${name} "${cxx_flags}" "${libs}" ${ARGN})
add_test(${name} ${name})
add_test(NAME ${name} COMMAND ${name})
endfunction()
# cxx_test(name libs srcs...)
@ -257,14 +257,14 @@ function(py_test name)
add_test(
NAME ${name}
COMMAND ${PYTHON_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/test/${name}.py
--build_dir=${CMAKE_CURRENT_BINARY_DIR}/$<CONFIG>)
--build_dir=${CMAKE_CURRENT_BINARY_DIR}/$<CONFIG> ${ARGN})
else (CMAKE_CONFIGURATION_TYPES)
# Single-configuration build generators like Makefile generators
# don't have subdirs below CMAKE_CURRENT_BINARY_DIR.
add_test(
NAME ${name}
COMMAND ${PYTHON_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/test/${name}.py
--build_dir=${CMAKE_CURRENT_BINARY_DIR})
--build_dir=${CMAKE_CURRENT_BINARY_DIR} ${ARGN})
endif (CMAKE_CONFIGURATION_TYPES)
else (${CMAKE_MAJOR_VERSION}.${CMAKE_MINOR_VERSION} GREATER 3.1)
# ${CMAKE_CURRENT_BINARY_DIR} is known at configuration time, so we can
@ -274,7 +274,7 @@ function(py_test name)
add_test(
${name}
${PYTHON_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/test/${name}.py
--build_dir=${CMAKE_CURRENT_BINARY_DIR}/\${CTEST_CONFIGURATION_TYPE})
--build_dir=${CMAKE_CURRENT_BINARY_DIR}/\${CTEST_CONFIGURATION_TYPE} ${ARGN})
endif (${CMAKE_MAJOR_VERSION}.${CMAKE_MINOR_VERSION} GREATER 3.1)
endif(PYTHONINTERP_FOUND)
endfunction()

File diff suppressed because it is too large Load Diff

View File

@ -1,16 +0,0 @@
This page lists all documentation markdown files for Google Test **(the
current git version)**
-- **if you use a former version of Google Test, please read the
documentation for that specific version instead (e.g. by checking out
the respective git branch/tag).**
* [Primer](Primer.md) -- start here if you are new to Google Test.
* [Samples](Samples.md) -- learn from examples.
* [AdvancedGuide](AdvancedGuide.md) -- learn more about Google Test.
* [XcodeGuide](XcodeGuide.md) -- how to use Google Test in Xcode on Mac.
* [Frequently-Asked Questions](FAQ.md) -- check here before asking a question on the mailing list.
To contribute code to Google Test, read:
* [CONTRIBUTING](../../CONTRIBUTING.md) -- read this _before_ writing your first patch.
* [PumpManual](PumpManual.md) -- how we generate some of Google Test's source files.

File diff suppressed because it is too large Load Diff

View File

@ -1,536 +0,0 @@
# Introduction: Why Google C++ Testing Framework? #
_Google C++ Testing Framework_ helps you write better C++ tests.
No matter whether you work on Linux, Windows, or a Mac, if you write C++ code,
Google Test can help you.
So what makes a good test, and how does Google C++ Testing Framework fit in? We believe:
1. Tests should be _independent_ and _repeatable_. It's a pain to debug a test that succeeds or fails as a result of other tests. Google C++ Testing Framework isolates the tests by running each of them on a different object. When a test fails, Google C++ Testing Framework allows you to run it in isolation for quick debugging.
1. Tests should be well _organized_ and reflect the structure of the tested code. Google C++ Testing Framework groups related tests into test cases that can share data and subroutines. This common pattern is easy to recognize and makes tests easy to maintain. Such consistency is especially helpful when people switch projects and start to work on a new code base.
1. Tests should be _portable_ and _reusable_. The open-source community has a lot of code that is platform-neutral, its tests should also be platform-neutral. Google C++ Testing Framework works on different OSes, with different compilers (gcc, MSVC, and others), with or without exceptions, so Google C++ Testing Framework tests can easily work with a variety of configurations. (Note that the current release only contains build scripts for Linux - we are actively working on scripts for other platforms.)
1. When tests fail, they should provide as much _information_ about the problem as possible. Google C++ Testing Framework doesn't stop at the first test failure. Instead, it only stops the current test and continues with the next. You can also set up tests that report non-fatal failures after which the current test continues. Thus, you can detect and fix multiple bugs in a single run-edit-compile cycle.
1. The testing framework should liberate test writers from housekeeping chores and let them focus on the test _content_. Google C++ Testing Framework automatically keeps track of all tests defined, and doesn't require the user to enumerate them in order to run them.
1. Tests should be _fast_. With Google C++ Testing Framework, you can reuse shared resources across tests and pay for the set-up/tear-down only once, without making tests depend on each other.
Since Google C++ Testing Framework is based on the popular xUnit
architecture, you'll feel right at home if you've used JUnit or PyUnit before.
If not, it will take you about 10 minutes to learn the basics and get started.
So let's go!
_Note:_ We sometimes refer to Google C++ Testing Framework informally
as _Google Test_.
# Beware of the nomenclature #
_Note:_ There might be some confusion of idea due to different
definitions of the terms _Test_, _Test Case_ and _Test Suite_, so beware
of misunderstanding these.
Historically, the Google C++ Testing Framework started to use the term
_Test Case_ for grouping related tests, whereas current publications
including the International Software Testing Qualifications Board
([ISTQB](http://www.istqb.org/)) and various textbooks on Software
Quality use the term _[Test
Suite](http://glossary.istqb.org/search/test%20suite)_ for this.
The related term _Test_, as it is used in the Google C++ Testing
Framework, is corresponding to the term _[Test
Case](http://glossary.istqb.org/search/test%20case)_ of ISTQB and
others.
The term _Test_ is commonly of broad enough sense, including ISTQB's
definition of _Test Case_, so it's not much of a problem here. But the
term _Test Case_ as used in Google Test is of contradictory sense and thus confusing.
Unfortunately replacing the term _Test Case_ by _Test Suite_ throughout
the Google C++ Testing Framework is not easy without breaking dependent
projects, as `TestCase` is part of the public API at various places.
So for the time being, please be aware of the different definitions of
the terms:
Meaning | Google Test Term | [ISTQB](http://www.istqb.org/) Term
------- | ---------------- | -----------------------------------
Exercise a particular program path with specific input values and verify the results | [TEST()](#simple-tests) | [Test Case](http://glossary.istqb.org/search/test%20case)
A set of several tests related to one component | [Test Case](#basic-concepts) | [Test Suite](http://glossary.istqb.org/search/test%20suite)
# Setting up a New Test Project #
To write a test program using Google Test, you need to compile Google
Test into a library and link your test with it. We provide build
files for some popular build systems: `msvc/` for Visual Studio,
`xcode/` for Mac Xcode, `make/` for GNU make, `codegear/` for Borland
C++ Builder, and the autotools script (deprecated) and
`CMakeLists.txt` for CMake (recommended) in the Google Test root
directory. If your build system is not on this list, you can take a
look at `make/Makefile` to learn how Google Test should be compiled
(basically you want to compile `src/gtest-all.cc` with `GTEST_ROOT`
and `GTEST_ROOT/include` in the header search path, where `GTEST_ROOT`
is the Google Test root directory).
Once you are able to compile the Google Test library, you should
create a project or build target for your test program. Make sure you
have `GTEST_ROOT/include` in the header search path so that the
compiler can find `"gtest/gtest.h"` when compiling your test. Set up
your test project to link with the Google Test library (for example,
in Visual Studio, this is done by adding a dependency on
`gtest.vcproj`).
If you still have questions, take a look at how Google Test's own
tests are built and use them as examples.
# Basic Concepts #
When using Google Test, you start by writing _assertions_, which are statements
that check whether a condition is true. An assertion's result can be _success_,
_nonfatal failure_, or _fatal failure_. If a fatal failure occurs, it aborts
the current function; otherwise the program continues normally.
_Tests_ use assertions to verify the tested code's behavior. If a test crashes
or has a failed assertion, then it _fails_; otherwise it _succeeds_.
A _test case_ contains one or many tests. You should group your tests into test
cases that reflect the structure of the tested code. When multiple tests in a
test case need to share common objects and subroutines, you can put them into a
_test fixture_ class.
A _test program_ can contain multiple test cases.
We'll now explain how to write a test program, starting at the individual
assertion level and building up to tests and test cases.
# Assertions #
Google Test assertions are macros that resemble function calls. You test a
class or function by making assertions about its behavior. When an assertion
fails, Google Test prints the assertion's source file and line number location,
along with a failure message. You may also supply a custom failure message
which will be appended to Google Test's message.
The assertions come in pairs that test the same thing but have different
effects on the current function. `ASSERT_*` versions generate fatal failures
when they fail, and **abort the current function**. `EXPECT_*` versions generate
nonfatal failures, which don't abort the current function. Usually `EXPECT_*`
are preferred, as they allow more than one failures to be reported in a test.
However, you should use `ASSERT_*` if it doesn't make sense to continue when
the assertion in question fails.
Since a failed `ASSERT_*` returns from the current function immediately,
possibly skipping clean-up code that comes after it, it may cause a space leak.
Depending on the nature of the leak, it may or may not be worth fixing - so
keep this in mind if you get a heap checker error in addition to assertion
errors.
To provide a custom failure message, simply stream it into the macro using the
`<<` operator, or a sequence of such operators. An example:
```
ASSERT_EQ(x.size(), y.size()) << "Vectors x and y are of unequal length";
for (int i = 0; i < x.size(); ++i) {
EXPECT_EQ(x[i], y[i]) << "Vectors x and y differ at index " << i;
}
```
Anything that can be streamed to an `ostream` can be streamed to an assertion
macro--in particular, C strings and `string` objects. If a wide string
(`wchar_t*`, `TCHAR*` in `UNICODE` mode on Windows, or `std::wstring`) is
streamed to an assertion, it will be translated to UTF-8 when printed.
## Basic Assertions ##
These assertions do basic true/false condition testing.
| **Fatal assertion** | **Nonfatal assertion** | **Verifies** |
|:--------------------|:-----------------------|:-------------|
| `ASSERT_TRUE(`_condition_`)`; | `EXPECT_TRUE(`_condition_`)`; | _condition_ is true |
| `ASSERT_FALSE(`_condition_`)`; | `EXPECT_FALSE(`_condition_`)`; | _condition_ is false |
Remember, when they fail, `ASSERT_*` yields a fatal failure and
returns from the current function, while `EXPECT_*` yields a nonfatal
failure, allowing the function to continue running. In either case, an
assertion failure means its containing test fails.
_Availability_: Linux, Windows, Mac.
## Binary Comparison ##
This section describes assertions that compare two values.
| **Fatal assertion** | **Nonfatal assertion** | **Verifies** |
|:--------------------|:-----------------------|:-------------|
|`ASSERT_EQ(`_val1_`, `_val2_`);`|`EXPECT_EQ(`_val1_`, `_val2_`);`| _val1_ `==` _val2_ |
|`ASSERT_NE(`_val1_`, `_val2_`);`|`EXPECT_NE(`_val1_`, `_val2_`);`| _val1_ `!=` _val2_ |
|`ASSERT_LT(`_val1_`, `_val2_`);`|`EXPECT_LT(`_val1_`, `_val2_`);`| _val1_ `<` _val2_ |
|`ASSERT_LE(`_val1_`, `_val2_`);`|`EXPECT_LE(`_val1_`, `_val2_`);`| _val1_ `<=` _val2_ |
|`ASSERT_GT(`_val1_`, `_val2_`);`|`EXPECT_GT(`_val1_`, `_val2_`);`| _val1_ `>` _val2_ |
|`ASSERT_GE(`_val1_`, `_val2_`);`|`EXPECT_GE(`_val1_`, `_val2_`);`| _val1_ `>=` _val2_ |
In the event of a failure, Google Test prints both _val1_ and _val2_.
Value arguments must be comparable by the assertion's comparison
operator or you'll get a compiler error. We used to require the
arguments to support the `<<` operator for streaming to an `ostream`,
but it's no longer necessary since v1.6.0 (if `<<` is supported, it
will be called to print the arguments when the assertion fails;
otherwise Google Test will attempt to print them in the best way it
can. For more details and how to customize the printing of the
arguments, see this Google Mock [recipe](../../googlemock/docs/CookBook.md#teaching-google-mock-how-to-print-your-values).).
These assertions can work with a user-defined type, but only if you define the
corresponding comparison operator (e.g. `==`, `<`, etc). If the corresponding
operator is defined, prefer using the `ASSERT_*()` macros because they will
print out not only the result of the comparison, but the two operands as well.
Arguments are always evaluated exactly once. Therefore, it's OK for the
arguments to have side effects. However, as with any ordinary C/C++ function,
the arguments' evaluation order is undefined (i.e. the compiler is free to
choose any order) and your code should not depend on any particular argument
evaluation order.
`ASSERT_EQ()` does pointer equality on pointers. If used on two C strings, it
tests if they are in the same memory location, not if they have the same value.
Therefore, if you want to compare C strings (e.g. `const char*`) by value, use
`ASSERT_STREQ()` , which will be described later on. In particular, to assert
that a C string is `NULL`, use `ASSERT_STREQ(NULL, c_string)` . However, to
compare two `string` objects, you should use `ASSERT_EQ`.
Macros in this section work with both narrow and wide string objects (`string`
and `wstring`).
_Availability_: Linux, Windows, Mac.
_Historical note_: Before February 2016 `*_EQ` had a convention of calling it as
`ASSERT_EQ(expected, actual)`, so lots of existing code uses this order.
Now `*_EQ` treats both parameters in the same way.
## String Comparison ##
The assertions in this group compare two **C strings**. If you want to compare
two `string` objects, use `EXPECT_EQ`, `EXPECT_NE`, and etc instead.
| **Fatal assertion** | **Nonfatal assertion** | **Verifies** |
|:--------------------|:-----------------------|:-------------|
| `ASSERT_STREQ(`_str1_`, `_str2_`);` | `EXPECT_STREQ(`_str1_`, `_str2_`);` | the two C strings have the same content |
| `ASSERT_STRNE(`_str1_`, `_str2_`);` | `EXPECT_STRNE(`_str1_`, `_str2_`);` | the two C strings have different content |
| `ASSERT_STRCASEEQ(`_str1_`, `_str2_`);`| `EXPECT_STRCASEEQ(`_str1_`, `_str2_`);` | the two C strings have the same content, ignoring case |
| `ASSERT_STRCASENE(`_str1_`, `_str2_`);`| `EXPECT_STRCASENE(`_str1_`, `_str2_`);` | the two C strings have different content, ignoring case |
Note that "CASE" in an assertion name means that case is ignored.
`*STREQ*` and `*STRNE*` also accept wide C strings (`wchar_t*`). If a
comparison of two wide strings fails, their values will be printed as UTF-8
narrow strings.
A `NULL` pointer and an empty string are considered _different_.
_Availability_: Linux, Windows, Mac.
See also: For more string comparison tricks (substring, prefix, suffix, and
regular expression matching, for example), see the [Advanced Google Test Guide](AdvancedGuide.md).
# Simple Tests #
To create a test:
1. Use the `TEST()` macro to define and name a test function, These are ordinary C++ functions that don't return a value.
1. In this function, along with any valid C++ statements you want to include, use the various Google Test assertions to check values.
1. The test's result is determined by the assertions; if any assertion in the test fails (either fatally or non-fatally), or if the test crashes, the entire test fails. Otherwise, it succeeds.
```
TEST(testCaseName, testName) {
... test body ...
}
```
`TEST()` arguments go from general to specific. The _first_ argument is the
name of the test case, and the _second_ argument is the test's name within the
test case. Both names must be valid C++ identifiers, and they should not contain underscore (`_`). A test's _full name_ consists of its containing test case and its
individual name. Tests from different test cases can have the same individual
name.
For example, let's take a simple integer function:
```
int Factorial(int n); // Returns the factorial of n
```
A test case for this function might look like:
```
// Tests factorial of 0.
TEST(FactorialTest, HandlesZeroInput) {
EXPECT_EQ(1, Factorial(0));
}
// Tests factorial of positive numbers.
TEST(FactorialTest, HandlesPositiveInput) {
EXPECT_EQ(1, Factorial(1));
EXPECT_EQ(2, Factorial(2));
EXPECT_EQ(6, Factorial(3));
EXPECT_EQ(40320, Factorial(8));
}
```
Google Test groups the test results by test cases, so logically-related tests
should be in the same test case; in other words, the first argument to their
`TEST()` should be the same. In the above example, we have two tests,
`HandlesZeroInput` and `HandlesPositiveInput`, that belong to the same test
case `FactorialTest`.
_Availability_: Linux, Windows, Mac.
# Test Fixtures: Using the Same Data Configuration for Multiple Tests #
If you find yourself writing two or more tests that operate on similar data,
you can use a _test fixture_. It allows you to reuse the same configuration of
objects for several different tests.
To create a fixture, just:
1. Derive a class from `::testing::Test` . Start its body with `protected:` or `public:` as we'll want to access fixture members from sub-classes.
1. Inside the class, declare any objects you plan to use.
1. If necessary, write a default constructor or `SetUp()` function to prepare the objects for each test. A common mistake is to spell `SetUp()` as `Setup()` with a small `u` - don't let that happen to you.
1. If necessary, write a destructor or `TearDown()` function to release any resources you allocated in `SetUp()` . To learn when you should use the constructor/destructor and when you should use `SetUp()/TearDown()`, read this [FAQ entry](FAQ.md#should-i-use-the-constructordestructor-of-the-test-fixture-or-the-set-uptear-down-function).
1. If needed, define subroutines for your tests to share.
When using a fixture, use `TEST_F()` instead of `TEST()` as it allows you to
access objects and subroutines in the test fixture:
```
TEST_F(test_case_name, test_name) {
... test body ...
}
```
Like `TEST()`, the first argument is the test case name, but for `TEST_F()`
this must be the name of the test fixture class. You've probably guessed: `_F`
is for fixture.
Unfortunately, the C++ macro system does not allow us to create a single macro
that can handle both types of tests. Using the wrong macro causes a compiler
error.
Also, you must first define a test fixture class before using it in a
`TEST_F()`, or you'll get the compiler error "`virtual outside class
declaration`".
For each test defined with `TEST_F()`, Google Test will:
1. Create a _fresh_ test fixture at runtime
1. Immediately initialize it via `SetUp()`
1. Run the test
1. Clean up by calling `TearDown()`
1. Delete the test fixture. Note that different tests in the same test case have different test fixture objects, and Google Test always deletes a test fixture before it creates the next one. Google Test does not reuse the same test fixture for multiple tests. Any changes one test makes to the fixture do not affect other tests.
As an example, let's write tests for a FIFO queue class named `Queue`, which
has the following interface:
```
template <typename E> // E is the element type.
class Queue {
public:
Queue();
void Enqueue(const E& element);
E* Dequeue(); // Returns NULL if the queue is empty.
size_t size() const;
...
};
```
First, define a fixture class. By convention, you should give it the name
`FooTest` where `Foo` is the class being tested.
```
class QueueTest : public ::testing::Test {
protected:
virtual void SetUp() {
q1_.Enqueue(1);
q2_.Enqueue(2);
q2_.Enqueue(3);
}
// virtual void TearDown() {}
Queue<int> q0_;
Queue<int> q1_;
Queue<int> q2_;
};
```
In this case, `TearDown()` is not needed since we don't have to clean up after
each test, other than what's already done by the destructor.
Now we'll write tests using `TEST_F()` and this fixture.
```
TEST_F(QueueTest, IsEmptyInitially) {
EXPECT_EQ(0, q0_.size());
}
TEST_F(QueueTest, DequeueWorks) {
int* n = q0_.Dequeue();
EXPECT_EQ(NULL, n);
n = q1_.Dequeue();
ASSERT_TRUE(n != NULL);
EXPECT_EQ(1, *n);
EXPECT_EQ(0, q1_.size());
delete n;
n = q2_.Dequeue();
ASSERT_TRUE(n != NULL);
EXPECT_EQ(2, *n);
EXPECT_EQ(1, q2_.size());
delete n;
}
```
The above uses both `ASSERT_*` and `EXPECT_*` assertions. The rule of thumb is
to use `EXPECT_*` when you want the test to continue to reveal more errors
after the assertion failure, and use `ASSERT_*` when continuing after failure
doesn't make sense. For example, the second assertion in the `Dequeue` test is
`ASSERT_TRUE(n != NULL)`, as we need to dereference the pointer `n` later,
which would lead to a segfault when `n` is `NULL`.
When these tests run, the following happens:
1. Google Test constructs a `QueueTest` object (let's call it `t1` ).
1. `t1.SetUp()` initializes `t1` .
1. The first test ( `IsEmptyInitially` ) runs on `t1` .
1. `t1.TearDown()` cleans up after the test finishes.
1. `t1` is destructed.
1. The above steps are repeated on another `QueueTest` object, this time running the `DequeueWorks` test.
_Availability_: Linux, Windows, Mac.
_Note_: Google Test automatically saves all _Google Test_ flags when a test
object is constructed, and restores them when it is destructed.
# Invoking the Tests #
`TEST()` and `TEST_F()` implicitly register their tests with Google Test. So, unlike with many other C++ testing frameworks, you don't have to re-list all your defined tests in order to run them.
After defining your tests, you can run them with `RUN_ALL_TESTS()` , which returns `0` if all the tests are successful, or `1` otherwise. Note that `RUN_ALL_TESTS()` runs _all tests_ in your link unit -- they can be from different test cases, or even different source files.
When invoked, the `RUN_ALL_TESTS()` macro:
1. Saves the state of all Google Test flags.
1. Creates a test fixture object for the first test.
1. Initializes it via `SetUp()`.
1. Runs the test on the fixture object.
1. Cleans up the fixture via `TearDown()`.
1. Deletes the fixture.
1. Restores the state of all Google Test flags.
1. Repeats the above steps for the next test, until all tests have run.
In addition, if the test fixture's constructor generates a fatal failure in
step 2, there is no point for step 3 - 5 and they are thus skipped. Similarly,
if step 3 generates a fatal failure, step 4 will be skipped.
_Important_: You must not ignore the return value of `RUN_ALL_TESTS()`, or `gcc`
will give you a compiler error. The rationale for this design is that the
automated testing service determines whether a test has passed based on its
exit code, not on its stdout/stderr output; thus your `main()` function must
return the value of `RUN_ALL_TESTS()`.
Also, you should call `RUN_ALL_TESTS()` only **once**. Calling it more than once
conflicts with some advanced Google Test features (e.g. thread-safe death
tests) and thus is not supported.
_Availability_: Linux, Windows, Mac.
# Writing the main() Function #
You can start from this boilerplate:
```
#include "this/package/foo.h"
#include "gtest/gtest.h"
namespace {
// The fixture for testing class Foo.
class FooTest : public ::testing::Test {
protected:
// You can remove any or all of the following functions if its body
// is empty.
FooTest() {
// You can do set-up work for each test here.
}
virtual ~FooTest() {
// You can do clean-up work that doesn't throw exceptions here.
}
// If the constructor and destructor are not enough for setting up
// and cleaning up each test, you can define the following methods:
virtual void SetUp() {
// Code here will be called immediately after the constructor (right
// before each test).
}
virtual void TearDown() {
// Code here will be called immediately after each test (right
// before the destructor).
}
// Objects declared here can be used by all tests in the test case for Foo.
};
// Tests that the Foo::Bar() method does Abc.
TEST_F(FooTest, MethodBarDoesAbc) {
const string input_filepath = "this/package/testdata/myinputfile.dat";
const string output_filepath = "this/package/testdata/myoutputfile.dat";
Foo f;
EXPECT_EQ(0, f.Bar(input_filepath, output_filepath));
}
// Tests that Foo does Xyz.
TEST_F(FooTest, DoesXyz) {
// Exercises the Xyz feature of Foo.
}
} // namespace
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
```
The `::testing::InitGoogleTest()` function parses the command line for Google
Test flags, and removes all recognized flags. This allows the user to control a
test program's behavior via various flags, which we'll cover in [AdvancedGuide](AdvancedGuide.md).
You must call this function before calling `RUN_ALL_TESTS()`, or the flags
won't be properly initialized.
On Windows, `InitGoogleTest()` also works with wide strings, so it can be used
in programs compiled in `UNICODE` mode as well.
But maybe you think that writing all those main() functions is too much work? We agree with you completely and that's why Google Test provides a basic implementation of main(). If it fits your needs, then just link your test with gtest\_main library and you are good to go.
## Important note for Visual C++ users ##
If you put your tests into a library and your `main()` function is in a different library or in your .exe file, those tests will not run. The reason is a [bug](https://connect.microsoft.com/feedback/viewfeedback.aspx?FeedbackID=244410&siteid=210) in Visual C++. When you define your tests, Google Test creates certain static objects to register them. These objects are not referenced from elsewhere but their constructors are still supposed to run. When Visual C++ linker sees that nothing in the library is referenced from other places it throws the library out. You have to reference your library with tests from your main program to keep the linker from discarding it. Here is how to do it. Somewhere in your library code declare a function:
```
__declspec(dllexport) int PullInMyLibrary() { return 0; }
```
If you put your tests in a static library (not DLL) then `__declspec(dllexport)` is not required. Now, in your main program, write a code that invokes that function:
```
int PullInMyLibrary();
static int dummy = PullInMyLibrary();
```
This will keep your tests referenced and will make them register themselves at startup.
In addition, if you define your tests in a static library, add `/OPT:NOREF` to your main program linker options. If you use MSVC++ IDE, go to your .exe project properties/Configuration Properties/Linker/Optimization and set References setting to `Keep Unreferenced Data (/OPT:NOREF)`. This will keep Visual C++ linker from discarding individual symbols generated by your tests from the final executable.
There is one more pitfall, though. If you use Google Test as a static library (that's how it is defined in gtest.vcproj) your tests must also reside in a static library. If you have to have them in a DLL, you _must_ change Google Test to build into a DLL as well. Otherwise your tests will not run correctly or will not run at all. The general conclusion here is: make your life easier - do not write your tests in libraries!
# Where to Go from Here #
Congratulations! You've learned the Google Test basics. You can start writing
and running Google Test tests, read some [samples](Samples.md), or continue with
[AdvancedGuide](AdvancedGuide.md), which describes many more useful Google Test features.
# Known Limitations #
Google Test is designed to be thread-safe. The implementation is
thread-safe on systems where the `pthreads` library is available. It
is currently _unsafe_ to use Google Test assertions from two threads
concurrently on other systems (e.g. Windows). In most tests this is
not an issue as usually the assertions are done in the main thread. If
you want to help, you can volunteer to implement the necessary
synchronization primitives in `gtest-port.h` for your platform.

View File

@ -1,14 +0,0 @@
If you're like us, you'd like to look at some Google Test sample code. The
[samples folder](../samples) has a number of well-commented samples showing how to use a
variety of Google Test features.
* [Sample #1](../samples/sample1_unittest.cc) shows the basic steps of using Google Test to test C++ functions.
* [Sample #2](../samples/sample2_unittest.cc) shows a more complex unit test for a class with multiple member functions.
* [Sample #3](../samples/sample3_unittest.cc) uses a test fixture.
* [Sample #4](../samples/sample4_unittest.cc) is another basic example of using Google Test.
* [Sample #5](../samples/sample5_unittest.cc) teaches how to reuse a test fixture in multiple test cases by deriving sub-fixtures from it.
* [Sample #6](../samples/sample6_unittest.cc) demonstrates type-parameterized tests.
* [Sample #7](../samples/sample7_unittest.cc) teaches the basics of value-parameterized tests.
* [Sample #8](../samples/sample8_unittest.cc) shows using `Combine()` in value-parameterized tests.
* [Sample #9](../samples/sample9_unittest.cc) shows use of the listener API to modify Google Test's console output and the use of its reflection API to inspect test results.
* [Sample #10](../samples/sample10_unittest.cc) shows use of the listener API to implement a primitive memory leak checker.

View File

@ -6,7 +6,7 @@ This guide will explain how to use the Google Testing Framework in your Xcode pr
Here is the quick guide for using Google Test in your Xcode project.
1. Download the source from the [website](http://code.google.com/p/googletest) using this command: `svn checkout http://googletest.googlecode.com/svn/trunk/ googletest-read-only`.
1. Download the source from the [website](https://github.com/google/googletest) using this command: `svn checkout http://googletest.googlecode.com/svn/trunk/ googletest-read-only`.
1. Open up the `gtest.xcodeproj` in the `googletest-read-only/xcode/` directory and build the gtest.framework.
1. Create a new "Shell Tool" target in your Xcode project called something like "UnitTests".
1. Add the gtest.framework to your project and add it to the "Link Binary with Libraries" build phase of "UnitTests".
@ -18,7 +18,7 @@ The following sections further explain each of the steps listed above in depth,
# Get the Source #
Currently, the gtest.framework discussed here isn't available in a tagged release of Google Test, it is only available in the trunk. As explained at the Google Test [site](http://code.google.com/p/googletest/source/checkout">svn), you can get the code from anonymous SVN with this command:
Currently, the gtest.framework discussed here isn't available in a tagged release of Google Test, it is only available in the trunk. As explained at the Google Test [site](https://github.com/google/googletest), you can get the code from anonymous SVN with this command:
```
svn checkout http://googletest.googlecode.com/svn/trunk/ googletest-read-only
@ -28,7 +28,7 @@ Alternatively, if you are working with Subversion in your own code base, you can
To use `svn:externals`, decide where you would like to have the external source reside. You might choose to put the external source inside the trunk, because you want it to be part of the branch when you make a release. However, keeping it outside the trunk in a version-tagged directory called something like `third-party/googletest/1.0.1`, is another option. Once the location is established, use `svn propedit svn:externals _directory_` to set the svn:externals property on a directory in your repository. This directory won't contain the code, but be its versioned parent directory.
The command `svn propedit` will bring up your Subversion editor, making editing the long, (potentially multi-line) property simpler. This same method can be used to check out a tagged branch, by using the appropriate URL (e.g. `http://googletest.googlecode.com/svn/tags/release-1.0.1`). Additionally, the svn:externals property allows the specification of a particular revision of the trunk with the `-r_##_` option (e.g. `externals/src/googletest -r60 http://googletest.googlecode.com/svn/trunk`).
The command `svn propedit` will bring up your Subversion editor, making editing the long, (potentially multi-line) property simpler. This same method can be used to check out a tagged branch, by using the appropriate URL (e.g. `https://github.com/google/googletest/releases/tag/release-1.0.1`). Additionally, the svn:externals property allows the specification of a particular revision of the trunk with the `-r_##_` option (e.g. `externals/src/googletest -r60 http://googletest.googlecode.com/svn/trunk`).
Here is an example of using the svn:externals properties on a trunk (read via `svn propget`) of a project. This value checks out a copy of Google Test into the `trunk/externals/src/googletest/` directory.

2520
googletest/docs/advanced.md Normal file

File diff suppressed because it is too large Load Diff

770
googletest/docs/faq.md Normal file
View File

@ -0,0 +1,770 @@
# Googletest FAQ
## Why should test case names and test names not contain underscore?
Underscore (`_`) is special, as C++ reserves the following to be used by the
compiler and the standard library:
1. any identifier that starts with an `_` followed by an upper-case letter, and
1. any identifier that contains two consecutive underscores (i.e. `__`)
*anywhere* in its name.
User code is *prohibited* from using such identifiers.
Now let's look at what this means for `TEST` and `TEST_F`.
Currently `TEST(TestCaseName, TestName)` generates a class named
`TestCaseName_TestName_Test`. What happens if `TestCaseName` or `TestName`
contains `_`?
1. If `TestCaseName` starts with an `_` followed by an upper-case letter (say,
`_Foo`), we end up with `_Foo_TestName_Test`, which is reserved and thus
invalid.
1. If `TestCaseName` ends with an `_` (say, `Foo_`), we get
`Foo__TestName_Test`, which is invalid.
1. If `TestName` starts with an `_` (say, `_Bar`), we get
`TestCaseName__Bar_Test`, which is invalid.
1. If `TestName` ends with an `_` (say, `Bar_`), we get
`TestCaseName_Bar__Test`, which is invalid.
So clearly `TestCaseName` and `TestName` cannot start or end with `_` (Actually,
`TestCaseName` can start with `_` -- as long as the `_` isn't followed by an
upper-case letter. But that's getting complicated. So for simplicity we just say
that it cannot start with `_`.).
It may seem fine for `TestCaseName` and `TestName` to contain `_` in the middle.
However, consider this:
```c++
TEST(Time, Flies_Like_An_Arrow) { ... }
TEST(Time_Flies, Like_An_Arrow) { ... }
```
Now, the two `TEST`s will both generate the same class
(`Time_Flies_Like_An_Arrow_Test`). That's not good.
So for simplicity, we just ask the users to avoid `_` in `TestCaseName` and
`TestName`. The rule is more constraining than necessary, but it's simple and
easy to remember. It also gives googletest some wiggle room in case its
implementation needs to change in the future.
If you violate the rule, there may not be immediate consequences, but your test
may (just may) break with a new compiler (or a new version of the compiler you
are using) or with a new version of googletest. Therefore it's best to follow
the rule.
## Why does googletest support `EXPECT_EQ(NULL, ptr)` and `ASSERT_EQ(NULL, ptr)` but not `EXPECT_NE(NULL, ptr)` and `ASSERT_NE(NULL, ptr)`?
First of all you can use `EXPECT_NE(nullptr, ptr)` and `ASSERT_NE(nullptr,
ptr)`. This is the preferred syntax in the style guide because nullptr does not
have the type problems that NULL does. Which is why NULL does not work.
Due to some peculiarity of C++, it requires some non-trivial template meta
programming tricks to support using `NULL` as an argument of the `EXPECT_XX()`
and `ASSERT_XX()` macros. Therefore we only do it where it's most needed
(otherwise we make the implementation of googletest harder to maintain and more
error-prone than necessary).
The `EXPECT_EQ()` macro takes the *expected* value as its first argument and the
*actual* value as the second. It's reasonable that someone wants to write
`EXPECT_EQ(NULL, some_expression)`, and this indeed was requested several times.
Therefore we implemented it.
The need for `EXPECT_NE(NULL, ptr)` isn't nearly as strong. When the assertion
fails, you already know that `ptr` must be `NULL`, so it doesn't add any
information to print `ptr` in this case. That means `EXPECT_TRUE(ptr != NULL)`
works just as well.
If we were to support `EXPECT_NE(NULL, ptr)`, for consistency we'll have to
support `EXPECT_NE(ptr, NULL)` as well, as unlike `EXPECT_EQ`, we don't have a
convention on the order of the two arguments for `EXPECT_NE`. This means using
the template meta programming tricks twice in the implementation, making it even
harder to understand and maintain. We believe the benefit doesn't justify the
cost.
Finally, with the growth of the gMock matcher library, we are encouraging people
to use the unified `EXPECT_THAT(value, matcher)` syntax more often in tests. One
significant advantage of the matcher approach is that matchers can be easily
combined to form new matchers, while the `EXPECT_NE`, etc, macros cannot be
easily combined. Therefore we want to invest more in the matchers than in the
`EXPECT_XX()` macros.
## I need to test that different implementations of an interface satisfy some common requirements. Should I use typed tests or value-parameterized tests?
For testing various implementations of the same interface, either typed tests or
value-parameterized tests can get it done. It's really up to you the user to
decide which is more convenient for you, depending on your particular case. Some
rough guidelines:
* Typed tests can be easier to write if instances of the different
implementations can be created the same way, modulo the type. For example,
if all these implementations have a public default constructor (such that
you can write `new TypeParam`), or if their factory functions have the same
form (e.g. `CreateInstance<TypeParam>()`).
* Value-parameterized tests can be easier to write if you need different code
patterns to create different implementations' instances, e.g. `new Foo` vs
`new Bar(5)`. To accommodate for the differences, you can write factory
function wrappers and pass these function pointers to the tests as their
parameters.
* When a typed test fails, the output includes the name of the type, which can
help you quickly identify which implementation is wrong. Value-parameterized
tests cannot do this, so there you'll have to look at the iteration number
to know which implementation the failure is from, which is less direct.
* If you make a mistake writing a typed test, the compiler errors can be
harder to digest, as the code is templatized.
* When using typed tests, you need to make sure you are testing against the
interface type, not the concrete types (in other words, you want to make
sure `implicit_cast<MyInterface*>(my_concrete_impl)` works, not just that
`my_concrete_impl` works). It's less likely to make mistakes in this area
when using value-parameterized tests.
I hope I didn't confuse you more. :-) If you don't mind, I'd suggest you to give
both approaches a try. Practice is a much better way to grasp the subtle
differences between the two tools. Once you have some concrete experience, you
can much more easily decide which one to use the next time.
## My death tests became very slow - what happened?
In August 2008 we had to switch the default death test style from `fast` to
`threadsafe`, as the former is no longer safe now that threaded logging is the
default. This caused many death tests to slow down. Unfortunately this change
was necessary.
Please read [Fixing Failing Death Tests](death_test_styles.md) for what you can
do.
## I got some run-time errors about invalid proto descriptors when using `ProtocolMessageEquals`. Help!
**Note:** `ProtocolMessageEquals` and `ProtocolMessageEquiv` are *deprecated*
now. Please use `EqualsProto`, etc instead.
`ProtocolMessageEquals` and `ProtocolMessageEquiv` were redefined recently and
are now less tolerant on invalid protocol buffer definitions. In particular, if
you have a `foo.proto` that doesn't fully qualify the type of a protocol message
it references (e.g. `message<Bar>` where it should be `message<blah.Bar>`), you
will now get run-time errors like:
```
... descriptor.cc:...] Invalid proto descriptor for file "path/to/foo.proto":
... descriptor.cc:...] blah.MyMessage.my_field: ".Bar" is not defined.
```
If you see this, your `.proto` file is broken and needs to be fixed by making
the types fully qualified. The new definition of `ProtocolMessageEquals` and
`ProtocolMessageEquiv` just happen to reveal your bug.
## My death test modifies some state, but the change seems lost after the death test finishes. Why?
Death tests (`EXPECT_DEATH`, etc) are executed in a sub-process s.t. the
expected crash won't kill the test program (i.e. the parent process). As a
result, any in-memory side effects they incur are observable in their respective
sub-processes, but not in the parent process. You can think of them as running
in a parallel universe, more or less.
In particular, if you use [gMock](../../googlemock) and the death test statement
invokes some mock methods, the parent process will think the calls have never
occurred. Therefore, you may want to move your `EXPECT_CALL` statements inside
the `EXPECT_DEATH` macro.
## EXPECT_EQ(htonl(blah), blah_blah) generates weird compiler errors in opt mode. Is this a googletest bug?
Actually, the bug is in `htonl()`.
According to `'man htonl'`, `htonl()` is a *function*, which means it's valid to
use `htonl` as a function pointer. However, in opt mode `htonl()` is defined as
a *macro*, which breaks this usage.
Worse, the macro definition of `htonl()` uses a `gcc` extension and is *not*
standard C++. That hacky implementation has some ad hoc limitations. In
particular, it prevents you from writing `Foo<sizeof(htonl(x))>()`, where `Foo`
is a template that has an integral argument.
The implementation of `EXPECT_EQ(a, b)` uses `sizeof(... a ...)` inside a
template argument, and thus doesn't compile in opt mode when `a` contains a call
to `htonl()`. It is difficult to make `EXPECT_EQ` bypass the `htonl()` bug, as
the solution must work with different compilers on various platforms.
`htonl()` has some other problems as described in `//util/endian/endian.h`,
which defines `ghtonl()` to replace it. `ghtonl()` does the same thing `htonl()`
does, only without its problems. We suggest you to use `ghtonl()` instead of
`htonl()`, both in your tests and production code.
`//util/endian/endian.h` also defines `ghtons()`, which solves similar problems
in `htons()`.
Don't forget to add `//util/endian` to the list of dependencies in the `BUILD`
file wherever `ghtonl()` and `ghtons()` are used. The library consists of a
single header file and will not bloat your binary.
## The compiler complains about "undefined references" to some static const member variables, but I did define them in the class body. What's wrong?
If your class has a static data member:
```c++
// foo.h
class Foo {
...
static const int kBar = 100;
};
```
You also need to define it *outside* of the class body in `foo.cc`:
```c++
const int Foo::kBar; // No initializer here.
```
Otherwise your code is **invalid C++**, and may break in unexpected ways. In
particular, using it in googletest comparison assertions (`EXPECT_EQ`, etc) will
generate an "undefined reference" linker error. The fact that "it used to work"
doesn't mean it's valid. It just means that you were lucky. :-)
## Can I derive a test fixture from another?
Yes.
Each test fixture has a corresponding and same named test case. This means only
one test case can use a particular fixture. Sometimes, however, multiple test
cases may want to use the same or slightly different fixtures. For example, you
may want to make sure that all of a GUI library's test cases don't leak
important system resources like fonts and brushes.
In googletest, you share a fixture among test cases by putting the shared logic
in a base test fixture, then deriving from that base a separate fixture for each
test case that wants to use this common logic. You then use `TEST_F()` to write
tests using each derived fixture.
Typically, your code looks like this:
```c++
// Defines a base test fixture.
class BaseTest : public ::testing::Test {
protected:
...
};
// Derives a fixture FooTest from BaseTest.
class FooTest : public BaseTest {
protected:
void SetUp() override {
BaseTest::SetUp(); // Sets up the base fixture first.
... additional set-up work ...
}
void TearDown() override {
... clean-up work for FooTest ...
BaseTest::TearDown(); // Remember to tear down the base fixture
// after cleaning up FooTest!
}
... functions and variables for FooTest ...
};
// Tests that use the fixture FooTest.
TEST_F(FooTest, Bar) { ... }
TEST_F(FooTest, Baz) { ... }
... additional fixtures derived from BaseTest ...
```
If necessary, you can continue to derive test fixtures from a derived fixture.
googletest has no limit on how deep the hierarchy can be.
For a complete example using derived test fixtures, see [googletest
sample](https://github.com/google/googletest/blob/master/googletest/samples/sample5_unittest.cc)
## My compiler complains "void value not ignored as it ought to be." What does this mean?
You're probably using an `ASSERT_*()` in a function that doesn't return `void`.
`ASSERT_*()` can only be used in `void` functions, due to exceptions being
disabled by our build system. Please see more details
[here](advanced.md#assertion-placement).
## My death test hangs (or seg-faults). How do I fix it?
In googletest, death tests are run in a child process and the way they work is
delicate. To write death tests you really need to understand how they work.
Please make sure you have read [this](advanced.md#how-it-works).
In particular, death tests don't like having multiple threads in the parent
process. So the first thing you can try is to eliminate creating threads outside
of `EXPECT_DEATH()`. For example, you may want to use [mocks](../../googlemock)
or fake objects instead of real ones in your tests.
Sometimes this is impossible as some library you must use may be creating
threads before `main()` is even reached. In this case, you can try to minimize
the chance of conflicts by either moving as many activities as possible inside
`EXPECT_DEATH()` (in the extreme case, you want to move everything inside), or
leaving as few things as possible in it. Also, you can try to set the death test
style to `"threadsafe"`, which is safer but slower, and see if it helps.
If you go with thread-safe death tests, remember that they rerun the test
program from the beginning in the child process. Therefore make sure your
program can run side-by-side with itself and is deterministic.
In the end, this boils down to good concurrent programming. You have to make
sure that there is no race conditions or dead locks in your program. No silver
bullet - sorry!
## Should I use the constructor/destructor of the test fixture or SetUp()/TearDown()?
The first thing to remember is that googletest does **not** reuse the same test
fixture object across multiple tests. For each `TEST_F`, googletest will create
a **fresh** test fixture object, immediately call `SetUp()`, run the test body,
call `TearDown()`, and then delete the test fixture object.
When you need to write per-test set-up and tear-down logic, you have the choice
between using the test fixture constructor/destructor or `SetUp()/TearDown()`.
The former is usually preferred, as it has the following benefits:
* By initializing a member variable in the constructor, we have the option to
make it `const`, which helps prevent accidental changes to its value and
makes the tests more obviously correct.
* In case we need to subclass the test fixture class, the subclass'
constructor is guaranteed to call the base class' constructor *first*, and
the subclass' destructor is guaranteed to call the base class' destructor
*afterward*. With `SetUp()/TearDown()`, a subclass may make the mistake of
forgetting to call the base class' `SetUp()/TearDown()` or call them at the
wrong time.
You may still want to use `SetUp()/TearDown()` in the following rare cases:
* In the body of a constructor (or destructor), it's not possible to use the
`ASSERT_xx` macros. Therefore, if the set-up operation could cause a fatal
test failure that should prevent the test from running, it's necessary to
use a `CHECK` macro or to use `SetUp()` instead of a constructor.
* If the tear-down operation could throw an exception, you must use
`TearDown()` as opposed to the destructor, as throwing in a destructor leads
to undefined behavior and usually will kill your program right away. Note
that many standard libraries (like STL) may throw when exceptions are
enabled in the compiler. Therefore you should prefer `TearDown()` if you
want to write portable tests that work with or without exceptions.
* The googletest team is considering making the assertion macros throw on
platforms where exceptions are enabled (e.g. Windows, Mac OS, and Linux
client-side), which will eliminate the need for the user to propagate
failures from a subroutine to its caller. Therefore, you shouldn't use
googletest assertions in a destructor if your code could run on such a
platform.
* In a constructor or destructor, you cannot make a virtual function call on
this object. (You can call a method declared as virtual, but it will be
statically bound.) Therefore, if you need to call a method that will be
overridden in a derived class, you have to use `SetUp()/TearDown()`.
## The compiler complains "no matching function to call" when I use ASSERT_PRED*. How do I fix it?
If the predicate function you use in `ASSERT_PRED*` or `EXPECT_PRED*` is
overloaded or a template, the compiler will have trouble figuring out which
overloaded version it should use. `ASSERT_PRED_FORMAT*` and
`EXPECT_PRED_FORMAT*` don't have this problem.
If you see this error, you might want to switch to
`(ASSERT|EXPECT)_PRED_FORMAT*`, which will also give you a better failure
message. If, however, that is not an option, you can resolve the problem by
explicitly telling the compiler which version to pick.
For example, suppose you have
```c++
bool IsPositive(int n) {
return n > 0;
}
bool IsPositive(double x) {
return x > 0;
}
```
you will get a compiler error if you write
```c++
EXPECT_PRED1(IsPositive, 5);
```
However, this will work:
```c++
EXPECT_PRED1(static_cast<bool (*)(int)>(IsPositive), 5);
```
(The stuff inside the angled brackets for the `static_cast` operator is the type
of the function pointer for the `int`-version of `IsPositive()`.)
As another example, when you have a template function
```c++
template <typename T>
bool IsNegative(T x) {
return x < 0;
}
```
you can use it in a predicate assertion like this:
```c++
ASSERT_PRED1(IsNegative<int>, -5);
```
Things are more interesting if your template has more than one parameters. The
following won't compile:
```c++
ASSERT_PRED2(GreaterThan<int, int>, 5, 0);
```
as the C++ pre-processor thinks you are giving `ASSERT_PRED2` 4 arguments, which
is one more than expected. The workaround is to wrap the predicate function in
parentheses:
```c++
ASSERT_PRED2((GreaterThan<int, int>), 5, 0);
```
## My compiler complains about "ignoring return value" when I call RUN_ALL_TESTS(). Why?
Some people had been ignoring the return value of `RUN_ALL_TESTS()`. That is,
instead of
```c++
return RUN_ALL_TESTS();
```
they write
```c++
RUN_ALL_TESTS();
```
This is **wrong and dangerous**. The testing services needs to see the return
value of `RUN_ALL_TESTS()` in order to determine if a test has passed. If your
`main()` function ignores it, your test will be considered successful even if it
has a googletest assertion failure. Very bad.
We have decided to fix this (thanks to Michael Chastain for the idea). Now, your
code will no longer be able to ignore `RUN_ALL_TESTS()` when compiled with
`gcc`. If you do so, you'll get a compiler error.
If you see the compiler complaining about you ignoring the return value of
`RUN_ALL_TESTS()`, the fix is simple: just make sure its value is used as the
return value of `main()`.
But how could we introduce a change that breaks existing tests? Well, in this
case, the code was already broken in the first place, so we didn't break it. :-)
## My compiler complains that a constructor (or destructor) cannot return a value. What's going on?
Due to a peculiarity of C++, in order to support the syntax for streaming
messages to an `ASSERT_*`, e.g.
```c++
ASSERT_EQ(1, Foo()) << "blah blah" << foo;
```
we had to give up using `ASSERT*` and `FAIL*` (but not `EXPECT*` and
`ADD_FAILURE*`) in constructors and destructors. The workaround is to move the
content of your constructor/destructor to a private void member function, or
switch to `EXPECT_*()` if that works. This
[section](advanced.md#assertion-placement) in the user's guide explains it.
## My SetUp() function is not called. Why?
C++ is case-sensitive. Did you spell it as `Setup()`?
Similarly, sometimes people spell `SetUpTestCase()` as `SetupTestCase()` and
wonder why it's never called.
## How do I jump to the line of a failure in Emacs directly?
googletest's failure message format is understood by Emacs and many other IDEs,
like acme and XCode. If a googletest message is in a compilation buffer in
Emacs, then it's clickable.
## I have several test cases which share the same test fixture logic, do I have to define a new test fixture class for each of them? This seems pretty tedious.
You don't have to. Instead of
```c++
class FooTest : public BaseTest {};
TEST_F(FooTest, Abc) { ... }
TEST_F(FooTest, Def) { ... }
class BarTest : public BaseTest {};
TEST_F(BarTest, Abc) { ... }
TEST_F(BarTest, Def) { ... }
```
you can simply `typedef` the test fixtures:
```c++
typedef BaseTest FooTest;
TEST_F(FooTest, Abc) { ... }
TEST_F(FooTest, Def) { ... }
typedef BaseTest BarTest;
TEST_F(BarTest, Abc) { ... }
TEST_F(BarTest, Def) { ... }
```
## googletest output is buried in a whole bunch of LOG messages. What do I do?
The googletest output is meant to be a concise and human-friendly report. If
your test generates textual output itself, it will mix with the googletest
output, making it hard to read. However, there is an easy solution to this
problem.
Since `LOG` messages go to stderr, we decided to let googletest output go to
stdout. This way, you can easily separate the two using redirection. For
example:
```shell
$ ./my_test > gtest_output.txt
```
## Why should I prefer test fixtures over global variables?
There are several good reasons:
1. It's likely your test needs to change the states of its global variables.
This makes it difficult to keep side effects from escaping one test and
contaminating others, making debugging difficult. By using fixtures, each
test has a fresh set of variables that's different (but with the same
names). Thus, tests are kept independent of each other.
1. Global variables pollute the global namespace.
1. Test fixtures can be reused via subclassing, which cannot be done easily
with global variables. This is useful if many test cases have something in
common.
## What can the statement argument in ASSERT_DEATH() be?
`ASSERT_DEATH(*statement*, *regex*)` (or any death assertion macro) can be used
wherever `*statement*` is valid. So basically `*statement*` can be any C++
statement that makes sense in the current context. In particular, it can
reference global and/or local variables, and can be:
* a simple function call (often the case),
* a complex expression, or
* a compound statement.
Some examples are shown here:
```c++
// A death test can be a simple function call.
TEST(MyDeathTest, FunctionCall) {
ASSERT_DEATH(Xyz(5), "Xyz failed");
}
// Or a complex expression that references variables and functions.
TEST(MyDeathTest, ComplexExpression) {
const bool c = Condition();
ASSERT_DEATH((c ? Func1(0) : object2.Method("test")),
"(Func1|Method) failed");
}
// Death assertions can be used any where in a function. In
// particular, they can be inside a loop.
TEST(MyDeathTest, InsideLoop) {
// Verifies that Foo(0), Foo(1), ..., and Foo(4) all die.
for (int i = 0; i < 5; i++) {
EXPECT_DEATH_M(Foo(i), "Foo has \\d+ errors",
::testing::Message() << "where i is " << i);
}
}
// A death assertion can contain a compound statement.
TEST(MyDeathTest, CompoundStatement) {
// Verifies that at lease one of Bar(0), Bar(1), ..., and
// Bar(4) dies.
ASSERT_DEATH({
for (int i = 0; i < 5; i++) {
Bar(i);
}
},
"Bar has \\d+ errors");
}
```
gtest-death-test_test.cc contains more examples if you are interested.
## I have a fixture class `FooTest`, but `TEST_F(FooTest, Bar)` gives me error ``"no matching function for call to `FooTest::FooTest()'"``. Why?
Googletest needs to be able to create objects of your test fixture class, so it
must have a default constructor. Normally the compiler will define one for you.
However, there are cases where you have to define your own:
* If you explicitly declare a non-default constructor for class `FooTest`
(`DISALLOW_EVIL_CONSTRUCTORS()` does this), then you need to define a
default constructor, even if it would be empty.
* If `FooTest` has a const non-static data member, then you have to define the
default constructor *and* initialize the const member in the initializer
list of the constructor. (Early versions of `gcc` doesn't force you to
initialize the const member. It's a bug that has been fixed in `gcc 4`.)
## Why does ASSERT_DEATH complain about previous threads that were already joined?
With the Linux pthread library, there is no turning back once you cross the line
from single thread to multiple threads. The first time you create a thread, a
manager thread is created in addition, so you get 3, not 2, threads. Later when
the thread you create joins the main thread, the thread count decrements by 1,
but the manager thread will never be killed, so you still have 2 threads, which
means you cannot safely run a death test.
The new NPTL thread library doesn't suffer from this problem, as it doesn't
create a manager thread. However, if you don't control which machine your test
runs on, you shouldn't depend on this.
## Why does googletest require the entire test case, instead of individual tests, to be named *DeathTest when it uses ASSERT_DEATH?
googletest does not interleave tests from different test cases. That is, it runs
all tests in one test case first, and then runs all tests in the next test case,
and so on. googletest does this because it needs to set up a test case before
the first test in it is run, and tear it down afterwords. Splitting up the test
case would require multiple set-up and tear-down processes, which is inefficient
and makes the semantics unclean.
If we were to determine the order of tests based on test name instead of test
case name, then we would have a problem with the following situation:
```c++
TEST_F(FooTest, AbcDeathTest) { ... }
TEST_F(FooTest, Uvw) { ... }
TEST_F(BarTest, DefDeathTest) { ... }
TEST_F(BarTest, Xyz) { ... }
```
Since `FooTest.AbcDeathTest` needs to run before `BarTest.Xyz`, and we don't
interleave tests from different test cases, we need to run all tests in the
`FooTest` case before running any test in the `BarTest` case. This contradicts
with the requirement to run `BarTest.DefDeathTest` before `FooTest.Uvw`.
## But I don't like calling my entire test case \*DeathTest when it contains both death tests and non-death tests. What do I do?
You don't have to, but if you like, you may split up the test case into
`FooTest` and `FooDeathTest`, where the names make it clear that they are
related:
```c++
class FooTest : public ::testing::Test { ... };
TEST_F(FooTest, Abc) { ... }
TEST_F(FooTest, Def) { ... }
using FooDeathTest = FooTest;
TEST_F(FooDeathTest, Uvw) { ... EXPECT_DEATH(...) ... }
TEST_F(FooDeathTest, Xyz) { ... ASSERT_DEATH(...) ... }
```
## googletest prints the LOG messages in a death test's child process only when the test fails. How can I see the LOG messages when the death test succeeds?
Printing the LOG messages generated by the statement inside `EXPECT_DEATH()`
makes it harder to search for real problems in the parent's log. Therefore,
googletest only prints them when the death test has failed.
If you really need to see such LOG messages, a workaround is to temporarily
break the death test (e.g. by changing the regex pattern it is expected to
match). Admittedly, this is a hack. We'll consider a more permanent solution
after the fork-and-exec-style death tests are implemented.
## The compiler complains about "no match for 'operator<<'" when I use an assertion. What gives?
If you use a user-defined type `FooType` in an assertion, you must make sure
there is an `std::ostream& operator<<(std::ostream&, const FooType&)` function
defined such that we can print a value of `FooType`.
In addition, if `FooType` is declared in a name space, the `<<` operator also
needs to be defined in the *same* name space. See go/totw/49 for details.
## How do I suppress the memory leak messages on Windows?
Since the statically initialized googletest singleton requires allocations on
the heap, the Visual C++ memory leak detector will report memory leaks at the
end of the program run. The easiest way to avoid this is to use the
`_CrtMemCheckpoint` and `_CrtMemDumpAllObjectsSince` calls to not report any
statically initialized heap objects. See MSDN for more details and additional
heap check/debug routines.
## How can my code detect if it is running in a test?
If you write code that sniffs whether it's running in a test and does different
things accordingly, you are leaking test-only logic into production code and
there is no easy way to ensure that the test-only code paths aren't run by
mistake in production. Such cleverness also leads to
[Heisenbugs](https://en.wikipedia.org/wiki/Heisenbug). Therefore we strongly
advise against the practice, and googletest doesn't provide a way to do it.
In general, the recommended way to cause the code to behave differently under
test is [Dependency Injection](https://en.wikipedia.org/wiki/Dependency_injection). You can inject
different functionality from the test and from the production code. Since your
production code doesn't link in the for-test logic at all (the
[`testonly`](https://docs.bazel.build/versions/master/be/common-definitions.html#common.testonly)
attribute for BUILD targets helps to ensure that), there is no danger in
accidentally running it.
However, if you *really*, *really*, *really* have no choice, and if you follow
the rule of ending your test program names with `_test`, you can use the
*horrible* hack of sniffing your executable name (`argv[0]` in `main()`) to know
whether the code is under test.
## How do I temporarily disable a test?
If you have a broken test that you cannot fix right away, you can add the
DISABLED_ prefix to its name. This will exclude it from execution. This is
better than commenting out the code or using #if 0, as disabled tests are still
compiled (and thus won't rot).
To include disabled tests in test execution, just invoke the test program with
the --gtest_also_run_disabled_tests flag.
## Is it OK if I have two separate `TEST(Foo, Bar)` test methods defined in different namespaces?
Yes.
The rule is **all test methods in the same test case must use the same fixture
class.** This means that the following is **allowed** because both tests use the
same fixture class (`::testing::Test`).
```c++
namespace foo {
TEST(CoolTest, DoSomething) {
SUCCEED();
}
} // namespace foo
namespace bar {
TEST(CoolTest, DoSomething) {
SUCCEED();
}
} // namespace bar
```
However, the following code is **not allowed** and will produce a runtime error
from googletest because the test methods are using different test fixture
classes with the same test case name.
```c++
namespace foo {
class CoolTest : public ::testing::Test {}; // Fixture foo::CoolTest
TEST_F(CoolTest, DoSomething) {
SUCCEED();
}
} // namespace foo
namespace bar {
class CoolTest : public ::testing::Test {}; // Fixture: bar::CoolTest
TEST_F(CoolTest, DoSomething) {
SUCCEED();
}
} // namespace bar
```

569
googletest/docs/primer.md Normal file
View File

@ -0,0 +1,569 @@
# Googletest Primer
## Introduction: Why googletest?
*googletest* helps you write better C++ tests.
googletest is a testing framework developed by the Testing
Technology team with Google's specific
requirements and constraints in mind. No matter whether you work on Linux,
Windows, or a Mac, if you write C++ code, googletest can help you. And it
supports *any* kind of tests, not just unit tests.
So what makes a good test, and how does googletest fit in? We believe:
1. Tests should be *independent* and *repeatable*. It's a pain to debug a test
that succeeds or fails as a result of other tests. googletest isolates the
tests by running each of them on a different object. When a test fails,
googletest allows you to run it in isolation for quick debugging.
1. Tests should be well *organized* and reflect the structure of the tested
code. googletest groups related tests into test cases that can share data
and subroutines. This common pattern is easy to recognize and makes tests
easy to maintain. Such consistency is especially helpful when people switch
projects and start to work on a new code base.
1. Tests should be *portable* and *reusable*. Google has a lot of code that is
platform-neutral, its tests should also be platform-neutral. googletest
works on different OSes, with different compilers (gcc, icc, and MSVC), with
or without exceptions, so googletest tests can easily work with a variety of
configurations.
1. When tests fail, they should provide as much *information* about the problem
as possible. googletest doesn't stop at the first test failure. Instead, it
only stops the current test and continues with the next. You can also set up
tests that report non-fatal failures after which the current test continues.
Thus, you can detect and fix multiple bugs in a single run-edit-compile
cycle.
1. The testing framework should liberate test writers from housekeeping chores
and let them focus on the test *content*. googletest automatically keeps
track of all tests defined, and doesn't require the user to enumerate them
in order to run them.
1. Tests should be *fast*. With googletest, you can reuse shared resources
across tests and pay for the set-up/tear-down only once, without making
tests depend on each other.
Since googletest is based on the popular xUnit architecture, you'll feel right
at home if you've used JUnit or PyUnit before. If not, it will take you about 10
minutes to learn the basics and get started. So let's go!
## Beware of the nomenclature
_Note:_ There might be some confusion of idea due to different
definitions of the terms _Test_, _Test Case_ and _Test Suite_, so beware
of misunderstanding these.
Historically, googletest started to use the term _Test Case_ for grouping
related tests, whereas current publications including the International Software
Testing Qualifications Board ([ISTQB](http://www.istqb.org/)) and various
textbooks on Software Quality use the term _[Test
Suite](http://glossary.istqb.org/search/test%20suite)_ for this.
The related term _Test_, as it is used in the googletest, is corresponding to
the term _[Test Case](http://glossary.istqb.org/search/test%20case)_ of ISTQB
and others.
The term _Test_ is commonly of broad enough sense, including ISTQB's
definition of _Test Case_, so it's not much of a problem here. But the
term _Test Case_ as used in Google Test is of contradictory sense and thus confusing.
Unfortunately replacing the term _Test Case_ by _Test Suite_ throughout the
googletest is not easy without breaking dependent projects, as `TestCase` is
part of the public API at various places.
So for the time being, please be aware of the different definitions of
the terms:
Meaning | googletest Term | [ISTQB](http://www.istqb.org/) Term
:----------------------------------------------------------------------------------- | :--------------------------------------------------------------------------------------------------------- | :----------------------------------
Exercise a particular program path with specific input values and verify the results | [TEST()](#simple-tests) | [Test Case](http://glossary.istqb.org/search/test%20case)
A set of several tests related to one component | [TestCase](#basic-concepts) | [TestSuite](http://glossary.istqb.org/search/test%20suite)
## Basic Concepts
When using googletest, you start by writing *assertions*, which are statements
that check whether a condition is true. An assertion's result can be *success*,
*nonfatal failure*, or *fatal failure*. If a fatal failure occurs, it aborts the
current function; otherwise the program continues normally.
*Tests* use assertions to verify the tested code's behavior. If a test crashes
or has a failed assertion, then it *fails*; otherwise it *succeeds*.
A *test case* contains one or many tests. You should group your tests into test
cases that reflect the structure of the tested code. When multiple tests in a
test case need to share common objects and subroutines, you can put them into a
*test fixture* class.
A *test program* can contain multiple test cases.
We'll now explain how to write a test program, starting at the individual
assertion level and building up to tests and test cases.
## Assertions
googletest assertions are macros that resemble function calls. You test a class
or function by making assertions about its behavior. When an assertion fails,
googletest prints the assertion's source file and line number location, along
with a failure message. You may also supply a custom failure message which will
be appended to googletest's message.
The assertions come in pairs that test the same thing but have different effects
on the current function. `ASSERT_*` versions generate fatal failures when they
fail, and **abort the current function**. `EXPECT_*` versions generate nonfatal
failures, which don't abort the current function. Usually `EXPECT_*` are
preferred, as they allow more than one failure to be reported in a test.
However, you should use `ASSERT_*` if it doesn't make sense to continue when the
assertion in question fails.
Since a failed `ASSERT_*` returns from the current function immediately,
possibly skipping clean-up code that comes after it, it may cause a space leak.
Depending on the nature of the leak, it may or may not be worth fixing - so keep
this in mind if you get a heap checker error in addition to assertion errors.
To provide a custom failure message, simply stream it into the macro using the
`<<` operator, or a sequence of such operators. An example:
```c++
ASSERT_EQ(x.size(), y.size()) << "Vectors x and y are of unequal length";
for (int i = 0; i < x.size(); ++i) {
EXPECT_EQ(x[i], y[i]) << "Vectors x and y differ at index " << i;
}
```
Anything that can be streamed to an `ostream` can be streamed to an assertion
macro--in particular, C strings and `string` objects. If a wide string
(`wchar_t*`, `TCHAR*` in `UNICODE` mode on Windows, or `std::wstring`) is
streamed to an assertion, it will be translated to UTF-8 when printed.
### Basic Assertions
These assertions do basic true/false condition testing.
Fatal assertion | Nonfatal assertion | Verifies
-------------------------- | -------------------------- | --------------------
`ASSERT_TRUE(condition);` | `EXPECT_TRUE(condition);` | `condition` is true
`ASSERT_FALSE(condition);` | `EXPECT_FALSE(condition);` | `condition` is false
Remember, when they fail, `ASSERT_*` yields a fatal failure and returns from the
current function, while `EXPECT_*` yields a nonfatal failure, allowing the
function to continue running. In either case, an assertion failure means its
containing test fails.
**Availability**: Linux, Windows, Mac.
### Binary Comparison
This section describes assertions that compare two values.
Fatal assertion | Nonfatal assertion | Verifies
------------------------ | ------------------------ | --------------
`ASSERT_EQ(val1, val2);` | `EXPECT_EQ(val1, val2);` | `val1 == val2`
`ASSERT_NE(val1, val2);` | `EXPECT_NE(val1, val2);` | `val1 != val2`
`ASSERT_LT(val1, val2);` | `EXPECT_LT(val1, val2);` | `val1 < val2`
`ASSERT_LE(val1, val2);` | `EXPECT_LE(val1, val2);` | `val1 <= val2`
`ASSERT_GT(val1, val2);` | `EXPECT_GT(val1, val2);` | `val1 > val2`
`ASSERT_GE(val1, val2);` | `EXPECT_GE(val1, val2);` | `val1 >= val2`
Value arguments must be comparable by the assertion's comparison operator or
you'll get a compiler error. We used to require the arguments to support the
`<<` operator for streaming to an `ostream`, but it's no longer necessary. If
`<<` is supported, it will be called to print the arguments when the assertion
fails; otherwise googletest will attempt to print them in the best way it can.
For more details and how to customize the printing of the arguments, see
gMock [recipe](../../googlemock/docs/CookBook.md#teaching-google-mock-how-to-print-your-values).).
These assertions can work with a user-defined type, but only if you define the
corresponding comparison operator (e.g. `==`, `<`, etc). Since this is
discouraged by the Google [C++ Style
Guide](https://google.github.io/styleguide/cppguide.html#Operator_Overloading),
you may need to use `ASSERT_TRUE()` or `EXPECT_TRUE()` to assert the equality of
two objects of a user-defined type.
However, when possible, `ASSERT_EQ(actual, expected)` is preferred to
`ASSERT_TRUE(actual == expected)`, since it tells you `actual` and `expected`'s
values on failure.
Arguments are always evaluated exactly once. Therefore, it's OK for the
arguments to have side effects. However, as with any ordinary C/C++ function,
the arguments' evaluation order is undefined (i.e. the compiler is free to
choose any order) and your code should not depend on any particular argument
evaluation order.
`ASSERT_EQ()` does pointer equality on pointers. If used on two C strings, it
tests if they are in the same memory location, not if they have the same value.
Therefore, if you want to compare C strings (e.g. `const char*`) by value, use
`ASSERT_STREQ()`, which will be described later on. In particular, to assert
that a C string is `NULL`, use `ASSERT_STREQ(c_string, NULL)`. Consider use
`ASSERT_EQ(c_string, nullptr)` if c++11 is supported. To compare two `string`
objects, you should use `ASSERT_EQ`.
When doing pointer comparisons use `*_EQ(ptr, nullptr)` and `*_NE(ptr, nullptr)`
instead of `*_EQ(ptr, NULL)` and `*_NE(ptr, NULL)`. This is because `nullptr` is
typed while `NULL` is not. See [FAQ](faq.md#why-does-google-test-support-expect_eqnull-ptr-and-assert_eqnull-ptr-but-not-expect_nenull-ptr-and-assert_nenull-ptr)
for more details.
If you're working with floating point numbers, you may want to use the floating
point variations of some of these macros in order to avoid problems caused by
rounding. See [Advanced googletest Topics](advanced.md) for details.
Macros in this section work with both narrow and wide string objects (`string`
and `wstring`).
**Availability**: Linux, Windows, Mac.
**Historical note**: Before February 2016 `*_EQ` had a convention of calling it
as `ASSERT_EQ(expected, actual)`, so lots of existing code uses this order. Now
`*_EQ` treats both parameters in the same way.
### String Comparison
The assertions in this group compare two **C strings**. If you want to compare
two `string` objects, use `EXPECT_EQ`, `EXPECT_NE`, and etc instead.
| Fatal assertion | Nonfatal assertion | Verifies |
| ------------------------------- | ------------------------------- | -------------------------------------------------------- |
| `ASSERT_STREQ(str1, str2);` | `EXPECT_STREQ(str1, str2);` | the two C strings have the same content |
| `ASSERT_STRNE(str1, str2);` | `EXPECT_STRNE(str1, str2);` | the two C strings have different contents |
| `ASSERT_STRCASEEQ(str1, str2);` | `EXPECT_STRCASEEQ(str1, str2);` | the two C strings have the same content, ignoring case |
| `ASSERT_STRCASENE(str1, str2);` | `EXPECT_STRCASENE(str1, str2);` | the two C strings have different contents, ignoring case |
Note that "CASE" in an assertion name means that case is ignored. A `NULL`
pointer and an empty string are considered *different*.
`*STREQ*` and `*STRNE*` also accept wide C strings (`wchar_t*`). If a comparison
of two wide strings fails, their values will be printed as UTF-8 narrow strings.
**Availability**: Linux, Windows, Mac.
**See also**: For more string comparison tricks (substring, prefix, suffix, and
regular expression matching, for example), see
[this](https://github.com/google/googletest/blob/master/googletest/docs/advanced.md)
in the Advanced googletest Guide.
## Simple Tests
To create a test:
1. Use the `TEST()` macro to define and name a test function, These are
ordinary C++ functions that don't return a value.
1. In this function, along with any valid C++ statements you want to include,
use the various googletest assertions to check values.
1. The test's result is determined by the assertions; if any assertion in the
test fails (either fatally or non-fatally), or if the test crashes, the
entire test fails. Otherwise, it succeeds.
```c++
TEST(TestCaseName, TestName) {
... test body ...
}
```
`TEST()` arguments go from general to specific. The *first* argument is the name
of the test case, and the *second* argument is the test's name within the test
case. Both names must be valid C++ identifiers, and they should not contain
underscore (`_`). A test's *full name* consists of its containing test case and
its individual name. Tests from different test cases can have the same
individual name.
For example, let's take a simple integer function:
```c++
int Factorial(int n); // Returns the factorial of n
```
A test case for this function might look like:
```c++
// Tests factorial of 0.
TEST(FactorialTest, HandlesZeroInput) {
EXPECT_EQ(Factorial(0), 1);
}
// Tests factorial of positive numbers.
TEST(FactorialTest, HandlesPositiveInput) {
EXPECT_EQ(Factorial(1), 1);
EXPECT_EQ(Factorial(2), 2);
EXPECT_EQ(Factorial(3), 6);
EXPECT_EQ(Factorial(8), 40320);
}
```
googletest groups the test results by test cases, so logically-related tests
should be in the same test case; in other words, the first argument to their
`TEST()` should be the same. In the above example, we have two tests,
`HandlesZeroInput` and `HandlesPositiveInput`, that belong to the same test case
`FactorialTest`.
When naming your test cases and tests, you should follow the same convention as
for [naming functions and
classes](https://google.github.io/styleguide/cppguide.html#Function_Names).
**Availability**: Linux, Windows, Mac.
## Test Fixtures: Using the Same Data Configuration for Multiple Tests
If you find yourself writing two or more tests that operate on similar data, you
can use a *test fixture*. It allows you to reuse the same configuration of
objects for several different tests.
To create a fixture:
1. Derive a class from `::testing::Test` . Start its body with `protected:` as
we'll want to access fixture members from sub-classes.
1. Inside the class, declare any objects you plan to use.
1. If necessary, write a default constructor or `SetUp()` function to prepare
the objects for each test. A common mistake is to spell `SetUp()` as
**`Setup()`** with a small `u` - Use `override` in C++11 to make sure you
spelled it correctly
1. If necessary, write a destructor or `TearDown()` function to release any
resources you allocated in `SetUp()` . To learn when you should use the
constructor/destructor and when you should use `SetUp()/TearDown()`, read
this [FAQ](faq.md#should-i-use-the-constructordestructor-of-the-test-fixture-or-the-set-uptear-down-function) entry.
1. If needed, define subroutines for your tests to share.
When using a fixture, use `TEST_F()` instead of `TEST()` as it allows you to
access objects and subroutines in the test fixture:
```c++
TEST_F(TestCaseName, TestName) {
... test body ...
}
```
Like `TEST()`, the first argument is the test case name, but for `TEST_F()` this
must be the name of the test fixture class. You've probably guessed: `_F` is for
fixture.
Unfortunately, the C++ macro system does not allow us to create a single macro
that can handle both types of tests. Using the wrong macro causes a compiler
error.
Also, you must first define a test fixture class before using it in a
`TEST_F()`, or you'll get the compiler error "`virtual outside class
declaration`".
For each test defined with `TEST_F()` , googletest will create a *fresh* test
fixture at runtime, immediately initialize it via `SetUp()` , run the test,
clean up by calling `TearDown()` , and then delete the test fixture. Note that
different tests in the same test case have different test fixture objects, and
googletest always deletes a test fixture before it creates the next one.
googletest does **not** reuse the same test fixture for multiple tests. Any
changes one test makes to the fixture do not affect other tests.
As an example, let's write tests for a FIFO queue class named `Queue`, which has
the following interface:
```c++
template <typename E> // E is the element type.
class Queue {
public:
Queue();
void Enqueue(const E& element);
E* Dequeue(); // Returns NULL if the queue is empty.
size_t size() const;
...
};
```
First, define a fixture class. By convention, you should give it the name
`FooTest` where `Foo` is the class being tested.
```c++
class QueueTest : public ::testing::Test {
protected:
void SetUp() override {
q1_.Enqueue(1);
q2_.Enqueue(2);
q2_.Enqueue(3);
}
// void TearDown() override {}
Queue<int> q0_;
Queue<int> q1_;
Queue<int> q2_;
};
```
In this case, `TearDown()` is not needed since we don't have to clean up after
each test, other than what's already done by the destructor.
Now we'll write tests using `TEST_F()` and this fixture.
```c++
TEST_F(QueueTest, IsEmptyInitially) {
EXPECT_EQ(q0_.size(), 0);
}
TEST_F(QueueTest, DequeueWorks) {
int* n = q0_.Dequeue();
EXPECT_EQ(n, nullptr);
n = q1_.Dequeue();
ASSERT_NE(n, nullptr);
EXPECT_EQ(*n, 1);
EXPECT_EQ(q1_.size(), 0);
delete n;
n = q2_.Dequeue();
ASSERT_NE(n, nullptr);
EXPECT_EQ(*n, 2);
EXPECT_EQ(q2_.size(), 1);
delete n;
}
```
The above uses both `ASSERT_*` and `EXPECT_*` assertions. The rule of thumb is
to use `EXPECT_*` when you want the test to continue to reveal more errors after
the assertion failure, and use `ASSERT_*` when continuing after failure doesn't
make sense. For example, the second assertion in the `Dequeue` test is
=ASSERT_NE(nullptr, n)=, as we need to dereference the pointer `n` later, which
would lead to a segfault when `n` is `NULL`.
When these tests run, the following happens:
1. googletest constructs a `QueueTest` object (let's call it `t1` ).
1. `t1.SetUp()` initializes `t1` .
1. The first test ( `IsEmptyInitially` ) runs on `t1` .
1. `t1.TearDown()` cleans up after the test finishes.
1. `t1` is destructed.
1. The above steps are repeated on another `QueueTest` object, this time
running the `DequeueWorks` test.
**Availability**: Linux, Windows, Mac.
## Invoking the Tests
`TEST()` and `TEST_F()` implicitly register their tests with googletest. So,
unlike with many other C++ testing frameworks, you don't have to re-list all
your defined tests in order to run them.
After defining your tests, you can run them with `RUN_ALL_TESTS()` , which
returns `0` if all the tests are successful, or `1` otherwise. Note that
`RUN_ALL_TESTS()` runs *all tests* in your link unit -- they can be from
different test cases, or even different source files.
When invoked, the `RUN_ALL_TESTS()` macro:
1. Saves the state of all googletest flags
* Creates a test fixture object for the first test.
* Initializes it via `SetUp()`.
* Runs the test on the fixture object.
* Cleans up the fixture via `TearDown()`.
* Deletes the fixture.
* Restores the state of all googletest flags
* Repeats the above steps for the next test, until all tests have run.
If a fatal failure happens the subsequent steps will be skipped.
> IMPORTANT: You must **not** ignore the return value of `RUN_ALL_TESTS()`, or
> you will get a compiler error. The rationale for this design is that the
> automated testing service determines whether a test has passed based on its
> exit code, not on its stdout/stderr output; thus your `main()` function must
> return the value of `RUN_ALL_TESTS()`.
>
> Also, you should call `RUN_ALL_TESTS()` only **once**. Calling it more than
> once conflicts with some advanced googletest features (e.g. thread-safe [death
> tests](advanced#death-tests)) and thus is not supported.
**Availability**: Linux, Windows, Mac.
## Writing the main() Function
In `google3`, the simplest approach is to use the default main() function
provided by linking in `"//testing/base/public:gtest_main"`. If that doesn't
cover what you need, you should write your own main() function, which should
return the value of `RUN_ALL_TESTS()`. Link to `"//testing/base/public:gunit"`.
You can start from this boilerplate:
```c++
#include "this/package/foo.h"
#include "gtest/gtest.h"
namespace {
// The fixture for testing class Foo.
class FooTest : public ::testing::Test {
protected:
// You can remove any or all of the following functions if its body
// is empty.
FooTest() {
// You can do set-up work for each test here.
}
~FooTest() override {
// You can do clean-up work that doesn't throw exceptions here.
}
// If the constructor and destructor are not enough for setting up
// and cleaning up each test, you can define the following methods:
void SetUp() override {
// Code here will be called immediately after the constructor (right
// before each test).
}
void TearDown() override {
// Code here will be called immediately after each test (right
// before the destructor).
}
// Objects declared here can be used by all tests in the test case for Foo.
};
// Tests that the Foo::Bar() method does Abc.
TEST_F(FooTest, MethodBarDoesAbc) {
const std::string input_filepath = "this/package/testdata/myinputfile.dat";
const std::string output_filepath = "this/package/testdata/myoutputfile.dat";
Foo f;
EXPECT_EQ(f.Bar(input_filepath, output_filepath), 0);
}
// Tests that Foo does Xyz.
TEST_F(FooTest, DoesXyz) {
// Exercises the Xyz feature of Foo.
}
} // namespace
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
```
The `::testing::InitGoogleTest()` function parses the command line for
googletest flags, and removes all recognized flags. This allows the user to
control a test program's behavior via various flags, which we'll cover in
[AdvancedGuide](advanced.md). You **must** call this function before calling
`RUN_ALL_TESTS()`, or the flags won't be properly initialized.
On Windows, `InitGoogleTest()` also works with wide strings, so it can be used
in programs compiled in `UNICODE` mode as well.
But maybe you think that writing all those main() functions is too much work? We
agree with you completely and that's why Google Test provides a basic
implementation of main(). If it fits your needs, then just link your test with
gtest\_main library and you are good to go.
NOTE: `ParseGUnitFlags()` is deprecated in favor of `InitGoogleTest()`.
## Known Limitations
* Google Test is designed to be thread-safe. The implementation is thread-safe
on systems where the `pthreads` library is available. It is currently
_unsafe_ to use Google Test assertions from two threads concurrently on
other systems (e.g. Windows). In most tests this is not an issue as usually
the assertions are done in the main thread. If you want to help, you can
volunteer to implement the necessary synchronization primitives in
`gtest-port.h` for your platform.

View File

@ -0,0 +1,22 @@
# Googletest Samples {#samples}
If you're like us, you'd like to look at [googletest
samples.](https://github.com/google/googletest/tree/master/googletest/samples)
The sample directory has a number of well-commented samples showing how to use a
variety of googletest features.
* Sample #1 shows the basic steps of using googletest to test C++ functions.
* Sample #2 shows a more complex unit test for a class with multiple member
functions.
* Sample #3 uses a test fixture.
* Sample #4 teaches you how to use googletest and `googletest.h` together to
get the best of both libraries.
* Sample #5 puts shared testing logic in a base test fixture, and reuses it in
derived fixtures.
* Sample #6 demonstrates type-parameterized tests.
* Sample #7 teaches the basics of value-parameterized tests.
* Sample #8 shows using `Combine()` in value-parameterized tests.
* Sample #9 shows use of the listener API to modify Google Test's console
output and the use of its reflection API to inspect test results.
* Sample #10 shows use of the listener API to implement a primitive memory
leak checker.

View File

@ -26,14 +26,14 @@
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Author: wan@google.com (Zhanyong Wan)
//
// The Google C++ Testing Framework (Google Test)
// The Google C++ Testing and Mocking Framework (Google Test)
//
// This header file defines the public API for death tests. It is
// #included by gtest.h so a user doesn't need to include this
// directly.
// GOOGLETEST_CM0001 DO NOT DELETE
#ifndef GTEST_INCLUDE_GTEST_GTEST_DEATH_TEST_H_
#define GTEST_INCLUDE_GTEST_GTEST_DEATH_TEST_H_
@ -99,6 +99,7 @@ GTEST_API_ bool InDeathTestChild();
//
// On the regular expressions used in death tests:
//
// GOOGLETEST_CM0005 DO NOT DELETE
// On POSIX-compliant systems (*nix), we use the <regex.h> library,
// which uses the POSIX extended regex syntax.
//
@ -160,7 +161,7 @@ GTEST_API_ bool InDeathTestChild();
// is rarely a problem as people usually don't put the test binary
// directory in PATH.
//
// TODO(wan@google.com): make thread-safe death tests search the PATH.
// FIXME: make thread-safe death tests search the PATH.
// Asserts that a given statement causes the program to exit, with an
// integer exit status that satisfies predicate, and emitting error output
@ -198,9 +199,10 @@ class GTEST_API_ ExitedWithCode {
const int exit_code_;
};
# if !GTEST_OS_WINDOWS
# if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA
// Tests that an exit code describes an exit due to termination by a
// given signal.
// GOOGLETEST_CM0006 DO NOT DELETE
class GTEST_API_ KilledBySignal {
public:
explicit KilledBySignal(int signum);

View File

@ -26,10 +26,9 @@
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Author: wan@google.com (Zhanyong Wan)
//
// The Google C++ Testing Framework (Google Test)
// The Google C++ Testing and Mocking Framework (Google Test)
//
// This header file defines the Message class.
//
@ -43,6 +42,8 @@
// to CHANGE WITHOUT NOTICE. Therefore DO NOT DEPEND ON IT in a user
// program!
// GOOGLETEST_CM0001 DO NOT DELETE
#ifndef GTEST_INCLUDE_GTEST_GTEST_MESSAGE_H_
#define GTEST_INCLUDE_GTEST_GTEST_MESSAGE_H_

View File

@ -31,13 +31,12 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Authors: vladl@google.com (Vlad Losev)
//
// Macros and functions for implementing parameterized tests
// in Google C++ Testing Framework (Google Test)
// in Google C++ Testing and Mocking Framework (Google Test)
//
// This file is generated by a SCRIPT. DO NOT EDIT BY HAND!
//
// GOOGLETEST_CM0001 DO NOT DELETE
#ifndef GTEST_INCLUDE_GTEST_GTEST_PARAM_TEST_H_
#define GTEST_INCLUDE_GTEST_GTEST_PARAM_TEST_H_

View File

@ -30,13 +30,12 @@ $var maxtuple = 10 $$ Maximum number of Combine arguments we want to support.
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Authors: vladl@google.com (Vlad Losev)
//
// Macros and functions for implementing parameterized tests
// in Google C++ Testing Framework (Google Test)
// in Google C++ Testing and Mocking Framework (Google Test)
//
// This file is generated by a SCRIPT. DO NOT EDIT BY HAND!
//
// GOOGLETEST_CM0001 DO NOT DELETE
#ifndef GTEST_INCLUDE_GTEST_GTEST_PARAM_TEST_H_
#define GTEST_INCLUDE_GTEST_GTEST_PARAM_TEST_H_

View File

@ -26,10 +26,9 @@
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Author: wan@google.com (Zhanyong Wan)
// Google Test - The Google C++ Testing Framework
// Google Test - The Google C++ Testing and Mocking Framework
//
// This file implements a universal value printer that can print a
// value of any type T:
@ -96,6 +95,8 @@
// being defined as many user-defined container types don't have
// value_type.
// GOOGLETEST_CM0001 DO NOT DELETE
#ifndef GTEST_INCLUDE_GTEST_GTEST_PRINTERS_H_
#define GTEST_INCLUDE_GTEST_GTEST_PRINTERS_H_
@ -114,6 +115,7 @@
#if GTEST_HAS_ABSL
#include "absl/strings/string_view.h"
#include "absl/types/optional.h"
#include "absl/types/variant.h"
#endif // GTEST_HAS_ABSL
namespace testing {
@ -636,6 +638,10 @@ inline void PrintTo(absl::string_view sp, ::std::ostream* os) {
}
#endif // GTEST_HAS_ABSL
#if GTEST_LANG_CXX11
inline void PrintTo(std::nullptr_t, ::std::ostream* os) { *os << "(nullptr)"; }
#endif // GTEST_LANG_CXX11
#if GTEST_HAS_TR1_TUPLE || GTEST_HAS_STD_TUPLE_
// Helper function for printing a tuple. T must be instantiated with
// a tuple type.
@ -783,6 +789,28 @@ class UniversalPrinter<::absl::optional<T>> {
}
};
// Printer for absl::variant
template <typename... T>
class UniversalPrinter<::absl::variant<T...>> {
public:
static void Print(const ::absl::variant<T...>& value, ::std::ostream* os) {
*os << '(';
absl::visit(Visitor{os}, value);
*os << ')';
}
private:
struct Visitor {
template <typename U>
void operator()(const U& u) const {
*os << "'" << GetTypeName<U>() << "' with value ";
UniversalPrint(u, os);
}
::std::ostream* os;
};
};
#endif // GTEST_HAS_ABSL
// UniversalPrintArray(begin, len, os) prints an array of 'len'
@ -798,7 +826,7 @@ void UniversalPrintArray(const T* begin, size_t len, ::std::ostream* os) {
// If the array has more than kThreshold elements, we'll have to
// omit some details by printing only the first and the last
// kChunkSize elements.
// TODO(wan@google.com): let the user control the threshold using a flag.
// FIXME: let the user control the threshold using a flag.
if (len <= kThreshold) {
PrintRawArrayTo(begin, len, os);
} else {

View File

@ -26,12 +26,13 @@
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Author: wan@google.com (Zhanyong Wan)
//
// Utilities for testing Google Test itself and code that uses Google Test
// (e.g. frameworks built on top of Google Test).
// GOOGLETEST_CM0004 DO NOT DELETE
#ifndef GTEST_INCLUDE_GTEST_GTEST_SPI_H_
#define GTEST_INCLUDE_GTEST_GTEST_SPI_H_

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.
//
// Author: mheule@google.com (Markus Heule)
//
// GOOGLETEST_CM0001 DO NOT DELETE
#ifndef GTEST_INCLUDE_GTEST_GTEST_TEST_PART_H_
#define GTEST_INCLUDE_GTEST_GTEST_TEST_PART_H_

View File

@ -26,8 +26,9 @@
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Author: wan@google.com (Zhanyong Wan)
// GOOGLETEST_CM0001 DO NOT DELETE
#ifndef GTEST_INCLUDE_GTEST_GTEST_TYPED_TEST_H_
#define GTEST_INCLUDE_GTEST_GTEST_TYPED_TEST_H_

View File

@ -26,10 +26,9 @@
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Author: wan@google.com (Zhanyong Wan)
//
// The Google C++ Testing Framework (Google Test)
// The Google C++ Testing and Mocking Framework (Google Test)
//
// This header file defines the public API for Google Test. It should be
// included by any test program that uses Google Test.
@ -48,6 +47,8 @@
// registration from Barthelemy Dagenais' (barthelemy@prologique.com)
// easyUnit framework.
// GOOGLETEST_CM0001 DO NOT DELETE
#ifndef GTEST_INCLUDE_GTEST_GTEST_H_
#define GTEST_INCLUDE_GTEST_GTEST_H_
@ -82,6 +83,15 @@
namespace testing {
// Silence C4100 (unreferenced formal parameter) and 4805
// unsafe mix of type 'const int' and type 'const bool'
#ifdef _MSC_VER
# pragma warning(push)
# pragma warning(disable:4805)
# pragma warning(disable:4100)
#endif
// Declares the flags.
// This flag temporary enables the disabled tests.
@ -163,6 +173,7 @@ class TestEventListenersAccessor;
class TestEventRepeater;
class UnitTestRecordPropertyTestHelper;
class WindowsDeathTest;
class FuchsiaDeathTest;
class UnitTestImpl* GetUnitTestImpl();
void ReportFailureInUnknownLocation(TestPartResult::Type result_type,
const std::string& message);
@ -304,7 +315,7 @@ class GTEST_API_ AssertionResult {
const char* message() const {
return message_.get() != NULL ? message_->c_str() : "";
}
// TODO(vladl@google.com): Remove this after making sure no clients use it.
// FIXME: Remove this after making sure no clients use it.
// Deprecated; please use message() instead.
const char* failure_message() const { return message(); }
@ -584,6 +595,7 @@ class GTEST_API_ TestResult {
friend class internal::TestResultAccessor;
friend class internal::UnitTestImpl;
friend class internal::WindowsDeathTest;
friend class internal::FuchsiaDeathTest;
// Gets the vector of TestPartResults.
const std::vector<TestPartResult>& test_part_results() const {
@ -609,7 +621,7 @@ class GTEST_API_ TestResult {
// Adds a failure if the key is a reserved attribute of Google Test
// testcase tags. Returns true if the property is valid.
// TODO(russr): Validate attribute names are legal and human readable.
// FIXME: Validate attribute names are legal and human readable.
static bool ValidateTestProperty(const std::string& xml_element,
const TestProperty& test_property);
@ -2298,6 +2310,10 @@ bool StaticAssertTypeEq() {
// Tries to determine an appropriate directory for the platform.
GTEST_API_ std::string TempDir();
#ifdef _MSC_VER
# pragma warning(pop)
#endif
} // namespace testing
// Use this function in main() to run all tests. It returns 0 if all

View File

@ -32,6 +32,8 @@
//
// Implements a family of generic predicate assertion macros.
// GOOGLETEST_CM0001 DO NOT DELETE
#ifndef GTEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_
#define GTEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_

View File

@ -26,10 +26,10 @@
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Author: wan@google.com (Zhanyong Wan)
//
// Google C++ Testing Framework definitions useful in production code.
// Google C++ Testing and Mocking Framework definitions useful in production code.
// GOOGLETEST_CM0003 DO NOT DELETE
#ifndef GTEST_INCLUDE_GTEST_GTEST_PROD_H_
#define GTEST_INCLUDE_GTEST_GTEST_PROD_H_

View File

@ -0,0 +1,56 @@
# Customization Points
The custom directory is an injection point for custom user configurations.
## Header `gtest.h`
### The following macros can be defined:
* `GTEST_OS_STACK_TRACE_GETTER_` - The name of an implementation of
`OsStackTraceGetterInterface`.
* `GTEST_CUSTOM_TEMPDIR_FUNCTION_` - An override for `testing::TempDir()`. See
`testing::TempDir` for semantics and signature.
## Header `gtest-port.h`
The following macros can be defined:
### Flag related macros:
* `GTEST_FLAG(flag_name)`
* `GTEST_USE_OWN_FLAGFILE_FLAG_` - Define to 0 when the system provides its
own flagfile flag parsing.
* `GTEST_DECLARE_bool_(name)`
* `GTEST_DECLARE_int32_(name)`
* `GTEST_DECLARE_string_(name)`
* `GTEST_DEFINE_bool_(name, default_val, doc)`
* `GTEST_DEFINE_int32_(name, default_val, doc)`
* `GTEST_DEFINE_string_(name, default_val, doc)`
### Logging:
* `GTEST_LOG_(severity)`
* `GTEST_CHECK_(condition)`
* Functions `LogToStderr()` and `FlushInfoLog()` have to be provided too.
### Threading:
* `GTEST_HAS_NOTIFICATION_` - Enabled if Notification is already provided.
* `GTEST_HAS_MUTEX_AND_THREAD_LOCAL_` - Enabled if `Mutex` and `ThreadLocal`
are already provided. Must also provide `GTEST_DECLARE_STATIC_MUTEX_(mutex)`
and `GTEST_DEFINE_STATIC_MUTEX_(mutex)`
* `GTEST_EXCLUSIVE_LOCK_REQUIRED_(locks)`
* `GTEST_LOCK_EXCLUDED_(locks)`
### Underlying library support features
* `GTEST_HAS_CXXABI_H_`
### Exporting API symbols:
* `GTEST_API_` - Specifier for exported symbols.
## Header `gtest-printers.h`
* See documentation at `gtest/gtest-printers.h` for details on how to define a
custom printer.

View File

@ -27,45 +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.
//
// Injection point for custom user configurations.
// The following macros can be defined:
//
// Flag related macros:
// GTEST_FLAG(flag_name)
// GTEST_USE_OWN_FLAGFILE_FLAG_ - Define to 0 when the system provides its
// own flagfile flag parsing.
// GTEST_DECLARE_bool_(name)
// GTEST_DECLARE_int32_(name)
// GTEST_DECLARE_string_(name)
// GTEST_DEFINE_bool_(name, default_val, doc)
// GTEST_DEFINE_int32_(name, default_val, doc)
// GTEST_DEFINE_string_(name, default_val, doc)
//
// Test filtering:
// GTEST_TEST_FILTER_ENV_VAR_ - The name of an environment variable that
// will be used if --GTEST_FLAG(test_filter)
// is not provided.
//
// Logging:
// GTEST_LOG_(severity)
// GTEST_CHECK_(condition)
// Functions LogToStderr() and FlushInfoLog() have to be provided too.
//
// Threading:
// GTEST_HAS_NOTIFICATION_ - Enabled if Notification is already provided.
// GTEST_HAS_MUTEX_AND_THREAD_LOCAL_ - Enabled if Mutex and ThreadLocal are
// already provided.
// Must also provide GTEST_DECLARE_STATIC_MUTEX_(mutex) and
// GTEST_DEFINE_STATIC_MUTEX_(mutex)
//
// GTEST_EXCLUSIVE_LOCK_REQUIRED_(locks)
// GTEST_LOCK_EXCLUDED_(locks)
//
// Underlying library support features:
// GTEST_HAS_CXXABI_H_
//
// Exporting API symbols:
// GTEST_API_ - Specifier for exported symbols.
// Injection point for custom user configurations. See README for details
//
// ** Custom implementation starts here **

View File

@ -31,8 +31,8 @@
// installation of gTest.
// It will be included from gtest-printers.h and the overrides in this file
// will be visible to everyone.
// See documentation at gtest/gtest-printers.h for details on how to define a
// custom printer.
//
// Injection point for custom user configurations. See README for details
//
// ** Custom implementation starts here **

View File

@ -27,15 +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.
//
// Injection point for custom user configurations.
// The following macros can be defined:
//
// GTEST_OS_STACK_TRACE_GETTER_ - The name of an implementation of
// OsStackTraceGetterInterface.
//
// GTEST_CUSTOM_TEMPDIR_FUNCTION_ - An override for testing::TempDir().
// See testing::TempDir for semantics and
// signature.
// Injection point for custom user configurations. See README for details
//
// ** Custom implementation starts here **

View File

@ -27,11 +27,11 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//
// The Google C++ Testing Framework (Google Test)
// The Google C++ Testing and Mocking Framework (Google Test)
//
// This header file defines internal utilities needed for implementing
// death tests. They are subject to change without notice.
// GOOGLETEST_CM0001 DO NOT DELETE
#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_DEATH_TEST_INTERNAL_H_
#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_DEATH_TEST_INTERNAL_H_

View File

@ -27,7 +27,6 @@
// (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 Test filepath utilities
//
// This header file declares classes and functions used internally by
@ -36,6 +35,8 @@
// This file is #included in gtest/internal/gtest-internal.h.
// Do not include this header file separately!
// GOOGLETEST_CM0001 DO NOT DELETE
#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_FILEPATH_H_
#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_FILEPATH_H_

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