commit
c00373320d
115 changed files with 2959 additions and 28062 deletions
@ -1,3 +1,10 @@ |
||||
# Ignore CI build directory |
||||
build/ |
||||
xcuserdata |
||||
cmake-build-debug/ |
||||
.idea/ |
||||
bazel-bin |
||||
bazel-genfiles |
||||
bazel-googletest |
||||
bazel-out |
||||
bazel-testlogs |
||||
|
@ -0,0 +1,147 @@ |
||||
# Copyright 2017 Google Inc. |
||||
# All Rights Reserved. |
||||
# |
||||
# |
||||
# Redistribution and use in source and binary forms, with or without |
||||
# modification, are permitted provided that the following conditions are |
||||
# met: |
||||
# |
||||
# * Redistributions of source code must retain the above copyright |
||||
# notice, this list of conditions and the following disclaimer. |
||||
# * Redistributions in binary form must reproduce the above |
||||
# copyright notice, this list of conditions and the following disclaimer |
||||
# in the documentation and/or other materials provided with the |
||||
# distribution. |
||||
# * Neither the name of Google Inc. nor the names of its |
||||
# contributors may be used to endorse or promote products derived from |
||||
# this software without specific prior written permission. |
||||
# |
||||
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
||||
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
||||
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR |
||||
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT |
||||
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, |
||||
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT |
||||
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, |
||||
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY |
||||
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT |
||||
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE |
||||
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |
||||
# |
||||
# Author: misterg@google.com (Gennadiy Civil) |
||||
# |
||||
# Bazel Build for Google C++ Testing Framework(Google Test) |
||||
|
||||
package(default_visibility = ["//visibility:public"]) |
||||
|
||||
licenses(["notice"]) |
||||
|
||||
config_setting( |
||||
name = "win", |
||||
values = {"cpu": "x64_windows_msvc"}, |
||||
) |
||||
|
||||
# Google Test including Google Mock |
||||
cc_library( |
||||
name = "gtest", |
||||
srcs = glob( |
||||
include = [ |
||||
"googletest/src/*.cc", |
||||
"googletest/src/*.h", |
||||
"googletest/include/gtest/**/*.h", |
||||
"googlemock/src/*.cc", |
||||
"googlemock/include/gmock/**/*.h", |
||||
], |
||||
exclude = [ |
||||
"googletest/src/gtest-all.cc", |
||||
"googletest/src/gtest_main.cc", |
||||
"googlemock/src/gmock-all.cc", |
||||
"googlemock/src/gmock_main.cc", |
||||
], |
||||
), |
||||
hdrs =glob([ |
||||
"googletest/include/gtest/*.h", |
||||
"googlemock/include/gmock/*.h", |
||||
]), |
||||
copts = select( |
||||
{ |
||||
":win": [], |
||||
"//conditions:default": ["-pthread"], |
||||
}, |
||||
), |
||||
includes = [ |
||||
"googlemock", |
||||
"googlemock/include", |
||||
"googletest", |
||||
"googletest/include", |
||||
], |
||||
linkopts = select({ |
||||
":win": [], |
||||
"//conditions:default": [ |
||||
"-pthread", |
||||
], |
||||
}), |
||||
) |
||||
|
||||
cc_library( |
||||
name = "gtest_main", |
||||
srcs = [ |
||||
"googlemock/src/gmock_main.cc", |
||||
], |
||||
deps = ["//:gtest"], |
||||
) |
||||
|
||||
# The following rules build samples of how to use gTest. |
||||
cc_library( |
||||
name = "gtest_sample_lib", |
||||
srcs = [ |
||||
"googletest/samples/sample1.cc", |
||||
"googletest/samples/sample2.cc", |
||||
"googletest/samples/sample4.cc", |
||||
], |
||||
hdrs = [ |
||||
"googletest/samples/prime_tables.h", |
||||
"googletest/samples/sample1.h", |
||||
"googletest/samples/sample2.h", |
||||
"googletest/samples/sample3-inl.h", |
||||
"googletest/samples/sample4.h", |
||||
], |
||||
) |
||||
|
||||
cc_test( |
||||
name = "gtest_samples", |
||||
size = "small", |
||||
#All Samples except: |
||||
#sample9 ( main ) |
||||
#sample10 (main and takes a command line option and needs to be separate) |
||||
srcs = [ |
||||
"googletest/samples/sample1_unittest.cc", |
||||
"googletest/samples/sample2_unittest.cc", |
||||
"googletest/samples/sample3_unittest.cc", |
||||
"googletest/samples/sample4_unittest.cc", |
||||
"googletest/samples/sample5_unittest.cc", |
||||
"googletest/samples/sample6_unittest.cc", |
||||
"googletest/samples/sample7_unittest.cc", |
||||
"googletest/samples/sample8_unittest.cc", |
||||
], |
||||
deps = [ |
||||
"gtest_sample_lib", |
||||
":gtest_main", |
||||
], |
||||
) |
||||
|
||||
cc_test( |
||||
name = "sample9_unittest", |
||||
size = "small", |
||||
srcs = ["googletest/samples/sample9_unittest.cc"], |
||||
deps = [":gtest"], |
||||
) |
||||
|
||||
cc_test( |
||||
name = "sample10_unittest", |
||||
size = "small", |
||||
srcs = ["googletest/samples/sample10_unittest.cc"], |
||||
deps = [ |
||||
":gtest", |
||||
], |
||||
) |
@ -0,0 +1,9 @@ |
||||
libdir=@CMAKE_INSTALL_FULL_LIBDIR@ |
||||
includedir=@CMAKE_INSTALL_FULL_INCLUDEDIR@ |
||||
|
||||
Name: gmock |
||||
Description: GoogleMock (without main() function) |
||||
Version: @PROJECT_VERSION@ |
||||
URL: https://github.com/google/googletest |
||||
Libs: -L${libdir} -lgmock @CMAKE_THREAD_LIBS_INIT@ |
||||
Cflags: -I${includedir} @GTEST_HAS_PTHREAD_MACRO@ @CMAKE_THREAD_LIBS_INIT@ |
@ -0,0 +1,9 @@ |
||||
libdir=@CMAKE_INSTALL_FULL_LIBDIR@ |
||||
includedir=@CMAKE_INSTALL_FULL_INCLUDEDIR@ |
||||
|
||||
Name: gmock_main |
||||
Description: GoogleMock (with main() function) |
||||
Version: @PROJECT_VERSION@ |
||||
URL: https://github.com/google/googletest |
||||
Libs: -L${libdir} -lgmock_main @CMAKE_THREAD_LIBS_INIT@ |
||||
Cflags: -I${includedir} @GTEST_HAS_PTHREAD_MACRO@ @CMAKE_THREAD_LIBS_INIT@ |
@ -1,525 +0,0 @@ |
||||
|
||||
|
||||
# Defining a Mock Class # |
||||
|
||||
## Mocking a Normal Class ## |
||||
|
||||
Given |
||||
``` |
||||
class Foo { |
||||
... |
||||
virtual ~Foo(); |
||||
virtual int GetSize() const = 0; |
||||
virtual string Describe(const char* name) = 0; |
||||
virtual string Describe(int type) = 0; |
||||
virtual bool Process(Bar elem, int count) = 0; |
||||
}; |
||||
``` |
||||
(note that `~Foo()` **must** be virtual) we can define its mock as |
||||
``` |
||||
#include <gmock/gmock.h> |
||||
|
||||
class MockFoo : public Foo { |
||||
MOCK_CONST_METHOD0(GetSize, int()); |
||||
MOCK_METHOD1(Describe, string(const char* name)); |
||||
MOCK_METHOD1(Describe, string(int type)); |
||||
MOCK_METHOD2(Process, bool(Bar elem, int count)); |
||||
}; |
||||
``` |
||||
|
||||
To create a "nice" mock object which ignores all uninteresting calls, |
||||
or a "strict" mock object, which treats them as failures: |
||||
``` |
||||
NiceMock<MockFoo> nice_foo; // The type is a subclass of MockFoo. |
||||
StrictMock<MockFoo> strict_foo; // The type is a subclass of MockFoo. |
||||
``` |
||||
|
||||
## Mocking a Class Template ## |
||||
|
||||
To mock |
||||
``` |
||||
template <typename Elem> |
||||
class StackInterface { |
||||
public: |
||||
... |
||||
virtual ~StackInterface(); |
||||
virtual int GetSize() const = 0; |
||||
virtual void Push(const Elem& x) = 0; |
||||
}; |
||||
``` |
||||
(note that `~StackInterface()` **must** be virtual) just append `_T` to the `MOCK_*` macros: |
||||
``` |
||||
template <typename Elem> |
||||
class MockStack : public StackInterface<Elem> { |
||||
public: |
||||
... |
||||
MOCK_CONST_METHOD0_T(GetSize, int()); |
||||
MOCK_METHOD1_T(Push, void(const Elem& x)); |
||||
}; |
||||
``` |
||||
|
||||
## Specifying Calling Conventions for Mock Functions ## |
||||
|
||||
If your mock function doesn't use the default calling convention, you |
||||
can specify it by appending `_WITH_CALLTYPE` to any of the macros |
||||
described in the previous two sections and supplying the calling |
||||
convention as the first argument to the macro. For example, |
||||
``` |
||||
MOCK_METHOD_1_WITH_CALLTYPE(STDMETHODCALLTYPE, Foo, bool(int n)); |
||||
MOCK_CONST_METHOD2_WITH_CALLTYPE(STDMETHODCALLTYPE, Bar, int(double x, double y)); |
||||
``` |
||||
where `STDMETHODCALLTYPE` is defined by `<objbase.h>` on Windows. |
||||
|
||||
# Using Mocks in Tests # |
||||
|
||||
The typical flow is: |
||||
1. Import the Google Mock names you need to use. All Google Mock names are in the `testing` namespace unless they are macros or otherwise noted. |
||||
1. Create the mock objects. |
||||
1. Optionally, set the default actions of the mock objects. |
||||
1. Set your expectations on the mock objects (How will they be called? What wil they do?). |
||||
1. Exercise code that uses the mock objects; if necessary, check the result using [Google Test](http://code.google.com/p/googletest/) assertions. |
||||
1. When a mock objects is destructed, Google Mock automatically verifies that all expectations on it have been satisfied. |
||||
|
||||
Here is an example: |
||||
``` |
||||
using ::testing::Return; // #1 |
||||
|
||||
TEST(BarTest, DoesThis) { |
||||
MockFoo foo; // #2 |
||||
|
||||
ON_CALL(foo, GetSize()) // #3 |
||||
.WillByDefault(Return(1)); |
||||
// ... other default actions ... |
||||
|
||||
EXPECT_CALL(foo, Describe(5)) // #4 |
||||
.Times(3) |
||||
.WillRepeatedly(Return("Category 5")); |
||||
// ... other expectations ... |
||||
|
||||
EXPECT_EQ("good", MyProductionFunction(&foo)); // #5 |
||||
} // #6 |
||||
``` |
||||
|
||||
# Setting Default Actions # |
||||
|
||||
Google Mock has a **built-in default action** for any function that |
||||
returns `void`, `bool`, a numeric value, or a pointer. |
||||
|
||||
To customize the default action for functions with return type `T` globally: |
||||
``` |
||||
using ::testing::DefaultValue; |
||||
|
||||
DefaultValue<T>::Set(value); // Sets the default value to be returned. |
||||
// ... use the mocks ... |
||||
DefaultValue<T>::Clear(); // Resets the default value. |
||||
``` |
||||
|
||||
To customize the default action for a particular method, use `ON_CALL()`: |
||||
``` |
||||
ON_CALL(mock_object, method(matchers)) |
||||
.With(multi_argument_matcher) ? |
||||
.WillByDefault(action); |
||||
``` |
||||
|
||||
# Setting Expectations # |
||||
|
||||
`EXPECT_CALL()` sets **expectations** on a mock method (How will it be |
||||
called? What will it do?): |
||||
``` |
||||
EXPECT_CALL(mock_object, method(matchers)) |
||||
.With(multi_argument_matcher) ? |
||||
.Times(cardinality) ? |
||||
.InSequence(sequences) * |
||||
.After(expectations) * |
||||
.WillOnce(action) * |
||||
.WillRepeatedly(action) ? |
||||
.RetiresOnSaturation(); ? |
||||
``` |
||||
|
||||
If `Times()` is omitted, the cardinality is assumed to be: |
||||
|
||||
* `Times(1)` when there is neither `WillOnce()` nor `WillRepeatedly()`; |
||||
* `Times(n)` when there are `n WillOnce()`s but no `WillRepeatedly()`, where `n` >= 1; or |
||||
* `Times(AtLeast(n))` when there are `n WillOnce()`s and a `WillRepeatedly()`, where `n` >= 0. |
||||
|
||||
A method with no `EXPECT_CALL()` is free to be invoked _any number of times_, and the default action will be taken each time. |
||||
|
||||
# Matchers # |
||||
|
||||
A **matcher** matches a _single_ argument. You can use it inside |
||||
`ON_CALL()` or `EXPECT_CALL()`, or use it to validate a value |
||||
directly: |
||||
|
||||
| `EXPECT_THAT(value, matcher)` | Asserts that `value` matches `matcher`. | |
||||
|:------------------------------|:----------------------------------------| |
||||
| `ASSERT_THAT(value, matcher)` | The same as `EXPECT_THAT(value, matcher)`, except that it generates a **fatal** failure. | |
||||
|
||||
Built-in matchers (where `argument` is the function argument) are |
||||
divided into several categories: |
||||
|
||||
## Wildcard ## |
||||
|`_`|`argument` can be any value of the correct type.| |
||||
|:--|:-----------------------------------------------| |
||||
|`A<type>()` or `An<type>()`|`argument` can be any value of type `type`. | |
||||
|
||||
## Generic Comparison ## |
||||
|
||||
|`Eq(value)` or `value`|`argument == value`| |
||||
|:---------------------|:------------------| |
||||
|`Ge(value)` |`argument >= value`| |
||||
|`Gt(value)` |`argument > value` | |
||||
|`Le(value)` |`argument <= value`| |
||||
|`Lt(value)` |`argument < value` | |
||||
|`Ne(value)` |`argument != value`| |
||||
|`IsNull()` |`argument` is a `NULL` pointer (raw or smart).| |
||||
|`NotNull()` |`argument` is a non-null pointer (raw or smart).| |
||||
|`Ref(variable)` |`argument` is a reference to `variable`.| |
||||
|`TypedEq<type>(value)`|`argument` has type `type` and is equal to `value`. You may need to use this instead of `Eq(value)` when the mock function is overloaded.| |
||||
|
||||
Except `Ref()`, these matchers make a _copy_ of `value` in case it's |
||||
modified or destructed later. If the compiler complains that `value` |
||||
doesn't have a public copy constructor, try wrap it in `ByRef()`, |
||||
e.g. `Eq(ByRef(non_copyable_value))`. If you do that, make sure |
||||
`non_copyable_value` is not changed afterwards, or the meaning of your |
||||
matcher will be changed. |
||||
|
||||
## Floating-Point Matchers ## |
||||
|
||||
|`DoubleEq(a_double)`|`argument` is a `double` value approximately equal to `a_double`, treating two NaNs as unequal.| |
||||
|:-------------------|:----------------------------------------------------------------------------------------------| |
||||
|`FloatEq(a_float)` |`argument` is a `float` value approximately equal to `a_float`, treating two NaNs as unequal. | |
||||
|`NanSensitiveDoubleEq(a_double)`|`argument` is a `double` value approximately equal to `a_double`, treating two NaNs as equal. | |
||||
|`NanSensitiveFloatEq(a_float)`|`argument` is a `float` value approximately equal to `a_float`, treating two NaNs as equal. | |
||||
|
||||
The above matchers use ULP-based comparison (the same as used in |
||||
[Google Test](http://code.google.com/p/googletest/)). They |
||||
automatically pick a reasonable error bound based on the absolute |
||||
value of the expected value. `DoubleEq()` and `FloatEq()` conform to |
||||
the IEEE standard, which requires comparing two NaNs for equality to |
||||
return false. The `NanSensitive*` version instead treats two NaNs as |
||||
equal, which is often what a user wants. |
||||
|
||||
## String Matchers ## |
||||
|
||||
The `argument` can be either a C string or a C++ string object: |
||||
|
||||
|`ContainsRegex(string)`|`argument` matches the given regular expression.| |
||||
|:----------------------|:-----------------------------------------------| |
||||
|`EndsWith(suffix)` |`argument` ends with string `suffix`. | |
||||
|`HasSubstr(string)` |`argument` contains `string` as a sub-string. | |
||||
|`MatchesRegex(string)` |`argument` matches the given regular expression with the match starting at the first character and ending at the last character.| |
||||
|`StartsWith(prefix)` |`argument` starts with string `prefix`. | |
||||
|`StrCaseEq(string)` |`argument` is equal to `string`, ignoring case. | |
||||
|`StrCaseNe(string)` |`argument` is not equal to `string`, ignoring case.| |
||||
|`StrEq(string)` |`argument` is equal to `string`. | |
||||
|`StrNe(string)` |`argument` is not equal to `string`. | |
||||
|
||||
`StrCaseEq()`, `StrCaseNe()`, `StrEq()`, and `StrNe()` work for wide |
||||
strings as well. |
||||
|
||||
## Container Matchers ## |
||||
|
||||
Most STL-style containers support `==`, so you can use |
||||
`Eq(expected_container)` or simply `expected_container` to match a |
||||
container exactly. If you want to write the elements in-line, |
||||
match them more flexibly, or get more informative messages, you can use: |
||||
|
||||
| `Contains(e)` | `argument` contains an element that matches `e`, which can be either a value or a matcher. | |
||||
|:--------------|:-------------------------------------------------------------------------------------------| |
||||
|`ElementsAre(e0, e1, ..., en)`|`argument` has `n + 1` elements, where the i-th element matches `ei`, which can be a value or a matcher. 0 to 10 arguments are allowed.| |
||||
|`ElementsAreArray(array)` or `ElementsAreArray(array, count)`|The same as `ElementsAre()` except that the expected element values/matchers come from a C-style array.| |
||||
| `ContainerEq(container)` | The same as `Eq(container)` except that the failure message also includes which elements are in one container but not the other. | |
||||
|
||||
These matchers can also match: |
||||
|
||||
1. a native array passed by reference (e.g. in `Foo(const int (&a)[5])`), and |
||||
1. an array passed as a pointer and a count (e.g. in `Bar(const T* buffer, int len)` -- see [Multi-argument Matchers](#Multiargument_Matchers.md)). |
||||
|
||||
where the array may be multi-dimensional (i.e. its elements can be arrays). |
||||
|
||||
## Member Matchers ## |
||||
|
||||
|`Field(&class::field, m)`|`argument.field` (or `argument->field` when `argument` is a plain pointer) matches matcher `m`, where `argument` is an object of type _class_.| |
||||
|:------------------------|:---------------------------------------------------------------------------------------------------------------------------------------------| |
||||
|`Key(e)` |`argument.first` matches `e`, which can be either a value or a matcher. E.g. `Contains(Key(Le(5)))` can verify that a `map` contains a key `<= 5`.| |
||||
|`Pair(m1, m2)` |`argument` is an `std::pair` whose `first` field matches `m1` and `second` field matches `m2`. | |
||||
|`Property(&class::property, m)`|`argument.property()` (or `argument->property()` when `argument` is a plain pointer) matches matcher `m`, where `argument` is an object of type _class_.| |
||||
|
||||
## Matching the Result of a Function or Functor ## |
||||
|
||||
|`ResultOf(f, m)`|`f(argument)` matches matcher `m`, where `f` is a function or functor.| |
||||
|:---------------|:---------------------------------------------------------------------| |
||||
|
||||
## Pointer Matchers ## |
||||
|
||||
|`Pointee(m)`|`argument` (either a smart pointer or a raw pointer) points to a value that matches matcher `m`.| |
||||
|:-----------|:-----------------------------------------------------------------------------------------------| |
||||
|
||||
## Multiargument Matchers ## |
||||
|
||||
These are matchers on tuple types. They can be used in |
||||
`.With()`. The following can be used on functions with <i>two<br> |
||||
arguments</i> `x` and `y`: |
||||
|
||||
|`Eq()`|`x == y`| |
||||
|:-----|:-------| |
||||
|`Ge()`|`x >= y`| |
||||
|`Gt()`|`x > y` | |
||||
|`Le()`|`x <= y`| |
||||
|`Lt()`|`x < y` | |
||||
|`Ne()`|`x != y`| |
||||
|
||||
You can use the following selectors to pick a subset of the arguments |
||||
(or reorder them) to participate in the matching: |
||||
|
||||
|`AllArgs(m)`|Equivalent to `m`. Useful as syntactic sugar in `.With(AllArgs(m))`.| |
||||
|:-----------|:-------------------------------------------------------------------| |
||||
|`Args<N1, N2, ..., Nk>(m)`|The `k` selected (using 0-based indices) arguments match `m`, e.g. `Args<1, 2>(Contains(5))`.| |
||||
|
||||
## Composite Matchers ## |
||||
|
||||
You can make a matcher from one or more other matchers: |
||||
|
||||
|`AllOf(m1, m2, ..., mn)`|`argument` matches all of the matchers `m1` to `mn`.| |
||||
|:-----------------------|:---------------------------------------------------| |
||||
|`AnyOf(m1, m2, ..., mn)`|`argument` matches at least one of the matchers `m1` to `mn`.| |
||||
|`Not(m)` |`argument` doesn't match matcher `m`. | |
||||
|
||||
## Adapters for Matchers ## |
||||
|
||||
|`MatcherCast<T>(m)`|casts matcher `m` to type `Matcher<T>`.| |
||||
|:------------------|:--------------------------------------| |
||||
|`SafeMatcherCast<T>(m)`| [safely casts](V1_5_CookBook#Casting_Matchers.md) matcher `m` to type `Matcher<T>`. | |
||||
|`Truly(predicate)` |`predicate(argument)` returns something considered by C++ to be true, where `predicate` is a function or functor.| |
||||
|
||||
## Matchers as Predicates ## |
||||
|
||||
|`Matches(m)`|a unary functor that returns `true` if the argument matches `m`.| |
||||
|:-----------|:---------------------------------------------------------------| |
||||
|`ExplainMatchResult(m, value, result_listener)`|returns `true` if `value` matches `m`, explaining the result to `result_listener`.| |
||||
|`Value(x, m)`|returns `true` if the value of `x` matches `m`. | |
||||
|
||||
## Defining Matchers ## |
||||
|
||||
| `MATCHER(IsEven, "") { return (arg % 2) == 0; }` | Defines a matcher `IsEven()` to match an even number. | |
||||
|:-------------------------------------------------|:------------------------------------------------------| |
||||
| `MATCHER_P(IsDivisibleBy, n, "") { *result_listener << "where the remainder is " << (arg % n); return (arg % n) == 0; }` | Defines a macher `IsDivisibleBy(n)` to match a number divisible by `n`. | |
||||
| `MATCHER_P2(IsBetween, a, b, "is between %(a)s and %(b)s") { return a <= arg && arg <= b; }` | Defines a matcher `IsBetween(a, b)` to match a value in the range [`a`, `b`]. | |
||||
|
||||
**Notes:** |
||||
|
||||
1. The `MATCHER*` macros cannot be used inside a function or class. |
||||
1. The matcher body must be _purely functional_ (i.e. it cannot have any side effect, and the result must not depend on anything other than the value being matched and the matcher parameters). |
||||
1. You can use `PrintToString(x)` to convert a value `x` of any type to a string. |
||||
|
||||
## Matchers as Test Assertions ## |
||||
|
||||
|`ASSERT_THAT(expression, m)`|Generates a [fatal failure](http://code.google.com/p/googletest/wiki/GoogleTestPrimer#Assertions) if the value of `expression` doesn't match matcher `m`.| |
||||
|:---------------------------|:--------------------------------------------------------------------------------------------------------------------------------------------------------| |
||||
|`EXPECT_THAT(expression, m)`|Generates a non-fatal failure if the value of `expression` doesn't match matcher `m`. | |
||||
|
||||
# Actions # |
||||
|
||||
**Actions** specify what a mock function should do when invoked. |
||||
|
||||
## Returning a Value ## |
||||
|
||||
|`Return()`|Return from a `void` mock function.| |
||||
|:---------|:----------------------------------| |
||||
|`Return(value)`|Return `value`. | |
||||
|`ReturnArg<N>()`|Return the `N`-th (0-based) argument.| |
||||
|`ReturnNew<T>(a1, ..., ak)`|Return `new T(a1, ..., ak)`; a different object is created each time.| |
||||
|`ReturnNull()`|Return a null pointer. | |
||||
|`ReturnRef(variable)`|Return a reference to `variable`. | |
||||
|
||||
## Side Effects ## |
||||
|
||||
|`Assign(&variable, value)`|Assign `value` to variable.| |
||||
|:-------------------------|:--------------------------| |
||||
| `DeleteArg<N>()` | Delete the `N`-th (0-based) argument, which must be a pointer. | |
||||
| `SaveArg<N>(pointer)` | Save the `N`-th (0-based) argument to `*pointer`. | |
||||
| `SetArgReferee<N>(value)` | Assign value to the variable referenced by the `N`-th (0-based) argument. | |
||||
|`SetArgumentPointee<N>(value)`|Assign `value` to the variable pointed by the `N`-th (0-based) argument.| |
||||
|`SetArrayArgument<N>(first, last)`|Copies the elements in source range [`first`, `last`) to the array pointed to by the `N`-th (0-based) argument, which can be either a pointer or an iterator. The action does not take ownership of the elements in the source range.| |
||||
|`SetErrnoAndReturn(error, value)`|Set `errno` to `error` and return `value`.| |
||||
|`Throw(exception)` |Throws the given exception, which can be any copyable value. Available since v1.1.0.| |
||||
|
||||
## Using a Function or a Functor as an Action ## |
||||
|
||||
|`Invoke(f)`|Invoke `f` with the arguments passed to the mock function, where `f` can be a global/static function or a functor.| |
||||
|:----------|:-----------------------------------------------------------------------------------------------------------------| |
||||
|`Invoke(object_pointer, &class::method)`|Invoke the {method on the object with the arguments passed to the mock function. | |
||||
|`InvokeWithoutArgs(f)`|Invoke `f`, which can be a global/static function or a functor. `f` must take no arguments. | |
||||
|`InvokeWithoutArgs(object_pointer, &class::method)`|Invoke the method on the object, which takes no arguments. | |
||||
|`InvokeArgument<N>(arg1, arg2, ..., argk)`|Invoke the mock function's `N`-th (0-based) argument, which must be a function or a functor, with the `k` arguments.| |
||||
|
||||
The return value of the invoked function is used as the return value |
||||
of the action. |
||||
|
||||
When defining a function or functor to be used with `Invoke*()`, you can declare any unused parameters as `Unused`: |
||||
``` |
||||
double Distance(Unused, double x, double y) { return sqrt(x*x + y*y); } |
||||
... |
||||
EXPECT_CALL(mock, Foo("Hi", _, _)).WillOnce(Invoke(Distance)); |
||||
``` |
||||
|
||||
In `InvokeArgument<N>(...)`, if an argument needs to be passed by reference, wrap it inside `ByRef()`. For example, |
||||
``` |
||||
InvokeArgument<2>(5, string("Hi"), ByRef(foo)) |
||||
``` |
||||
calls the mock function's #2 argument, passing to it `5` and `string("Hi")` by value, and `foo` by reference. |
||||
|
||||
## Default Action ## |
||||
|
||||
|`DoDefault()`|Do the default action (specified by `ON_CALL()` or the built-in one).| |
||||
|:------------|:--------------------------------------------------------------------| |
||||
|
||||
**Note:** due to technical reasons, `DoDefault()` cannot be used inside a composite action - trying to do so will result in a run-time error. |
||||
|
||||
## Composite Actions ## |
||||
|
||||
|`DoAll(a1, a2, ..., an)`|Do all actions `a1` to `an` and return the result of `an` in each invocation. The first `n - 1` sub-actions must return void. | |
||||
|:-----------------------|:-----------------------------------------------------------------------------------------------------------------------------| |
||||
|`IgnoreResult(a)` |Perform action `a` and ignore its result. `a` must not return void. | |
||||
|`WithArg<N>(a)` |Pass the `N`-th (0-based) argument of the mock function to action `a` and perform it. | |
||||
|`WithArgs<N1, N2, ..., Nk>(a)`|Pass the selected (0-based) arguments of the mock function to action `a` and perform it. | |
||||
|`WithoutArgs(a)` |Perform action `a` without any arguments. | |
||||
|
||||
## Defining Actions ## |
||||
|
||||
| `ACTION(Sum) { return arg0 + arg1; }` | Defines an action `Sum()` to return the sum of the mock function's argument #0 and #1. | |
||||
|:--------------------------------------|:---------------------------------------------------------------------------------------| |
||||
| `ACTION_P(Plus, n) { return arg0 + n; }` | Defines an action `Plus(n)` to return the sum of the mock function's argument #0 and `n`. | |
||||
| `ACTION_Pk(Foo, p1, ..., pk) { statements; }` | Defines a parameterized action `Foo(p1, ..., pk)` to execute the given `statements`. | |
||||
|
||||
The `ACTION*` macros cannot be used inside a function or class. |
||||
|
||||
# Cardinalities # |
||||
|
||||
These are used in `Times()` to specify how many times a mock function will be called: |
||||
|
||||
|`AnyNumber()`|The function can be called any number of times.| |
||||
|:------------|:----------------------------------------------| |
||||
|`AtLeast(n)` |The call is expected at least `n` times. | |
||||
|`AtMost(n)` |The call is expected at most `n` times. | |
||||
|`Between(m, n)`|The call is expected between `m` and `n` (inclusive) times.| |
||||
|`Exactly(n) or n`|The call is expected exactly `n` times. In particular, the call should never happen when `n` is 0.| |
||||
|
||||
# Expectation Order # |
||||
|
||||
By default, the expectations can be matched in _any_ order. If some |
||||
or all expectations must be matched in a given order, there are two |
||||
ways to specify it. They can be used either independently or |
||||
together. |
||||
|
||||
## The After Clause ## |
||||
|
||||
``` |
||||
using ::testing::Expectation; |
||||
... |
||||
Expectation init_x = EXPECT_CALL(foo, InitX()); |
||||
Expectation init_y = EXPECT_CALL(foo, InitY()); |
||||
EXPECT_CALL(foo, Bar()) |
||||
.After(init_x, init_y); |
||||
``` |
||||
says that `Bar()` can be called only after both `InitX()` and |
||||
`InitY()` have been called. |
||||
|
||||
If you don't know how many pre-requisites an expectation has when you |
||||
write it, you can use an `ExpectationSet` to collect them: |
||||
|
||||
``` |
||||
using ::testing::ExpectationSet; |
||||
... |
||||
ExpectationSet all_inits; |
||||
for (int i = 0; i < element_count; i++) { |
||||
all_inits += EXPECT_CALL(foo, InitElement(i)); |
||||
} |
||||
EXPECT_CALL(foo, Bar()) |
||||
.After(all_inits); |
||||
``` |
||||
says that `Bar()` can be called only after all elements have been |
||||
initialized (but we don't care about which elements get initialized |
||||
before the others). |
||||
|
||||
Modifying an `ExpectationSet` after using it in an `.After()` doesn't |
||||
affect the meaning of the `.After()`. |
||||
|
||||
## Sequences ## |
||||
|
||||
When you have a long chain of sequential expectations, it's easier to |
||||
specify the order using **sequences**, which don't require you to given |
||||
each expectation in the chain a different name. <i>All expected<br> |
||||
calls</i> in the same sequence must occur in the order they are |
||||
specified. |
||||
|
||||
``` |
||||
using ::testing::Sequence; |
||||
Sequence s1, s2; |
||||
... |
||||
EXPECT_CALL(foo, Reset()) |
||||
.InSequence(s1, s2) |
||||
.WillOnce(Return(true)); |
||||
EXPECT_CALL(foo, GetSize()) |
||||
.InSequence(s1) |
||||
.WillOnce(Return(1)); |
||||
EXPECT_CALL(foo, Describe(A<const char*>())) |
||||
.InSequence(s2) |
||||
.WillOnce(Return("dummy")); |
||||
``` |
||||
says that `Reset()` must be called before _both_ `GetSize()` _and_ |
||||
`Describe()`, and the latter two can occur in any order. |
||||
|
||||
To put many expectations in a sequence conveniently: |
||||
``` |
||||
using ::testing::InSequence; |
||||
{ |
||||
InSequence dummy; |
||||
|
||||
EXPECT_CALL(...)...; |
||||
EXPECT_CALL(...)...; |
||||
... |
||||
EXPECT_CALL(...)...; |
||||
} |
||||
``` |
||||
says that all expected calls in the scope of `dummy` must occur in |
||||
strict order. The name `dummy` is irrelevant.) |
||||
|
||||
# Verifying and Resetting a Mock # |
||||
|
||||
Google Mock will verify the expectations on a mock object when it is destructed, or you can do it earlier: |
||||
``` |
||||
using ::testing::Mock; |
||||
... |
||||
// Verifies and removes the expectations on mock_obj; |
||||
// returns true iff successful. |
||||
Mock::VerifyAndClearExpectations(&mock_obj); |
||||
... |
||||
// Verifies and removes the expectations on mock_obj; |
||||
// also removes the default actions set by ON_CALL(); |
||||
// returns true iff successful. |
||||
Mock::VerifyAndClear(&mock_obj); |
||||
``` |
||||
|
||||
You can also tell Google Mock that a mock object can be leaked and doesn't |
||||
need to be verified: |
||||
``` |
||||
Mock::AllowLeak(&mock_obj); |
||||
``` |
||||
|
||||
# Mock Classes # |
||||
|
||||
Google Mock defines a convenient mock class template |
||||
``` |
||||
class MockFunction<R(A1, ..., An)> { |
||||
public: |
||||
MOCK_METHODn(Call, R(A1, ..., An)); |
||||
}; |
||||
``` |
||||
See this [recipe](V1_5_CookBook#Using_Check_Points.md) for one application of it. |
||||
|
||||
# Flags # |
||||
|
||||
| `--gmock_catch_leaked_mocks=0` | Don't report leaked mock objects as failures. | |
||||
|:-------------------------------|:----------------------------------------------| |
||||
| `--gmock_verbose=LEVEL` | Sets the default verbosity level (`info`, `warning`, or `error`) of Google Mock messages. | |
File diff suppressed because it is too large
Load Diff
@ -1,11 +0,0 @@ |
||||
This page lists all documentation wiki pages for Google Mock **version 1.5.0** -- **if you use a different version of Google Mock, please read the documentation for that specific version instead.** |
||||
|
||||
* [ForDummies](V1_5_ForDummies.md) -- start here if you are new to Google Mock. |
||||
* [CheatSheet](V1_5_CheatSheet.md) -- a quick reference. |
||||
* [CookBook](V1_5_CookBook.md) -- recipes for doing various tasks using Google Mock. |
||||
* [FrequentlyAskedQuestions](V1_5_FrequentlyAskedQuestions.md) -- check here before asking a question on the mailing list. |
||||
|
||||
To contribute code to Google Mock, read: |
||||
|
||||
* DevGuide -- read this _before_ writing your first patch. |
||||
* [Pump Manual](http://code.google.com/p/googletest/wiki/PumpManual) -- how we generate some of Google Mock's source files. |
@ -1,439 +0,0 @@ |
||||
|
||||
|
||||
(**Note:** If you get compiler errors that you don't understand, be sure to consult [Google Mock Doctor](V1_5_FrequentlyAskedQuestions#How_am_I_supposed_to_make_sense_of_these_horrible_template_error.md).) |
||||
|
||||
# What Is Google C++ Mocking Framework? # |
||||
When you write a prototype or test, often it's not feasible or wise to rely on real objects entirely. A **mock object** implements the same interface as a real object (so it can be used as one), but lets you specify at run time how it will be used and what it should do (which methods will be called? in which order? how many times? with what arguments? what will they return? etc). |
||||
|
||||
**Note:** It is easy to confuse the term _fake objects_ with mock objects. Fakes and mocks actually mean very different things in the Test-Driven Development (TDD) community: |
||||
|
||||
* **Fake** objects have working implementations, but usually take some shortcut (perhaps to make the operations less expensive), which makes them not suitable for production. An in-memory file system would be an example of a fake. |
||||
* **Mocks** are objects pre-programmed with _expectations_, which form a specification of the calls they are expected to receive. |
||||
|
||||
If all this seems too abstract for you, don't worry - the most important thing to remember is that a mock allows you to check the _interaction_ between itself and code that uses it. The difference between fakes and mocks will become much clearer once you start to use mocks. |
||||
|
||||
**Google C++ Mocking Framework** (or **Google Mock** for short) is a library (sometimes we also call it a "framework" to make it sound cool) for creating mock classes and using them. It does to C++ what [jMock](http://www.jmock.org/) and [EasyMock](http://www.easymock.org/) do to Java. |
||||
|
||||
Using Google Mock involves three basic steps: |
||||
|
||||
1. Use some simple macros to describe the interface you want to mock, and they will expand to the implementation of your mock class; |
||||
1. Create some mock objects and specify its expectations and behavior using an intuitive syntax; |
||||
1. Exercise code that uses the mock objects. Google Mock will catch any violation of the expectations as soon as it arises. |
||||
|
||||
# Why Google Mock? # |
||||
While mock objects help you remove unnecessary dependencies in tests and make them fast and reliable, using mocks manually in C++ is _hard_: |
||||
|
||||
* Someone has to implement the mocks. The job is usually tedious and error-prone. No wonder people go great distance to avoid it. |
||||
* The quality of those manually written mocks is a bit, uh, unpredictable. You may see some really polished ones, but you may also see some that were hacked up in a hurry and have all sorts of ad hoc restrictions. |
||||
* The knowledge you gained from using one mock doesn't transfer to the next. |
||||
|
||||
In contrast, Java and Python programmers have some fine mock frameworks, which automate the creation of mocks. As a result, mocking is a proven effective technique and widely adopted practice in those communities. Having the right tool absolutely makes the difference. |
||||
|
||||
Google Mock was built to help C++ programmers. It was inspired by [jMock](http://www.jmock.org/) and [EasyMock](http://www.easymock.org/), but designed with C++'s specifics in mind. It is your friend if any of the following problems is bothering you: |
||||
|
||||
* You are stuck with a sub-optimal design and wish you had done more prototyping before it was too late, but prototyping in C++ is by no means "rapid". |
||||
* Your tests are slow as they depend on too many libraries or use expensive resources (e.g. a database). |
||||
* Your tests are brittle as some resources they use are unreliable (e.g. the network). |
||||
* You want to test how your code handles a failure (e.g. a file checksum error), but it's not easy to cause one. |
||||
* You need to make sure that your module interacts with other modules in the right way, but it's hard to observe the interaction; therefore you resort to observing the side effects at the end of the action, which is awkward at best. |
||||
* You want to "mock out" your dependencies, except that they don't have mock implementations yet; and, frankly, you aren't thrilled by some of those hand-written mocks. |
||||
|
||||
We encourage you to use Google Mock as: |
||||
|
||||
* a _design_ tool, for it lets you experiment with your interface design early and often. More iterations lead to better designs! |
||||
* a _testing_ tool to cut your tests' outbound dependencies and probe the interaction between your module and its collaborators. |
||||
|
||||
# Getting Started # |
||||
Using Google Mock is easy! Inside your C++ source file, just `#include` `<gtest/gtest.h>` and `<gmock/gmock.h>`, and you are ready to go. |
||||
|
||||
# A Case for Mock Turtles # |
||||
Let's look at an example. Suppose you are developing a graphics program that relies on a LOGO-like API for drawing. How would you test that it does the right thing? Well, you can run it and compare the screen with a golden screen snapshot, but let's admit it: tests like this are expensive to run and fragile (What if you just upgraded to a shiny new graphics card that has better anti-aliasing? Suddenly you have to update all your golden images.). It would be too painful if all your tests are like this. Fortunately, you learned about Dependency Injection and know the right thing to do: instead of having your application talk to the drawing API directly, wrap the API in an interface (say, `Turtle`) and code to that interface: |
||||
|
||||
``` |
||||
class Turtle { |
||||
... |
||||
virtual ~Turtle() {} |
||||
virtual void PenUp() = 0; |
||||
virtual void PenDown() = 0; |
||||
virtual void Forward(int distance) = 0; |
||||
virtual void Turn(int degrees) = 0; |
||||
virtual void GoTo(int x, int y) = 0; |
||||
virtual int GetX() const = 0; |
||||
virtual int GetY() const = 0; |
||||
}; |
||||
``` |
||||
|
||||
(Note that the destructor of `Turtle` **must** be virtual, as is the case for **all** classes you intend to inherit from - otherwise the destructor of the derived class will not be called when you delete an object through a base pointer, and you'll get corrupted program states like memory leaks.) |
||||
|
||||
You can control whether the turtle's movement will leave a trace using `PenUp()` and `PenDown()`, and control its movement using `Forward()`, `Turn()`, and `GoTo()`. Finally, `GetX()` and `GetY()` tell you the current position of the turtle. |
||||
|
||||
Your program will normally use a real implementation of this interface. In tests, you can use a mock implementation instead. This allows you to easily check what drawing primitives your program is calling, with what arguments, and in which order. Tests written this way are much more robust (they won't break because your new machine does anti-aliasing differently), easier to read and maintain (the intent of a test is expressed in the code, not in some binary images), and run _much, much faster_. |
||||
|
||||
# Writing the Mock Class # |
||||
If you are lucky, the mocks you need to use have already been implemented by some nice people. If, however, you find yourself in the position to write a mock class, relax - Google Mock turns this task into a fun game! (Well, almost.) |
||||
|
||||
## How to Define It ## |
||||
Using the `Turtle` interface as example, here are the simple steps you need to follow: |
||||
|
||||
1. Derive a class `MockTurtle` from `Turtle`. |
||||
1. Take a virtual function of `Turtle`. Count how many arguments it has. |
||||
1. In the `public:` section of the child class, write `MOCK_METHODn();` (or `MOCK_CONST_METHODn();` if you are mocking a `const` method), where `n` is the number of the arguments; if you counted wrong, shame on you, and a compiler error will tell you so. |
||||
1. Now comes the fun part: you take the function signature, cut-and-paste the _function name_ as the _first_ argument to the macro, and leave what's left as the _second_ argument (in case you're curious, this is the _type of the function_). |
||||
1. Repeat until all virtual functions you want to mock are done. |
||||
|
||||
After the process, you should have something like: |
||||
|
||||
``` |
||||
#include <gmock/gmock.h> // Brings in Google Mock. |
||||
class MockTurtle : public Turtle { |
||||
public: |
||||
... |
||||
MOCK_METHOD0(PenUp, void()); |
||||
MOCK_METHOD0(PenDown, void()); |
||||
MOCK_METHOD1(Forward, void(int distance)); |
||||
MOCK_METHOD1(Turn, void(int degrees)); |
||||
MOCK_METHOD2(GoTo, void(int x, int y)); |
||||
MOCK_CONST_METHOD0(GetX, int()); |
||||
MOCK_CONST_METHOD0(GetY, int()); |
||||
}; |
||||
``` |
||||
|
||||
You don't need to define these mock methods somewhere else - the `MOCK_METHOD*` macros will generate the definitions for you. It's that simple! Once you get the hang of it, you can pump out mock classes faster than your source-control system can handle your check-ins. |
||||
|
||||
**Tip:** If even this is too much work for you, you'll find the |
||||
`gmock_gen.py` tool in Google Mock's `scripts/generator/` directory (courtesy of the [cppclean](http://code.google.com/p/cppclean/) project) useful. This command-line |
||||
tool requires that you have Python 2.4 installed. You give it a C++ file and the name of an abstract class defined in it, |
||||
and it will print the definition of the mock class for you. Due to the |
||||
complexity of the C++ language, this script may not always work, but |
||||
it can be quite handy when it does. For more details, read the [user documentation](http://code.google.com/p/googlemock/source/browse/trunk/scripts/generator/README). |
||||
|
||||
## Where to Put It ## |
||||
When you define a mock class, you need to decide where to put its definition. Some people put it in a `*_test.cc`. This is fine when the interface being mocked (say, `Foo`) is owned by the same person or team. Otherwise, when the owner of `Foo` changes it, your test could break. (You can't really expect `Foo`'s maintainer to fix every test that uses `Foo`, can you?) |
||||
|
||||
So, the rule of thumb is: if you need to mock `Foo` and it's owned by others, define the mock class in `Foo`'s package (better, in a `testing` sub-package such that you can clearly separate production code and testing utilities), and put it in a `mock_foo.h`. Then everyone can reference `mock_foo.h` from their tests. If `Foo` ever changes, there is only one copy of `MockFoo` to change, and only tests that depend on the changed methods need to be fixed. |
||||
|
||||
Another way to do it: you can introduce a thin layer `FooAdaptor` on top of `Foo` and code to this new interface. Since you own `FooAdaptor`, you can absorb changes in `Foo` much more easily. While this is more work initially, carefully choosing the adaptor interface can make your code easier to write and more readable (a net win in the long run), as you can choose `FooAdaptor` to fit your specific domain much better than `Foo` does. |
||||
|
||||
# Using Mocks in Tests # |
||||
Once you have a mock class, using it is easy. The typical work flow is: |
||||
|
||||
1. Import the Google Mock names from the `testing` namespace such that you can use them unqualified (You only have to do it once per file. Remember that namespaces are a good idea and good for your health.). |
||||
1. Create some mock objects. |
||||
1. Specify your expectations on them (How many times will a method be called? With what arguments? What should it do? etc.). |
||||
1. Exercise some code that uses the mocks; optionally, check the result using Google Test assertions. If a mock method is called more than expected or with wrong arguments, you'll get an error immediately. |
||||
1. When a mock is destructed, Google Mock will automatically check whether all expectations on it have been satisfied. |
||||
|
||||
Here's an example: |
||||
|
||||
``` |
||||
#include "path/to/mock-turtle.h" |
||||
#include <gmock/gmock.h> |
||||
#include <gtest/gtest.h> |
||||
using ::testing::AtLeast; // #1 |
||||
|
||||
TEST(PainterTest, CanDrawSomething) { |
||||
MockTurtle turtle; // #2 |
||||
EXPECT_CALL(turtle, PenDown()) // #3 |
||||
.Times(AtLeast(1)); |
||||
|
||||
Painter painter(&turtle); // #4 |
||||
|
||||
EXPECT_TRUE(painter.DrawCircle(0, 0, 10)); |
||||
} // #5 |
||||
|
||||
int main(int argc, char** argv) { |
||||
// The following line must be executed to initialize Google Mock |
||||
// (and Google Test) before running the tests. |
||||
::testing::InitGoogleMock(&argc, argv); |
||||
return RUN_ALL_TESTS(); |
||||
} |
||||
``` |
||||
|
||||
As you might have guessed, this test checks that `PenDown()` is called at least once. If the `painter` object didn't call this method, your test will fail with a message like this: |
||||
|
||||
``` |
||||
path/to/my_test.cc:119: Failure |
||||
Actual function call count doesn't match this expectation: |
||||
Actually: never called; |
||||
Expected: called at least once. |
||||
``` |
||||
|
||||
**Tip 1:** If you run the test from an Emacs buffer, you can hit `<Enter>` on the line number displayed in the error message to jump right to the failed expectation. |
||||
|
||||
**Tip 2:** If your mock objects are never deleted, the final verification won't happen. Therefore it's a good idea to use a heap leak checker in your tests when you allocate mocks on the heap. |
||||
|
||||
**Important note:** Google Mock requires expectations to be set **before** the mock functions are called, otherwise the behavior is **undefined**. In particular, you mustn't interleave `EXPECT_CALL()`s and calls to the mock functions. |
||||
|
||||
This means `EXPECT_CALL()` should be read as expecting that a call will occur _in the future_, not that a call has occurred. Why does Google Mock work like that? Well, specifying the expectation beforehand allows Google Mock to report a violation as soon as it arises, when the context (stack trace, etc) is still available. This makes debugging much easier. |
||||
|
||||
Admittedly, this test is contrived and doesn't do much. You can easily achieve the same effect without using Google Mock. However, as we shall reveal soon, Google Mock allows you to do _much more_ with the mocks. |
||||
|
||||
## Using Google Mock with Any Testing Framework ## |
||||
If you want to use something other than Google Test (e.g. [CppUnit](http://apps.sourceforge.net/mediawiki/cppunit/index.php?title=Main_Page) or |
||||
[CxxTest](http://cxxtest.tigris.org/)) as your testing framework, just change the `main()` function in the previous section to: |
||||
``` |
||||
int main(int argc, char** argv) { |
||||
// The following line causes Google Mock to throw an exception on failure, |
||||
// which will be interpreted by your testing framework as a test failure. |
||||
::testing::GTEST_FLAG(throw_on_failure) = true; |
||||
::testing::InitGoogleMock(&argc, argv); |
||||
... whatever your testing framework requires ... |
||||
} |
||||
``` |
||||
|
||||
This approach has a catch: it makes Google Mock throw an exception |
||||
from a mock object's destructor sometimes. With some compilers, this |
||||
sometimes causes the test program to crash. You'll still be able to |
||||
notice that the test has failed, but it's not a graceful failure. |
||||
|
||||
A better solution is to use Google Test's |
||||
[event listener API](http://code.google.com/p/googletest/wiki/GoogleTestAdvancedGuide#Extending_Google_Test_by_Handling_Test_Events) |
||||
to report a test failure to your testing framework properly. You'll need to |
||||
implement the `OnTestPartResult()` method of the event listener interface, but it |
||||
should be straightforward. |
||||
|
||||
If this turns out to be too much work, we suggest that you stick with |
||||
Google Test, which works with Google Mock seamlessly (in fact, it is |
||||
technically part of Google Mock.). If there is a reason that you |
||||
cannot use Google Test, please let us know. |
||||
|
||||
# Setting Expectations # |
||||
The key to using a mock object successfully is to set the _right expectations_ on it. If you set the expectations too strict, your test will fail as the result of unrelated changes. If you set them too loose, bugs can slip through. You want to do it just right such that your test can catch exactly the kind of bugs you intend it to catch. Google Mock provides the necessary means for you to do it "just right." |
||||
|
||||
## General Syntax ## |
||||
In Google Mock we use the `EXPECT_CALL()` macro to set an expectation on a mock method. The general syntax is: |
||||
|
||||
``` |
||||
EXPECT_CALL(mock_object, method(matchers)) |
||||
.Times(cardinality) |
||||
.WillOnce(action) |
||||
.WillRepeatedly(action); |
||||
``` |
||||
|
||||
The macro has two arguments: first the mock object, and then the method and its arguments. Note that the two are separated by a comma (`,`), not a period (`.`). (Why using a comma? The answer is that it was necessary for technical reasons.) |
||||
|
||||
The macro can be followed by some optional _clauses_ that provide more information about the expectation. We'll discuss how each clause works in the coming sections. |
||||
|
||||
This syntax is designed to make an expectation read like English. For example, you can probably guess that |
||||
|
||||
``` |
||||
using ::testing::Return;... |
||||
EXPECT_CALL(turtle, GetX()) |
||||
.Times(5) |
||||
.WillOnce(Return(100)) |
||||
.WillOnce(Return(150)) |
||||
.WillRepeatedly(Return(200)); |
||||
``` |
||||
|
||||
says that the `turtle` object's `GetX()` method will be called five times, it will return 100 the first time, 150 the second time, and then 200 every time. Some people like to call this style of syntax a Domain-Specific Language (DSL). |
||||
|
||||
**Note:** Why do we use a macro to do this? It serves two purposes: first it makes expectations easily identifiable (either by `grep` or by a human reader), and second it allows Google Mock to include the source file location of a failed expectation in messages, making debugging easier. |
||||
|
||||
## Matchers: What Arguments Do We Expect? ## |
||||
When a mock function takes arguments, we must specify what arguments we are expecting; for example: |
||||
|
||||
``` |
||||
// Expects the turtle to move forward by 100 units. |
||||
EXPECT_CALL(turtle, Forward(100)); |
||||
``` |
||||
|
||||
Sometimes you may not want to be too specific (Remember that talk about tests being too rigid? Over specification leads to brittle tests and obscures the intent of tests. Therefore we encourage you to specify only what's necessary - no more, no less.). If you care to check that `Forward()` will be called but aren't interested in its actual argument, write `_` as the argument, which means "anything goes": |
||||
|
||||
``` |
||||
using ::testing::_; |
||||
... |
||||
// Expects the turtle to move forward. |
||||
EXPECT_CALL(turtle, Forward(_)); |
||||
``` |
||||
|
||||
`_` is an instance of what we call **matchers**. A matcher is like a predicate and can test whether an argument is what we'd expect. You can use a matcher inside `EXPECT_CALL()` wherever a function argument is expected. |
||||
|
||||
A list of built-in matchers can be found in the [CheatSheet](V1_5_CheatSheet.md). For example, here's the `Ge` (greater than or equal) matcher: |
||||
|
||||
``` |
||||
using ::testing::Ge;... |
||||
EXPECT_CALL(turtle, Forward(Ge(100))); |
||||
``` |
||||
|
||||
This checks that the turtle will be told to go forward by at least 100 units. |
||||
|
||||
## Cardinalities: How Many Times Will It Be Called? ## |
||||
The first clause we can specify following an `EXPECT_CALL()` is `Times()`. We call its argument a **cardinality** as it tells _how many times_ the call should occur. It allows us to repeat an expectation many times without actually writing it as many times. More importantly, a cardinality can be "fuzzy", just like a matcher can be. This allows a user to express the intent of a test exactly. |
||||
|
||||
An interesting special case is when we say `Times(0)`. You may have guessed - it means that the function shouldn't be called with the given arguments at all, and Google Mock will report a Google Test failure whenever the function is (wrongfully) called. |
||||
|
||||
We've seen `AtLeast(n)` as an example of fuzzy cardinalities earlier. For the list of built-in cardinalities you can use, see the [CheatSheet](V1_5_CheatSheet.md). |
||||
|
||||
The `Times()` clause can be omitted. **If you omit `Times()`, Google Mock will infer the cardinality for you.** The rules are easy to remember: |
||||
|
||||
* If **neither** `WillOnce()` **nor** `WillRepeatedly()` is in the `EXPECT_CALL()`, the inferred cardinality is `Times(1)`. |
||||
* If there are `n WillOnce()`'s but **no** `WillRepeatedly()`, where `n` >= 1, the cardinality is `Times(n)`. |
||||
* If there are `n WillOnce()`'s and **one** `WillRepeatedly()`, where `n` >= 0, the cardinality is `Times(AtLeast(n))`. |
||||
|
||||
**Quick quiz:** what do you think will happen if a function is expected to be called twice but actually called four times? |
||||
|
||||
## Actions: What Should It Do? ## |
||||
Remember that a mock object doesn't really have a working implementation? We as users have to tell it what to do when a method is invoked. This is easy in Google Mock. |
||||
|
||||
First, if the return type of a mock function is a built-in type or a pointer, the function has a **default action** (a `void` function will just return, a `bool` function will return `false`, and other functions will return 0). If you don't say anything, this behavior will be used. |
||||
|
||||
Second, if a mock function doesn't have a default action, or the default action doesn't suit you, you can specify the action to be taken each time the expectation matches using a series of `WillOnce()` clauses followed by an optional `WillRepeatedly()`. For example, |
||||
|
||||
``` |
||||
using ::testing::Return;... |
||||
EXPECT_CALL(turtle, GetX()) |
||||
.WillOnce(Return(100)) |
||||
.WillOnce(Return(200)) |
||||
.WillOnce(Return(300)); |
||||
``` |
||||
|
||||
This says that `turtle.GetX()` will be called _exactly three times_ (Google Mock inferred this from how many `WillOnce()` clauses we've written, since we didn't explicitly write `Times()`), and will return 100, 200, and 300 respectively. |
||||
|
||||
``` |
||||
using ::testing::Return;... |
||||
EXPECT_CALL(turtle, GetY()) |
||||
.WillOnce(Return(100)) |
||||
.WillOnce(Return(200)) |
||||
.WillRepeatedly(Return(300)); |
||||
``` |
||||
|
||||
says that `turtle.GetY()` will be called _at least twice_ (Google Mock knows this as we've written two `WillOnce()` clauses and a `WillRepeatedly()` while having no explicit `Times()`), will return 100 the first time, 200 the second time, and 300 from the third time on. |
||||
|
||||
Of course, if you explicitly write a `Times()`, Google Mock will not try to infer the cardinality itself. What if the number you specified is larger than there are `WillOnce()` clauses? Well, after all `WillOnce()`s are used up, Google Mock will do the _default_ action for the function every time (unless, of course, you have a `WillRepeatedly()`.). |
||||
|
||||
What can we do inside `WillOnce()` besides `Return()`? You can return a reference using `ReturnRef(variable)`, or invoke a pre-defined function, among [others](V1_5_CheatSheet#Actions.md). |
||||
|
||||
**Important note:** The `EXPECT_CALL()` statement evaluates the action clause only once, even though the action may be performed many times. Therefore you must be careful about side effects. The following may not do what you want: |
||||
|
||||
``` |
||||
int n = 100; |
||||
EXPECT_CALL(turtle, GetX()) |
||||
.Times(4) |
||||
.WillOnce(Return(n++)); |
||||
``` |
||||
|
||||
Instead of returning 100, 101, 102, ..., consecutively, this mock function will always return 100 as `n++` is only evaluated once. Similarly, `Return(new Foo)` will create a new `Foo` object when the `EXPECT_CALL()` is executed, and will return the same pointer every time. If you want the side effect to happen every time, you need to define a custom action, which we'll teach in the [CookBook](V1_5_CookBook.md). |
||||
|
||||
Time for another quiz! What do you think the following means? |
||||
|
||||
``` |
||||
using ::testing::Return;... |
||||
EXPECT_CALL(turtle, GetY()) |
||||
.Times(4) |
||||
.WillOnce(Return(100)); |
||||
``` |
||||
|
||||
Obviously `turtle.GetY()` is expected to be called four times. But if you think it will return 100 every time, think twice! Remember that one `WillOnce()` clause will be consumed each time the function is invoked and the default action will be taken afterwards. So the right answer is that `turtle.GetY()` will return 100 the first time, but **return 0 from the second time on**, as returning 0 is the default action for `int` functions. |
||||
|
||||
## Using Multiple Expectations ## |
||||
So far we've only shown examples where you have a single expectation. More realistically, you're going to specify expectations on multiple mock methods, which may be from multiple mock objects. |
||||
|
||||
By default, when a mock method is invoked, Google Mock will search the expectations in the **reverse order** they are defined, and stop when an active expectation that matches the arguments is found (you can think of it as "newer rules override older ones."). If the matching expectation cannot take any more calls, you will get an upper-bound-violated failure. Here's an example: |
||||
|
||||
``` |
||||
using ::testing::_;... |
||||
EXPECT_CALL(turtle, Forward(_)); // #1 |
||||
EXPECT_CALL(turtle, Forward(10)) // #2 |
||||
.Times(2); |
||||
``` |
||||
|
||||
If `Forward(10)` is called three times in a row, the third time it will be an error, as the last matching expectation (#2) has been saturated. If, however, the third `Forward(10)` call is replaced by `Forward(20)`, then it would be OK, as now #1 will be the matching expectation. |
||||
|
||||
**Side note:** Why does Google Mock search for a match in the _reverse_ order of the expectations? The reason is that this allows a user to set up the default expectations in a mock object's constructor or the test fixture's set-up phase and then customize the mock by writing more specific expectations in the test body. So, if you have two expectations on the same method, you want to put the one with more specific matchers **after** the other, or the more specific rule would be shadowed by the more general one that comes after it. |
||||
|
||||
## Ordered vs Unordered Calls ## |
||||
By default, an expectation can match a call even though an earlier expectation hasn't been satisfied. In other words, the calls don't have to occur in the order the expectations are specified. |
||||
|
||||
Sometimes, you may want all the expected calls to occur in a strict order. To say this in Google Mock is easy: |
||||
|
||||
``` |
||||
using ::testing::InSequence;... |
||||
TEST(FooTest, DrawsLineSegment) { |
||||
... |
||||
{ |
||||
InSequence dummy; |
||||
|
||||
EXPECT_CALL(turtle, PenDown()); |
||||
EXPECT_CALL(turtle, Forward(100)); |
||||
EXPECT_CALL(turtle, PenUp()); |
||||
} |
||||
Foo(); |
||||
} |
||||
``` |
||||
|
||||
By creating an object of type `InSequence`, all expectations in its scope are put into a _sequence_ and have to occur _sequentially_. Since we are just relying on the constructor and destructor of this object to do the actual work, its name is really irrelevant. |
||||
|
||||
In this example, we test that `Foo()` calls the three expected functions in the order as written. If a call is made out-of-order, it will be an error. |
||||
|
||||
(What if you care about the relative order of some of the calls, but not all of them? Can you specify an arbitrary partial order? The answer is ... yes! If you are impatient, the details can be found in the [CookBook](V1_5_CookBook.md).) |
||||
|
||||
## All Expectations Are Sticky (Unless Said Otherwise) ## |
||||
Now let's do a quick quiz to see how well you can use this mock stuff already. How would you test that the turtle is asked to go to the origin _exactly twice_ (you want to ignore any other instructions it receives)? |
||||
|
||||
After you've come up with your answer, take a look at ours and compare notes (solve it yourself first - don't cheat!): |
||||
|
||||
``` |
||||
using ::testing::_;... |
||||
EXPECT_CALL(turtle, GoTo(_, _)) // #1 |
||||
.Times(AnyNumber()); |
||||
EXPECT_CALL(turtle, GoTo(0, 0)) // #2 |
||||
.Times(2); |
||||
``` |
||||
|
||||
Suppose `turtle.GoTo(0, 0)` is called three times. In the third time, Google Mock will see that the arguments match expectation #2 (remember that we always pick the last matching expectation). Now, since we said that there should be only two such calls, Google Mock will report an error immediately. This is basically what we've told you in the "Using Multiple Expectations" section above. |
||||
|
||||
This example shows that **expectations in Google Mock are "sticky" by default**, in the sense that they remain active even after we have reached their invocation upper bounds. This is an important rule to remember, as it affects the meaning of the spec, and is **different** to how it's done in many other mocking frameworks (Why'd we do that? Because we think our rule makes the common cases easier to express and understand.). |
||||
|
||||
Simple? Let's see if you've really understood it: what does the following code say? |
||||
|
||||
``` |
||||
using ::testing::Return; |
||||
... |
||||
for (int i = n; i > 0; i--) { |
||||
EXPECT_CALL(turtle, GetX()) |
||||
.WillOnce(Return(10*i)); |
||||
} |
||||
``` |
||||
|
||||
If you think it says that `turtle.GetX()` will be called `n` times and will return 10, 20, 30, ..., consecutively, think twice! The problem is that, as we said, expectations are sticky. So, the second time `turtle.GetX()` is called, the last (latest) `EXPECT_CALL()` statement will match, and will immediately lead to an "upper bound exceeded" error - this piece of code is not very useful! |
||||
|
||||
One correct way of saying that `turtle.GetX()` will return 10, 20, 30, ..., is to explicitly say that the expectations are _not_ sticky. In other words, they should _retire_ as soon as they are saturated: |
||||
|
||||
``` |
||||
using ::testing::Return; |
||||
... |
||||
for (int i = n; i > 0; i--) { |
||||
EXPECT_CALL(turtle, GetX()) |
||||
.WillOnce(Return(10*i)) |
||||
.RetiresOnSaturation(); |
||||
} |
||||
``` |
||||
|
||||
And, there's a better way to do it: in this case, we expect the calls to occur in a specific order, and we line up the actions to match the order. Since the order is important here, we should make it explicit using a sequence: |
||||
|
||||
``` |
||||
using ::testing::InSequence; |
||||
using ::testing::Return; |
||||
... |
||||
{ |
||||
InSequence s; |
||||
|
||||
for (int i = 1; i <= n; i++) { |
||||
EXPECT_CALL(turtle, GetX()) |
||||
.WillOnce(Return(10*i)) |
||||
.RetiresOnSaturation(); |
||||
} |
||||
} |
||||
``` |
||||
|
||||
By the way, the other situation where an expectation may _not_ be sticky is when it's in a sequence - as soon as another expectation that comes after it in the sequence has been used, it automatically retires (and will never be used to match any call). |
||||
|
||||
## Uninteresting Calls ## |
||||
A mock object may have many methods, and not all of them are that interesting. For example, in some tests we may not care about how many times `GetX()` and `GetY()` get called. |
||||
|
||||
In Google Mock, if you are not interested in a method, just don't say anything about it. If a call to this method occurs, you'll see a warning in the test output, but it won't be a failure. |
||||
|
||||
# What Now? # |
||||
Congratulations! You've learned enough about Google Mock to start using it. Now, you might want to join the [googlemock](http://groups.google.com/group/googlemock) discussion group and actually write some tests using Google Mock - it will be fun. Hey, it may even be addictive - you've been warned. |
||||
|
||||
Then, if you feel like increasing your mock quotient, you should move on to the [CookBook](V1_5_CookBook.md). You can learn many advanced features of Google Mock there -- and advance your level of enjoyment and testing bliss. |
@ -1,624 +0,0 @@ |
||||
|
||||
|
||||
Please send your questions to the |
||||
[googlemock](http://groups.google.com/group/googlemock) discussion |
||||
group. If you need help with compiler errors, make sure you have |
||||
tried [Google Mock Doctor](#How_am_I_supposed_to_make_sense_of_these_horrible_template_error.md) first. |
||||
|
||||
## I wrote some matchers. After I upgraded to a new version of Google Mock, they no longer compile. What's going on? ## |
||||
|
||||
After version 1.4.0 of Google Mock was released, we had an idea on how |
||||
to make it easier to write matchers that can generate informative |
||||
messages efficiently. We experimented with this idea and liked what |
||||
we saw. Therefore we decided to implement it. |
||||
|
||||
Unfortunately, this means that if you have defined your own matchers |
||||
by implementing `MatcherInterface` or using `MakePolymorphicMatcher()`, |
||||
your definitions will no longer compile. Matchers defined using the |
||||
`MATCHER*` family of macros are not affected. |
||||
|
||||
Sorry for the hassle if your matchers are affected. We believe it's |
||||
in everyone's long-term interest to make this change sooner than |
||||
later. Fortunately, it's usually not hard to migrate an existing |
||||
matcher to the new API. Here's what you need to do: |
||||
|
||||
If you wrote your matcher like this: |
||||
``` |
||||
// Old matcher definition that doesn't work with the latest |
||||
// Google Mock. |
||||
using ::testing::MatcherInterface; |
||||
... |
||||
class MyWonderfulMatcher : public MatcherInterface<MyType> { |
||||
public: |
||||
... |
||||
virtual bool Matches(MyType value) const { |
||||
// Returns true if value matches. |
||||
return value.GetFoo() > 5; |
||||
} |
||||
... |
||||
}; |
||||
``` |
||||
|
||||
you'll need to change it to: |
||||
``` |
||||
// New matcher definition that works with the latest Google Mock. |
||||
using ::testing::MatcherInterface; |
||||
using ::testing::MatchResultListener; |
||||
... |
||||
class MyWonderfulMatcher : public MatcherInterface<MyType> { |
||||
public: |
||||
... |
||||
virtual bool MatchAndExplain(MyType value, |
||||
MatchResultListener* listener) const { |
||||
// Returns true if value matches. |
||||
return value.GetFoo() > 5; |
||||
} |
||||
... |
||||
}; |
||||
``` |
||||
(i.e. rename `Matches()` to `MatchAndExplain()` and give it a second |
||||
argument of type `MatchResultListener*`.) |
||||
|
||||
If you were also using `ExplainMatchResultTo()` to improve the matcher |
||||
message: |
||||
``` |
||||
// Old matcher definition that doesn't work with the lastest |
||||
// Google Mock. |
||||
using ::testing::MatcherInterface; |
||||
... |
||||
class MyWonderfulMatcher : public MatcherInterface<MyType> { |
||||
public: |
||||
... |
||||
virtual bool Matches(MyType value) const { |
||||
// Returns true if value matches. |
||||
return value.GetFoo() > 5; |
||||
} |
||||
|
||||
virtual void ExplainMatchResultTo(MyType value, |
||||
::std::ostream* os) const { |
||||
// Prints some helpful information to os to help |
||||
// a user understand why value matches (or doesn't match). |
||||
*os << "the Foo property is " << value.GetFoo(); |
||||
} |
||||
... |
||||
}; |
||||
``` |
||||
|
||||
you should move the logic of `ExplainMatchResultTo()` into |
||||
`MatchAndExplain()`, using the `MatchResultListener` argument where |
||||
the `::std::ostream` was used: |
||||
``` |
||||
// New matcher definition that works with the latest Google Mock. |
||||
using ::testing::MatcherInterface; |
||||
using ::testing::MatchResultListener; |
||||
... |
||||
class MyWonderfulMatcher : public MatcherInterface<MyType> { |
||||
public: |
||||
... |
||||
virtual bool MatchAndExplain(MyType value, |
||||
MatchResultListener* listener) const { |
||||
// Returns true if value matches. |
||||
*listener << "the Foo property is " << value.GetFoo(); |
||||
return value.GetFoo() > 5; |
||||
} |
||||
... |
||||
}; |
||||
``` |
||||
|
||||
If your matcher is defined using `MakePolymorphicMatcher()`: |
||||
``` |
||||
// Old matcher definition that doesn't work with the latest |
||||
// Google Mock. |
||||
using ::testing::MakePolymorphicMatcher; |
||||
... |
||||
class MyGreatMatcher { |
||||
public: |
||||
... |
||||
bool Matches(MyType value) const { |
||||
// Returns true if value matches. |
||||
return value.GetBar() < 42; |
||||
} |
||||
... |
||||
}; |
||||
... MakePolymorphicMatcher(MyGreatMatcher()) ... |
||||
``` |
||||
|
||||
you should rename the `Matches()` method to `MatchAndExplain()` and |
||||
add a `MatchResultListener*` argument (the same as what you need to do |
||||
for matchers defined by implementing `MatcherInterface`): |
||||
``` |
||||
// New matcher definition that works with the latest Google Mock. |
||||
using ::testing::MakePolymorphicMatcher; |
||||
using ::testing::MatchResultListener; |
||||
... |
||||
class MyGreatMatcher { |
||||
public: |
||||
... |
||||
bool MatchAndExplain(MyType value, |
||||
MatchResultListener* listener) const { |
||||
// Returns true if value matches. |
||||
return value.GetBar() < 42; |
||||
} |
||||
... |
||||
}; |
||||
... MakePolymorphicMatcher(MyGreatMatcher()) ... |
||||
``` |
||||
|
||||
If your polymorphic matcher uses `ExplainMatchResultTo()` for better |
||||
failure messages: |
||||
``` |
||||
// Old matcher definition that doesn't work with the latest |
||||
// Google Mock. |
||||
using ::testing::MakePolymorphicMatcher; |
||||
... |
||||
class MyGreatMatcher { |
||||
public: |
||||
... |
||||
bool Matches(MyType value) const { |
||||
// Returns true if value matches. |
||||
return value.GetBar() < 42; |
||||
} |
||||
... |
||||
}; |
||||
void ExplainMatchResultTo(const MyGreatMatcher& matcher, |
||||
MyType value, |
||||
::std::ostream* os) { |
||||
// Prints some helpful information to os to help |
||||
// a user understand why value matches (or doesn't match). |
||||
*os << "the Bar property is " << value.GetBar(); |
||||
} |
||||
... MakePolymorphicMatcher(MyGreatMatcher()) ... |
||||
``` |
||||
|
||||
you'll need to move the logic inside `ExplainMatchResultTo()` to |
||||
`MatchAndExplain()`: |
||||
``` |
||||
// New matcher definition that works with the latest Google Mock. |
||||
using ::testing::MakePolymorphicMatcher; |
||||
using ::testing::MatchResultListener; |
||||
... |
||||
class MyGreatMatcher { |
||||
public: |
||||
... |
||||
bool MatchAndExplain(MyType value, |
||||
MatchResultListener* listener) const { |
||||
// Returns true if value matches. |
||||
*listener << "the Bar property is " << value.GetBar(); |
||||
return value.GetBar() < 42; |
||||
} |
||||
... |
||||
}; |
||||
... MakePolymorphicMatcher(MyGreatMatcher()) ... |
||||
``` |
||||
|
||||
For more information, you can read these |
||||
[two](V1_5_CookBook#Writing_New_Monomorphic_Matchers.md) |
||||
[recipes](V1_5_CookBook#Writing_New_Polymorphic_Matchers.md) |
||||
from the cookbook. As always, you |
||||
are welcome to post questions on `googlemock@googlegroups.com` if you |
||||
need any help. |
||||
|
||||
## When using Google Mock, do I have to use Google Test as the testing framework? I have my favorite testing framework and don't want to switch. ## |
||||
|
||||
Google Mock works out of the box with Google Test. However, it's easy |
||||
to configure it to work with any testing framework of your choice. |
||||
[Here](V1_5_ForDummies#Using_Google_Mock_with_Any_Testing_Framework.md) is how. |
||||
|
||||
## How am I supposed to make sense of these horrible template errors? ## |
||||
|
||||
If you are confused by the compiler errors gcc threw at you, |
||||
try consulting the _Google Mock Doctor_ tool first. What it does is to |
||||
scan stdin for gcc error messages, and spit out diagnoses on the |
||||
problems (we call them diseases) your code has. |
||||
|
||||
To "install", run command: |
||||
``` |
||||
alias gmd='<path to googlemock>/scripts/gmock_doctor.py' |
||||
``` |
||||
|
||||
To use it, do: |
||||
``` |
||||
<your-favorite-build-command> <your-test> 2>&1 | gmd |
||||
``` |
||||
|
||||
For example: |
||||
``` |
||||
make my_test 2>&1 | gmd |
||||
``` |
||||
|
||||
Or you can run `gmd` and copy-n-paste gcc's error messages to it. |
||||
|
||||
## Can I mock a variadic function? ## |
||||
|
||||
You cannot mock a variadic function (i.e. a function taking ellipsis |
||||
(`...`) arguments) directly in Google Mock. |
||||
|
||||
The problem is that in general, there is _no way_ for a mock object to |
||||
know how many arguments are passed to the variadic method, and what |
||||
the arguments' types are. Only the _author of the base class_ knows |
||||
the protocol, and we cannot look into his head. |
||||
|
||||
Therefore, to mock such a function, the _user_ must teach the mock |
||||
object how to figure out the number of arguments and their types. One |
||||
way to do it is to provide overloaded versions of the function. |
||||
|
||||
Ellipsis arguments are inherited from C and not really a C++ feature. |
||||
They are unsafe to use and don't work with arguments that have |
||||
constructors or destructors. Therefore we recommend to avoid them in |
||||
C++ as much as possible. |
||||
|
||||
## MSVC gives me warning C4301 or C4373 when I define a mock method with a const parameter. Why? ## |
||||
|
||||
If you compile this using Microsoft Visual C++ 2005 SP1: |
||||
``` |
||||
class Foo { |
||||
... |
||||
virtual void Bar(const int i) = 0; |
||||
}; |
||||
|
||||
class MockFoo : public Foo { |
||||
... |
||||
MOCK_METHOD1(Bar, void(const int i)); |
||||
}; |
||||
``` |
||||
You may get the following warning: |
||||
``` |
||||
warning C4301: 'MockFoo::Bar': overriding virtual function only differs from 'Foo::Bar' by const/volatile qualifier |
||||
``` |
||||
|
||||
This is a MSVC bug. The same code compiles fine with gcc ,for |
||||
example. If you use Visual C++ 2008 SP1, you would get the warning: |
||||
``` |
||||
warning C4373: 'MockFoo::Bar': virtual function overrides 'Foo::Bar', previous versions of the compiler did not override when parameters only differed by const/volatile qualifiers |
||||
``` |
||||
|
||||
In C++, if you _declare_ a function with a `const` parameter, the |
||||
`const` modifier is _ignored_. Therefore, the `Foo` base class above |
||||
is equivalent to: |
||||
``` |
||||
class Foo { |
||||
... |
||||
virtual void Bar(int i) = 0; // int or const int? Makes no difference. |
||||
}; |
||||
``` |
||||
|
||||
In fact, you can _declare_ Bar() with an `int` parameter, and _define_ |
||||
it with a `const int` parameter. The compiler will still match them |
||||
up. |
||||
|
||||
Since making a parameter `const` is meaningless in the method |
||||
_declaration_, we recommend to remove it in both `Foo` and `MockFoo`. |
||||
That should workaround the VC bug. |
||||
|
||||
Note that we are talking about the _top-level_ `const` modifier here. |
||||
If the function parameter is passed by pointer or reference, declaring |
||||
the _pointee_ or _referee_ as `const` is still meaningful. For |
||||
example, the following two declarations are _not_ equivalent: |
||||
``` |
||||
void Bar(int* p); // Neither p nor *p is const. |
||||
void Bar(const int* p); // p is not const, but *p is. |
||||
``` |
||||
|
||||
## I have a huge mock class, and Microsoft Visual C++ runs out of memory when compiling it. What can I do? ## |
||||
|
||||
We've noticed that when the `/clr` compiler flag is used, Visual C++ |
||||
uses 5~6 times as much memory when compiling a mock class. We suggest |
||||
to avoid `/clr` when compiling native C++ mocks. |
||||
|
||||
## I can't figure out why Google Mock thinks my expectations are not satisfied. What should I do? ## |
||||
|
||||
You might want to run your test with |
||||
`--gmock_verbose=info`. This flag lets Google Mock print a trace |
||||
of every mock function call it receives. By studying the trace, |
||||
you'll gain insights on why the expectations you set are not met. |
||||
|
||||
## How can I assert that a function is NEVER called? ## |
||||
|
||||
``` |
||||
EXPECT_CALL(foo, Bar(_)) |
||||
.Times(0); |
||||
``` |
||||
|
||||
## I have a failed test where Google Mock tells me TWICE that a particular expectation is not satisfied. Isn't this redundant? ## |
||||
|
||||
When Google Mock detects a failure, it prints relevant information |
||||
(the mock function arguments, the state of relevant expectations, and |
||||
etc) to help the user debug. If another failure is detected, Google |
||||
Mock will do the same, including printing the state of relevant |
||||
expectations. |
||||
|
||||
Sometimes an expectation's state didn't change between two failures, |
||||
and you'll see the same description of the state twice. They are |
||||
however _not_ redundant, as they refer to _different points in time_. |
||||
The fact they are the same _is_ interesting information. |
||||
|
||||
## I get a heap check failure when using a mock object, but using a real object is fine. What can be wrong? ## |
||||
|
||||
Does the class (hopefully a pure interface) you are mocking have a |
||||
virtual destructor? |
||||
|
||||
Whenever you derive from a base class, make sure its destructor is |
||||
virtual. Otherwise Bad Things will happen. Consider the following |
||||
code: |
||||
|
||||
``` |
||||
class Base { |
||||
public: |
||||
// Not virtual, but should be. |
||||
~Base() { ... } |
||||
... |
||||
}; |
||||
|
||||
class Derived : public Base { |
||||
public: |
||||
... |
||||
private: |
||||
std::string value_; |
||||
}; |
||||
|
||||
... |
||||
Base* p = new Derived; |
||||
... |
||||
delete p; // Surprise! ~Base() will be called, but ~Derived() will not |
||||
// - value_ is leaked. |
||||
``` |
||||
|
||||
By changing `~Base()` to virtual, `~Derived()` will be correctly |
||||
called when `delete p` is executed, and the heap checker |
||||
will be happy. |
||||
|
||||
## The "newer expectations override older ones" rule makes writing expectations awkward. Why does Google Mock do that? ## |
||||
|
||||
When people complain about this, often they are referring to code like: |
||||
|
||||
``` |
||||
// foo.Bar() should be called twice, return 1 the first time, and return |
||||
// 2 the second time. However, I have to write the expectations in the |
||||
// reverse order. This sucks big time!!! |
||||
EXPECT_CALL(foo, Bar()) |
||||
.WillOnce(Return(2)) |
||||
.RetiresOnSaturation(); |
||||
EXPECT_CALL(foo, Bar()) |
||||
.WillOnce(Return(1)) |
||||
.RetiresOnSaturation(); |
||||
``` |
||||
|
||||
The problem is that they didn't pick the **best** way to express the test's |
||||
intent. |
||||
|
||||
By default, expectations don't have to be matched in _any_ particular |
||||
order. If you want them to match in a certain order, you need to be |
||||
explicit. This is Google Mock's (and jMock's) fundamental philosophy: it's |
||||
easy to accidentally over-specify your tests, and we want to make it |
||||
harder to do so. |
||||
|
||||
There are two better ways to write the test spec. You could either |
||||
put the expectations in sequence: |
||||
|
||||
``` |
||||
// foo.Bar() should be called twice, return 1 the first time, and return |
||||
// 2 the second time. Using a sequence, we can write the expectations |
||||
// in their natural order. |
||||
{ |
||||
InSequence s; |
||||
EXPECT_CALL(foo, Bar()) |
||||
.WillOnce(Return(1)) |
||||
.RetiresOnSaturation(); |
||||
EXPECT_CALL(foo, Bar()) |
||||
.WillOnce(Return(2)) |
||||
.RetiresOnSaturation(); |
||||
} |
||||
``` |
||||
|
||||
or you can put the sequence of actions in the same expectation: |
||||
|
||||
``` |
||||
// foo.Bar() should be called twice, return 1 the first time, and return |
||||
// 2 the second time. |
||||
EXPECT_CALL(foo, Bar()) |
||||
.WillOnce(Return(1)) |
||||
.WillOnce(Return(2)) |
||||
.RetiresOnSaturation(); |
||||
``` |
||||
|
||||
Back to the original questions: why does Google Mock search the |
||||
expectations (and `ON_CALL`s) from back to front? Because this |
||||
allows a user to set up a mock's behavior for the common case early |
||||
(e.g. in the mock's constructor or the test fixture's set-up phase) |
||||
and customize it with more specific rules later. If Google Mock |
||||
searches from front to back, this very useful pattern won't be |
||||
possible. |
||||
|
||||
## Google Mock prints a warning when a function without EXPECT\_CALL is called, even if I have set its behavior using ON\_CALL. Would it be reasonable not to show the warning in this case? ## |
||||
|
||||
When choosing between being neat and being safe, we lean toward the |
||||
latter. So the answer is that we think it's better to show the |
||||
warning. |
||||
|
||||
Often people write `ON_CALL`s in the mock object's |
||||
constructor or `SetUp()`, as the default behavior rarely changes from |
||||
test to test. Then in the test body they set the expectations, which |
||||
are often different for each test. Having an `ON_CALL` in the set-up |
||||
part of a test doesn't mean that the calls are expected. If there's |
||||
no `EXPECT_CALL` and the method is called, it's possibly an error. If |
||||
we quietly let the call go through without notifying the user, bugs |
||||
may creep in unnoticed. |
||||
|
||||
If, however, you are sure that the calls are OK, you can write |
||||
|
||||
``` |
||||
EXPECT_CALL(foo, Bar(_)) |
||||
.WillRepeatedly(...); |
||||
``` |
||||
|
||||
instead of |
||||
|
||||
``` |
||||
ON_CALL(foo, Bar(_)) |
||||
.WillByDefault(...); |
||||
``` |
||||
|
||||
This tells Google Mock that you do expect the calls and no warning should be |
||||
printed. |
||||
|
||||
Also, you can control the verbosity using the `--gmock_verbose` flag. |
||||
If you find the output too noisy when debugging, just choose a less |
||||
verbose level. |
||||
|
||||
## How can I delete the mock function's argument in an action? ## |
||||
|
||||
If you find yourself needing to perform some action that's not |
||||
supported by Google Mock directly, remember that you can define your own |
||||
actions using |
||||
[MakeAction()](V1_5_CookBook#Writing_New_Actions.md) or |
||||
[MakePolymorphicAction()](V1_5_CookBook#Writing_New_Polymorphic_Actions.md), |
||||
or you can write a stub function and invoke it using |
||||
[Invoke()](V1_5_CookBook#Using_Functions_Methods_Functors.md). |
||||
|
||||
## MOCK\_METHODn()'s second argument looks funny. Why don't you use the MOCK\_METHODn(Method, return\_type, arg\_1, ..., arg\_n) syntax? ## |
||||
|
||||
What?! I think it's beautiful. :-) |
||||
|
||||
While which syntax looks more natural is a subjective matter to some |
||||
extent, Google Mock's syntax was chosen for several practical advantages it |
||||
has. |
||||
|
||||
Try to mock a function that takes a map as an argument: |
||||
``` |
||||
virtual int GetSize(const map<int, std::string>& m); |
||||
``` |
||||
|
||||
Using the proposed syntax, it would be: |
||||
``` |
||||
MOCK_METHOD1(GetSize, int, const map<int, std::string>& m); |
||||
``` |
||||
|
||||
Guess what? You'll get a compiler error as the compiler thinks that |
||||
`const map<int, std::string>& m` are **two**, not one, arguments. To work |
||||
around this you can use `typedef` to give the map type a name, but |
||||
that gets in the way of your work. Google Mock's syntax avoids this |
||||
problem as the function's argument types are protected inside a pair |
||||
of parentheses: |
||||
``` |
||||
// This compiles fine. |
||||
MOCK_METHOD1(GetSize, int(const map<int, std::string>& m)); |
||||
``` |
||||
|
||||
You still need a `typedef` if the return type contains an unprotected |
||||
comma, but that's much rarer. |
||||
|
||||
Other advantages include: |
||||
1. `MOCK_METHOD1(Foo, int, bool)` can leave a reader wonder whether the method returns `int` or `bool`, while there won't be such confusion using Google Mock's syntax. |
||||
1. The way Google Mock describes a function type is nothing new, although many people may not be familiar with it. The same syntax was used in C, and the `function` library in `tr1` uses this syntax extensively. Since `tr1` will become a part of the new version of STL, we feel very comfortable to be consistent with it. |
||||
1. The function type syntax is also used in other parts of Google Mock's API (e.g. the action interface) in order to make the implementation tractable. A user needs to learn it anyway in order to utilize Google Mock's more advanced features. We'd as well stick to the same syntax in `MOCK_METHOD*`! |
||||
|
||||
## My code calls a static/global function. Can I mock it? ## |
||||
|
||||
You can, but you need to make some changes. |
||||
|
||||
In general, if you find yourself needing to mock a static function, |
||||
it's a sign that your modules are too tightly coupled (and less |
||||
flexible, less reusable, less testable, etc). You are probably better |
||||
off defining a small interface and call the function through that |
||||
interface, which then can be easily mocked. It's a bit of work |
||||
initially, but usually pays for itself quickly. |
||||
|
||||
This Google Testing Blog |
||||
[post](http://googletesting.blogspot.com/2008/06/defeat-static-cling.html) |
||||
says it excellently. Check it out. |
||||
|
||||
## My mock object needs to do complex stuff. It's a lot of pain to specify the actions. Google Mock sucks! ## |
||||
|
||||
I know it's not a question, but you get an answer for free any way. :-) |
||||
|
||||
With Google Mock, you can create mocks in C++ easily. And people might be |
||||
tempted to use them everywhere. Sometimes they work great, and |
||||
sometimes you may find them, well, a pain to use. So, what's wrong in |
||||
the latter case? |
||||
|
||||
When you write a test without using mocks, you exercise the code and |
||||
assert that it returns the correct value or that the system is in an |
||||
expected state. This is sometimes called "state-based testing". |
||||
|
||||
Mocks are great for what some call "interaction-based" testing: |
||||
instead of checking the system state at the very end, mock objects |
||||
verify that they are invoked the right way and report an error as soon |
||||
as it arises, giving you a handle on the precise context in which the |
||||
error was triggered. This is often more effective and economical to |
||||
do than state-based testing. |
||||
|
||||
If you are doing state-based testing and using a test double just to |
||||
simulate the real object, you are probably better off using a fake. |
||||
Using a mock in this case causes pain, as it's not a strong point for |
||||
mocks to perform complex actions. If you experience this and think |
||||
that mocks suck, you are just not using the right tool for your |
||||
problem. Or, you might be trying to solve the wrong problem. :-) |
||||
|
||||
## I got a warning "Uninteresting function call encountered - default action taken.." Should I panic? ## |
||||
|
||||
By all means, NO! It's just an FYI. |
||||
|
||||
What it means is that you have a mock function, you haven't set any |
||||
expectations on it (by Google Mock's rule this means that you are not |
||||
interested in calls to this function and therefore it can be called |
||||
any number of times), and it is called. That's OK - you didn't say |
||||
it's not OK to call the function! |
||||
|
||||
What if you actually meant to disallow this function to be called, but |
||||
forgot to write `EXPECT_CALL(foo, Bar()).Times(0)`? While |
||||
one can argue that it's the user's fault, Google Mock tries to be nice and |
||||
prints you a note. |
||||
|
||||
So, when you see the message and believe that there shouldn't be any |
||||
uninteresting calls, you should investigate what's going on. To make |
||||
your life easier, Google Mock prints the function name and arguments |
||||
when an uninteresting call is encountered. |
||||
|
||||
## I want to define a custom action. Should I use Invoke() or implement the action interface? ## |
||||
|
||||
Either way is fine - you want to choose the one that's more convenient |
||||
for your circumstance. |
||||
|
||||
Usually, if your action is for a particular function type, defining it |
||||
using `Invoke()` should be easier; if your action can be used in |
||||
functions of different types (e.g. if you are defining |
||||
`Return(value)`), `MakePolymorphicAction()` is |
||||
easiest. Sometimes you want precise control on what types of |
||||
functions the action can be used in, and implementing |
||||
`ActionInterface` is the way to go here. See the implementation of |
||||
`Return()` in `include/gmock/gmock-actions.h` for an example. |
||||
|
||||
## I'm using the set-argument-pointee action, and the compiler complains about "conflicting return type specified". What does it mean? ## |
||||
|
||||
You got this error as Google Mock has no idea what value it should return |
||||
when the mock method is called. `SetArgumentPointee()` says what the |
||||
side effect is, but doesn't say what the return value should be. You |
||||
need `DoAll()` to chain a `SetArgumentPointee()` with a `Return()`. |
||||
|
||||
See this [recipe](V1_5_CookBook#Mocking_Side_Effects.md) for more details and an example. |
||||
|
||||
|
||||
## My question is not in your FAQ! ## |
||||
|
||||
If you cannot find the answer to your question in this FAQ, there are |
||||
some other resources you can use: |
||||
|
||||
1. read other [wiki pages](http://code.google.com/p/googlemock/w/list), |
||||
1. search the mailing list [archive](http://groups.google.com/group/googlemock/topics), |
||||
1. ask it on [googlemock@googlegroups.com](mailto:googlemock@googlegroups.com) and someone will answer it (to prevent spam, we require you to join the [discussion group](http://groups.google.com/group/googlemock) before you can post.). |
||||
|
||||
Please note that creating an issue in the |
||||
[issue tracker](http://code.google.com/p/googlemock/issues/list) is _not_ |
||||
a good way to get your answer, as it is monitored infrequently by a |
||||
very small number of people. |
||||
|
||||
When asking a question, it's helpful to provide as much of the |
||||
following information as possible (people cannot help you if there's |
||||
not enough information in your question): |
||||
|
||||
* the version (or the revision number if you check out from SVN directly) of Google Mock you use (Google Mock is under active development, so it's possible that your problem has been solved in a later version), |
||||
* your operating system, |
||||
* the name and version of your compiler, |
||||
* the complete command line flags you give to your compiler, |
||||
* the complete compiler error messages (if the question is about compilation), |
||||
* the _actual_ code (ideally, a minimal but complete program) that has the problem you encounter. |
@ -1,534 +0,0 @@ |
||||
|
||||
|
||||
# Defining a Mock Class # |
||||
|
||||
## Mocking a Normal Class ## |
||||
|
||||
Given |
||||
``` |
||||
class Foo { |
||||
... |
||||
virtual ~Foo(); |
||||
virtual int GetSize() const = 0; |
||||
virtual string Describe(const char* name) = 0; |
||||
virtual string Describe(int type) = 0; |
||||
virtual bool Process(Bar elem, int count) = 0; |
||||
}; |
||||
``` |
||||
(note that `~Foo()` **must** be virtual) we can define its mock as |
||||
``` |
||||
#include "gmock/gmock.h" |
||||
|
||||
class MockFoo : public Foo { |
||||
MOCK_CONST_METHOD0(GetSize, int()); |
||||
MOCK_METHOD1(Describe, string(const char* name)); |
||||
MOCK_METHOD1(Describe, string(int type)); |
||||
MOCK_METHOD2(Process, bool(Bar elem, int count)); |
||||
}; |
||||
``` |
||||
|
||||
To create a "nice" mock object which ignores all uninteresting calls, |
||||
or a "strict" mock object, which treats them as failures: |
||||
``` |
||||
NiceMock<MockFoo> nice_foo; // The type is a subclass of MockFoo. |
||||
StrictMock<MockFoo> strict_foo; // The type is a subclass of MockFoo. |
||||
``` |
||||
|
||||
## Mocking a Class Template ## |
||||
|
||||
To mock |
||||
``` |
||||
template <typename Elem> |
||||
class StackInterface { |
||||
public: |
||||
... |
||||
virtual ~StackInterface(); |
||||
virtual int GetSize() const = 0; |
||||
virtual void Push(const Elem& x) = 0; |
||||
}; |
||||
``` |
||||
(note that `~StackInterface()` **must** be virtual) just append `_T` to the `MOCK_*` macros: |
||||
``` |
||||
template <typename Elem> |
||||
class MockStack : public StackInterface<Elem> { |
||||
public: |
||||
... |
||||
MOCK_CONST_METHOD0_T(GetSize, int()); |
||||
MOCK_METHOD1_T(Push, void(const Elem& x)); |
||||
}; |
||||
``` |
||||
|
||||
## Specifying Calling Conventions for Mock Functions ## |
||||
|
||||
If your mock function doesn't use the default calling convention, you |
||||
can specify it by appending `_WITH_CALLTYPE` to any of the macros |
||||
described in the previous two sections and supplying the calling |
||||
convention as the first argument to the macro. For example, |
||||
``` |
||||
MOCK_METHOD_1_WITH_CALLTYPE(STDMETHODCALLTYPE, Foo, bool(int n)); |
||||
MOCK_CONST_METHOD2_WITH_CALLTYPE(STDMETHODCALLTYPE, Bar, int(double x, double y)); |
||||
``` |
||||
where `STDMETHODCALLTYPE` is defined by `<objbase.h>` on Windows. |
||||
|
||||
# Using Mocks in Tests # |
||||
|
||||
The typical flow is: |
||||
1. Import the Google Mock names you need to use. All Google Mock names are in the `testing` namespace unless they are macros or otherwise noted. |
||||
1. Create the mock objects. |
||||
1. Optionally, set the default actions of the mock objects. |
||||
1. Set your expectations on the mock objects (How will they be called? What wil they do?). |
||||
1. Exercise code that uses the mock objects; if necessary, check the result using [Google Test](http://code.google.com/p/googletest/) assertions. |
||||
1. When a mock objects is destructed, Google Mock automatically verifies that all expectations on it have been satisfied. |
||||
|
||||
Here is an example: |
||||
``` |
||||
using ::testing::Return; // #1 |
||||
|
||||
TEST(BarTest, DoesThis) { |
||||
MockFoo foo; // #2 |
||||
|
||||
ON_CALL(foo, GetSize()) // #3 |
||||
.WillByDefault(Return(1)); |
||||
// ... other default actions ... |
||||
|
||||
EXPECT_CALL(foo, Describe(5)) // #4 |
||||
.Times(3) |
||||
.WillRepeatedly(Return("Category 5")); |
||||
// ... other expectations ... |
||||
|
||||
EXPECT_EQ("good", MyProductionFunction(&foo)); // #5 |
||||
} // #6 |
||||
``` |
||||
|
||||
# Setting Default Actions # |
||||
|
||||
Google Mock has a **built-in default action** for any function that |
||||
returns `void`, `bool`, a numeric value, or a pointer. |
||||
|
||||
To customize the default action for functions with return type `T` globally: |
||||
``` |
||||
using ::testing::DefaultValue; |
||||
|
||||
DefaultValue<T>::Set(value); // Sets the default value to be returned. |
||||
// ... use the mocks ... |
||||
DefaultValue<T>::Clear(); // Resets the default value. |
||||
``` |
||||
|
||||
To customize the default action for a particular method, use `ON_CALL()`: |
||||
``` |
||||
ON_CALL(mock_object, method(matchers)) |
||||
.With(multi_argument_matcher) ? |
||||
.WillByDefault(action); |
||||
``` |
||||
|
||||
# Setting Expectations # |
||||
|
||||
`EXPECT_CALL()` sets **expectations** on a mock method (How will it be |
||||
called? What will it do?): |
||||
``` |
||||
EXPECT_CALL(mock_object, method(matchers)) |
||||
.With(multi_argument_matcher) ? |
||||
.Times(cardinality) ? |
||||
.InSequence(sequences) * |
||||
.After(expectations) * |
||||
.WillOnce(action) * |
||||
.WillRepeatedly(action) ? |
||||
.RetiresOnSaturation(); ? |
||||
``` |
||||
|
||||
If `Times()` is omitted, the cardinality is assumed to be: |
||||
|
||||
* `Times(1)` when there is neither `WillOnce()` nor `WillRepeatedly()`; |
||||
* `Times(n)` when there are `n WillOnce()`s but no `WillRepeatedly()`, where `n` >= 1; or |
||||
* `Times(AtLeast(n))` when there are `n WillOnce()`s and a `WillRepeatedly()`, where `n` >= 0. |
||||
|
||||
A method with no `EXPECT_CALL()` is free to be invoked _any number of times_, and the default action will be taken each time. |
||||
|
||||
# Matchers # |
||||
|
||||
A **matcher** matches a _single_ argument. You can use it inside |
||||
`ON_CALL()` or `EXPECT_CALL()`, or use it to validate a value |
||||
directly: |
||||
|
||||
| `EXPECT_THAT(value, matcher)` | Asserts that `value` matches `matcher`. | |
||||
|:------------------------------|:----------------------------------------| |
||||
| `ASSERT_THAT(value, matcher)` | The same as `EXPECT_THAT(value, matcher)`, except that it generates a **fatal** failure. | |
||||
|
||||
Built-in matchers (where `argument` is the function argument) are |
||||
divided into several categories: |
||||
|
||||
## Wildcard ## |
||||
|`_`|`argument` can be any value of the correct type.| |
||||
|:--|:-----------------------------------------------| |
||||
|`A<type>()` or `An<type>()`|`argument` can be any value of type `type`. | |
||||
|
||||
## Generic Comparison ## |
||||
|
||||
|`Eq(value)` or `value`|`argument == value`| |
||||
|:---------------------|:------------------| |
||||
|`Ge(value)` |`argument >= value`| |
||||
|`Gt(value)` |`argument > value` | |
||||
|`Le(value)` |`argument <= value`| |
||||
|`Lt(value)` |`argument < value` | |
||||
|`Ne(value)` |`argument != value`| |
||||
|`IsNull()` |`argument` is a `NULL` pointer (raw or smart).| |
||||
|`NotNull()` |`argument` is a non-null pointer (raw or smart).| |
||||
|`Ref(variable)` |`argument` is a reference to `variable`.| |
||||
|`TypedEq<type>(value)`|`argument` has type `type` and is equal to `value`. You may need to use this instead of `Eq(value)` when the mock function is overloaded.| |
||||
|
||||
Except `Ref()`, these matchers make a _copy_ of `value` in case it's |
||||
modified or destructed later. If the compiler complains that `value` |
||||
doesn't have a public copy constructor, try wrap it in `ByRef()`, |
||||
e.g. `Eq(ByRef(non_copyable_value))`. If you do that, make sure |
||||
`non_copyable_value` is not changed afterwards, or the meaning of your |
||||
matcher will be changed. |
||||
|
||||
## Floating-Point Matchers ## |
||||
|
||||
|`DoubleEq(a_double)`|`argument` is a `double` value approximately equal to `a_double`, treating two NaNs as unequal.| |
||||
|:-------------------|:----------------------------------------------------------------------------------------------| |
||||
|`FloatEq(a_float)` |`argument` is a `float` value approximately equal to `a_float`, treating two NaNs as unequal. | |
||||
|`NanSensitiveDoubleEq(a_double)`|`argument` is a `double` value approximately equal to `a_double`, treating two NaNs as equal. | |
||||
|`NanSensitiveFloatEq(a_float)`|`argument` is a `float` value approximately equal to `a_float`, treating two NaNs as equal. | |
||||
|
||||
These matchers use ULP-based comparison (the same as used in |
||||
[Google Test](http://code.google.com/p/googletest/)). They |
||||
automatically pick a reasonable error bound based on the absolute |
||||
value of the expected value. `DoubleEq()` and `FloatEq()` conform to |
||||
the IEEE standard, which requires comparing two NaNs for equality to |
||||
return false. The `NanSensitive*` version instead treats two NaNs as |
||||
equal, which is often what a user wants. |
||||
|
||||
## String Matchers ## |
||||
|
||||
The `argument` can be either a C string or a C++ string object: |
||||
|
||||
|`ContainsRegex(string)`|`argument` matches the given regular expression.| |
||||
|:----------------------|:-----------------------------------------------| |
||||
|`EndsWith(suffix)` |`argument` ends with string `suffix`. | |
||||
|`HasSubstr(string)` |`argument` contains `string` as a sub-string. | |
||||
|`MatchesRegex(string)` |`argument` matches the given regular expression with the match starting at the first character and ending at the last character.| |
||||
|`StartsWith(prefix)` |`argument` starts with string `prefix`. | |
||||
|`StrCaseEq(string)` |`argument` is equal to `string`, ignoring case. | |
||||
|`StrCaseNe(string)` |`argument` is not equal to `string`, ignoring case.| |
||||
|`StrEq(string)` |`argument` is equal to `string`. | |
||||
|`StrNe(string)` |`argument` is not equal to `string`. | |
||||
|
||||
`ContainsRegex()` and `MatchesRegex()` use the regular expression |
||||
syntax defined |
||||
[here](http://code.google.com/p/googletest/wiki/V1_6_AdvancedGuide#Regular_Expression_Syntax). |
||||
`StrCaseEq()`, `StrCaseNe()`, `StrEq()`, and `StrNe()` work for wide |
||||
strings as well. |
||||
|
||||
## Container Matchers ## |
||||
|
||||
Most STL-style containers support `==`, so you can use |
||||
`Eq(expected_container)` or simply `expected_container` to match a |
||||
container exactly. If you want to write the elements in-line, |
||||
match them more flexibly, or get more informative messages, you can use: |
||||
|
||||
| `Contains(e)` | `argument` contains an element that matches `e`, which can be either a value or a matcher. | |
||||
|:--------------|:-------------------------------------------------------------------------------------------| |
||||
| `Each(e)` | `argument` is a container where _every_ element matches `e`, which can be either a value or a matcher. | |
||||
| `ElementsAre(e0, e1, ..., en)` | `argument` has `n + 1` elements, where the i-th element matches `ei`, which can be a value or a matcher. 0 to 10 arguments are allowed. | |
||||
| `ElementsAreArray(array)` or `ElementsAreArray(array, count)` | The same as `ElementsAre()` except that the expected element values/matchers come from a C-style array. | |
||||
| `ContainerEq(container)` | The same as `Eq(container)` except that the failure message also includes which elements are in one container but not the other. | |
||||
| `Pointwise(m, container)` | `argument` contains the same number of elements as in `container`, and for all i, (the i-th element in `argument`, the i-th element in `container`) match `m`, which is a matcher on 2-tuples. E.g. `Pointwise(Le(), upper_bounds)` verifies that each element in `argument` doesn't exceed the corresponding element in `upper_bounds`. | |
||||
|
||||
These matchers can also match: |
||||
|
||||
1. a native array passed by reference (e.g. in `Foo(const int (&a)[5])`), and |
||||
1. an array passed as a pointer and a count (e.g. in `Bar(const T* buffer, int len)` -- see [Multi-argument Matchers](#Multiargument_Matchers.md)). |
||||
|
||||
where the array may be multi-dimensional (i.e. its elements can be arrays). |
||||
|
||||
## Member Matchers ## |
||||
|
||||
|`Field(&class::field, m)`|`argument.field` (or `argument->field` when `argument` is a plain pointer) matches matcher `m`, where `argument` is an object of type _class_.| |
||||
|:------------------------|:---------------------------------------------------------------------------------------------------------------------------------------------| |
||||
|`Key(e)` |`argument.first` matches `e`, which can be either a value or a matcher. E.g. `Contains(Key(Le(5)))` can verify that a `map` contains a key `<= 5`.| |
||||
|`Pair(m1, m2)` |`argument` is an `std::pair` whose `first` field matches `m1` and `second` field matches `m2`. | |
||||
|`Property(&class::property, m)`|`argument.property()` (or `argument->property()` when `argument` is a plain pointer) matches matcher `m`, where `argument` is an object of type _class_.| |
||||
|
||||
## Matching the Result of a Function or Functor ## |
||||
|
||||
|`ResultOf(f, m)`|`f(argument)` matches matcher `m`, where `f` is a function or functor.| |
||||
|:---------------|:---------------------------------------------------------------------| |
||||
|
||||
## Pointer Matchers ## |
||||
|
||||
|`Pointee(m)`|`argument` (either a smart pointer or a raw pointer) points to a value that matches matcher `m`.| |
||||
|:-----------|:-----------------------------------------------------------------------------------------------| |
||||
|
||||
## Multiargument Matchers ## |
||||
|
||||
Technically, all matchers match a _single_ value. A "multi-argument" |
||||
matcher is just one that matches a _tuple_. The following matchers can |
||||
be used to match a tuple `(x, y)`: |
||||
|
||||
|`Eq()`|`x == y`| |
||||
|:-----|:-------| |
||||
|`Ge()`|`x >= y`| |
||||
|`Gt()`|`x > y` | |
||||
|`Le()`|`x <= y`| |
||||
|`Lt()`|`x < y` | |
||||
|`Ne()`|`x != y`| |
||||
|
||||
You can use the following selectors to pick a subset of the arguments |
||||
(or reorder them) to participate in the matching: |
||||
|
||||
|`AllArgs(m)`|Equivalent to `m`. Useful as syntactic sugar in `.With(AllArgs(m))`.| |
||||
|:-----------|:-------------------------------------------------------------------| |
||||
|`Args<N1, N2, ..., Nk>(m)`|The tuple of the `k` selected (using 0-based indices) arguments matches `m`, e.g. `Args<1, 2>(Eq())`.| |
||||
|
||||
## Composite Matchers ## |
||||
|
||||
You can make a matcher from one or more other matchers: |
||||
|
||||
|`AllOf(m1, m2, ..., mn)`|`argument` matches all of the matchers `m1` to `mn`.| |
||||
|:-----------------------|:---------------------------------------------------| |
||||
|`AnyOf(m1, m2, ..., mn)`|`argument` matches at least one of the matchers `m1` to `mn`.| |
||||
|`Not(m)` |`argument` doesn't match matcher `m`. | |
||||
|
||||
## Adapters for Matchers ## |
||||
|
||||
|`MatcherCast<T>(m)`|casts matcher `m` to type `Matcher<T>`.| |
||||
|:------------------|:--------------------------------------| |
||||
|`SafeMatcherCast<T>(m)`| [safely casts](http://code.google.com/p/googlemock/wiki/V1_6_CookBook#Casting_Matchers) matcher `m` to type `Matcher<T>`. | |
||||
|`Truly(predicate)` |`predicate(argument)` returns something considered by C++ to be true, where `predicate` is a function or functor.| |
||||
|
||||
## Matchers as Predicates ## |
||||
|
||||
|`Matches(m)(value)`|evaluates to `true` if `value` matches `m`. You can use `Matches(m)` alone as a unary functor.| |
||||
|:------------------|:---------------------------------------------------------------------------------------------| |
||||
|`ExplainMatchResult(m, value, result_listener)`|evaluates to `true` if `value` matches `m`, explaining the result to `result_listener`. | |
||||
|`Value(value, m)` |evaluates to `true` if `value` matches `m`. | |
||||
|
||||
## Defining Matchers ## |
||||
|
||||
| `MATCHER(IsEven, "") { return (arg % 2) == 0; }` | Defines a matcher `IsEven()` to match an even number. | |
||||
|:-------------------------------------------------|:------------------------------------------------------| |
||||
| `MATCHER_P(IsDivisibleBy, n, "") { *result_listener << "where the remainder is " << (arg % n); return (arg % n) == 0; }` | Defines a macher `IsDivisibleBy(n)` to match a number divisible by `n`. | |
||||
| `MATCHER_P2(IsBetween, a, b, std::string(negation ? "isn't" : "is") + " between " + PrintToString(a) + " and " + PrintToString(b)) { return a <= arg && arg <= b; }` | Defines a matcher `IsBetween(a, b)` to match a value in the range [`a`, `b`]. | |
||||
|
||||
**Notes:** |
||||
|
||||
1. The `MATCHER*` macros cannot be used inside a function or class. |
||||
1. The matcher body must be _purely functional_ (i.e. it cannot have any side effect, and the result must not depend on anything other than the value being matched and the matcher parameters). |
||||
1. You can use `PrintToString(x)` to convert a value `x` of any type to a string. |
||||
|
||||
## Matchers as Test Assertions ## |
||||
|
||||
|`ASSERT_THAT(expression, m)`|Generates a [fatal failure](http://code.google.com/p/googletest/wiki/V1_6_Primer#Assertions) if the value of `expression` doesn't match matcher `m`.| |
||||
|:---------------------------|:---------------------------------------------------------------------------------------------------------------------------------------------------| |
||||
|`EXPECT_THAT(expression, m)`|Generates a non-fatal failure if the value of `expression` doesn't match matcher `m`. | |
||||
|
||||
# Actions # |
||||
|
||||
**Actions** specify what a mock function should do when invoked. |
||||
|
||||
## Returning a Value ## |
||||
|
||||
|`Return()`|Return from a `void` mock function.| |
||||
|:---------|:----------------------------------| |
||||
|`Return(value)`|Return `value`. If the type of `value` is different to the mock function's return type, `value` is converted to the latter type <i>at the time the expectation is set</i>, not when the action is executed.| |
||||
|`ReturnArg<N>()`|Return the `N`-th (0-based) argument.| |
||||
|`ReturnNew<T>(a1, ..., ak)`|Return `new T(a1, ..., ak)`; a different object is created each time.| |
||||
|`ReturnNull()`|Return a null pointer. | |
||||
|`ReturnPointee(ptr)`|Return the value pointed to by `ptr`.| |
||||
|`ReturnRef(variable)`|Return a reference to `variable`. | |
||||
|`ReturnRefOfCopy(value)`|Return a reference to a copy of `value`; the copy lives as long as the action.| |
||||
|
||||
## Side Effects ## |
||||
|
||||
|`Assign(&variable, value)`|Assign `value` to variable.| |
||||
|:-------------------------|:--------------------------| |
||||
| `DeleteArg<N>()` | Delete the `N`-th (0-based) argument, which must be a pointer. | |
||||
| `SaveArg<N>(pointer)` | Save the `N`-th (0-based) argument to `*pointer`. | |
||||
| `SaveArgPointee<N>(pointer)` | Save the value pointed to by the `N`-th (0-based) argument to `*pointer`. | |
||||
| `SetArgReferee<N>(value)` | Assign value to the variable referenced by the `N`-th (0-based) argument. | |
||||
|`SetArgPointee<N>(value)` |Assign `value` to the variable pointed by the `N`-th (0-based) argument.| |
||||
|`SetArgumentPointee<N>(value)`|Same as `SetArgPointee<N>(value)`. Deprecated. Will be removed in v1.7.0.| |
||||
|`SetArrayArgument<N>(first, last)`|Copies the elements in source range [`first`, `last`) to the array pointed to by the `N`-th (0-based) argument, which can be either a pointer or an iterator. The action does not take ownership of the elements in the source range.| |
||||
|`SetErrnoAndReturn(error, value)`|Set `errno` to `error` and return `value`.| |
||||
|`Throw(exception)` |Throws the given exception, which can be any copyable value. Available since v1.1.0.| |
||||
|
||||
## Using a Function or a Functor as an Action ## |
||||
|
||||
|`Invoke(f)`|Invoke `f` with the arguments passed to the mock function, where `f` can be a global/static function or a functor.| |
||||
|:----------|:-----------------------------------------------------------------------------------------------------------------| |
||||
|`Invoke(object_pointer, &class::method)`|Invoke the {method on the object with the arguments passed to the mock function. | |
||||
|`InvokeWithoutArgs(f)`|Invoke `f`, which can be a global/static function or a functor. `f` must take no arguments. | |
||||
|`InvokeWithoutArgs(object_pointer, &class::method)`|Invoke the method on the object, which takes no arguments. | |
||||
|`InvokeArgument<N>(arg1, arg2, ..., argk)`|Invoke the mock function's `N`-th (0-based) argument, which must be a function or a functor, with the `k` arguments.| |
||||
|
||||
The return value of the invoked function is used as the return value |
||||
of the action. |
||||
|
||||
When defining a function or functor to be used with `Invoke*()`, you can declare any unused parameters as `Unused`: |
||||
``` |
||||
double Distance(Unused, double x, double y) { return sqrt(x*x + y*y); } |
||||
... |
||||
EXPECT_CALL(mock, Foo("Hi", _, _)).WillOnce(Invoke(Distance)); |
||||
``` |
||||
|
||||
In `InvokeArgument<N>(...)`, if an argument needs to be passed by reference, wrap it inside `ByRef()`. For example, |
||||
``` |
||||
InvokeArgument<2>(5, string("Hi"), ByRef(foo)) |
||||
``` |
||||
calls the mock function's #2 argument, passing to it `5` and `string("Hi")` by value, and `foo` by reference. |
||||
|
||||
## Default Action ## |
||||
|
||||
|`DoDefault()`|Do the default action (specified by `ON_CALL()` or the built-in one).| |
||||
|:------------|:--------------------------------------------------------------------| |
||||
|
||||
**Note:** due to technical reasons, `DoDefault()` cannot be used inside a composite action - trying to do so will result in a run-time error. |
||||
|
||||
## Composite Actions ## |
||||
|
||||
|`DoAll(a1, a2, ..., an)`|Do all actions `a1` to `an` and return the result of `an` in each invocation. The first `n - 1` sub-actions must return void. | |
||||
|:-----------------------|:-----------------------------------------------------------------------------------------------------------------------------| |
||||
|`IgnoreResult(a)` |Perform action `a` and ignore its result. `a` must not return void. | |
||||
|`WithArg<N>(a)` |Pass the `N`-th (0-based) argument of the mock function to action `a` and perform it. | |
||||
|`WithArgs<N1, N2, ..., Nk>(a)`|Pass the selected (0-based) arguments of the mock function to action `a` and perform it. | |
||||
|`WithoutArgs(a)` |Perform action `a` without any arguments. | |
||||
|
||||
## Defining Actions ## |
||||
|
||||
| `ACTION(Sum) { return arg0 + arg1; }` | Defines an action `Sum()` to return the sum of the mock function's argument #0 and #1. | |
||||
|:--------------------------------------|:---------------------------------------------------------------------------------------| |
||||
| `ACTION_P(Plus, n) { return arg0 + n; }` | Defines an action `Plus(n)` to return the sum of the mock function's argument #0 and `n`. | |
||||
| `ACTION_Pk(Foo, p1, ..., pk) { statements; }` | Defines a parameterized action `Foo(p1, ..., pk)` to execute the given `statements`. | |
||||
|
||||
The `ACTION*` macros cannot be used inside a function or class. |
||||
|
||||
# Cardinalities # |
||||
|
||||
These are used in `Times()` to specify how many times a mock function will be called: |
||||
|
||||
|`AnyNumber()`|The function can be called any number of times.| |
||||
|:------------|:----------------------------------------------| |
||||
|`AtLeast(n)` |The call is expected at least `n` times. | |
||||
|`AtMost(n)` |The call is expected at most `n` times. | |
||||
|`Between(m, n)`|The call is expected between `m` and `n` (inclusive) times.| |
||||
|`Exactly(n) or n`|The call is expected exactly `n` times. In particular, the call should never happen when `n` is 0.| |
||||
|
||||
# Expectation Order # |
||||
|
||||
By default, the expectations can be matched in _any_ order. If some |
||||
or all expectations must be matched in a given order, there are two |
||||
ways to specify it. They can be used either independently or |
||||
together. |
||||
|
||||
## The After Clause ## |
||||
|
||||
``` |
||||
using ::testing::Expectation; |
||||
... |
||||
Expectation init_x = EXPECT_CALL(foo, InitX()); |
||||
Expectation init_y = EXPECT_CALL(foo, InitY()); |
||||
EXPECT_CALL(foo, Bar()) |
||||
.After(init_x, init_y); |
||||
``` |
||||
says that `Bar()` can be called only after both `InitX()` and |
||||
`InitY()` have been called. |
||||
|
||||
If you don't know how many pre-requisites an expectation has when you |
||||
write it, you can use an `ExpectationSet` to collect them: |
||||
|
||||
``` |
||||
using ::testing::ExpectationSet; |
||||
... |
||||
ExpectationSet all_inits; |
||||
for (int i = 0; i < element_count; i++) { |
||||
all_inits += EXPECT_CALL(foo, InitElement(i)); |
||||
} |
||||
EXPECT_CALL(foo, Bar()) |
||||
.After(all_inits); |
||||
``` |
||||
says that `Bar()` can be called only after all elements have been |
||||
initialized (but we don't care about which elements get initialized |
||||
before the others). |
||||
|
||||
Modifying an `ExpectationSet` after using it in an `.After()` doesn't |
||||
affect the meaning of the `.After()`. |
||||
|
||||
## Sequences ## |
||||
|
||||
When you have a long chain of sequential expectations, it's easier to |
||||
specify the order using **sequences**, which don't require you to given |
||||
each expectation in the chain a different name. <i>All expected<br> |
||||
calls</i> in the same sequence must occur in the order they are |
||||
specified. |
||||
|
||||
``` |
||||
using ::testing::Sequence; |
||||
Sequence s1, s2; |
||||
... |
||||
EXPECT_CALL(foo, Reset()) |
||||
.InSequence(s1, s2) |
||||
.WillOnce(Return(true)); |
||||
EXPECT_CALL(foo, GetSize()) |
||||
.InSequence(s1) |
||||
.WillOnce(Return(1)); |
||||
EXPECT_CALL(foo, Describe(A<const char*>())) |
||||
.InSequence(s2) |
||||
.WillOnce(Return("dummy")); |
||||
``` |
||||
says that `Reset()` must be called before _both_ `GetSize()` _and_ |
||||
`Describe()`, and the latter two can occur in any order. |
||||
|
||||
To put many expectations in a sequence conveniently: |
||||
``` |
||||
using ::testing::InSequence; |
||||
{ |
||||
InSequence dummy; |
||||
|
||||
EXPECT_CALL(...)...; |
||||
EXPECT_CALL(...)...; |
||||
... |
||||
EXPECT_CALL(...)...; |
||||
} |
||||
``` |
||||
says that all expected calls in the scope of `dummy` must occur in |
||||
strict order. The name `dummy` is irrelevant.) |
||||
|
||||
# Verifying and Resetting a Mock # |
||||
|
||||
Google Mock will verify the expectations on a mock object when it is destructed, or you can do it earlier: |
||||
``` |
||||
using ::testing::Mock; |
||||
... |
||||
// Verifies and removes the expectations on mock_obj; |
||||
// returns true iff successful. |
||||
Mock::VerifyAndClearExpectations(&mock_obj); |
||||
... |
||||
// Verifies and removes the expectations on mock_obj; |
||||
// also removes the default actions set by ON_CALL(); |
||||
// returns true iff successful. |
||||
Mock::VerifyAndClear(&mock_obj); |
||||
``` |
||||
|
||||
You can also tell Google Mock that a mock object can be leaked and doesn't |
||||
need to be verified: |
||||
``` |
||||
Mock::AllowLeak(&mock_obj); |
||||
``` |
||||
|
||||
# Mock Classes # |
||||
|
||||
Google Mock defines a convenient mock class template |
||||
``` |
||||
class MockFunction<R(A1, ..., An)> { |
||||
public: |
||||
MOCK_METHODn(Call, R(A1, ..., An)); |
||||
}; |
||||
``` |
||||
See this [recipe](http://code.google.com/p/googlemock/wiki/V1_6_CookBook#Using_Check_Points) for one application of it. |
||||
|
||||
# Flags # |
||||
|
||||
| `--gmock_catch_leaked_mocks=0` | Don't report leaked mock objects as failures. | |
||||
|:-------------------------------|:----------------------------------------------| |
||||
| `--gmock_verbose=LEVEL` | Sets the default verbosity level (`info`, `warning`, or `error`) of Google Mock messages. | |
File diff suppressed because it is too large
Load Diff
@ -1,12 +0,0 @@ |
||||
This page lists all documentation wiki pages for Google Mock **1.6** |
||||
- **if you use a released version of Google Mock, please read the documentation for that specific version instead.** |
||||
|
||||
* [ForDummies](V1_6_ForDummies.md) -- start here if you are new to Google Mock. |
||||
* [CheatSheet](V1_6_CheatSheet.md) -- a quick reference. |
||||
* [CookBook](V1_6_CookBook.md) -- recipes for doing various tasks using Google Mock. |
||||
* [FrequentlyAskedQuestions](V1_6_FrequentlyAskedQuestions.md) -- check here before asking a question on the mailing list. |
||||
|
||||
To contribute code to Google Mock, read: |
||||
|
||||
* [DevGuide](DevGuide.md) -- read this _before_ writing your first patch. |
||||
* [Pump Manual](http://code.google.com/p/googletest/wiki/V1_6_PumpManual) -- how we generate some of Google Mock's source files. |
@ -1,439 +0,0 @@ |
||||
|
||||
|
||||
(**Note:** If you get compiler errors that you don't understand, be sure to consult [Google Mock Doctor](http://code.google.com/p/googlemock/wiki/V1_6_FrequentlyAskedQuestions#How_am_I_supposed_to_make_sense_of_these_horrible_template_error).) |
||||
|
||||
# What Is Google C++ Mocking Framework? # |
||||
When you write a prototype or test, often it's not feasible or wise to rely on real objects entirely. A **mock object** implements the same interface as a real object (so it can be used as one), but lets you specify at run time how it will be used and what it should do (which methods will be called? in which order? how many times? with what arguments? what will they return? etc). |
||||
|
||||
**Note:** It is easy to confuse the term _fake objects_ with mock objects. Fakes and mocks actually mean very different things in the Test-Driven Development (TDD) community: |
||||
|
||||
* **Fake** objects have working implementations, but usually take some shortcut (perhaps to make the operations less expensive), which makes them not suitable for production. An in-memory file system would be an example of a fake. |
||||
* **Mocks** are objects pre-programmed with _expectations_, which form a specification of the calls they are expected to receive. |
||||
|
||||
If all this seems too abstract for you, don't worry - the most important thing to remember is that a mock allows you to check the _interaction_ between itself and code that uses it. The difference between fakes and mocks will become much clearer once you start to use mocks. |
||||
|
||||
**Google C++ Mocking Framework** (or **Google Mock** for short) is a library (sometimes we also call it a "framework" to make it sound cool) for creating mock classes and using them. It does to C++ what [jMock](http://www.jmock.org/) and [EasyMock](http://www.easymock.org/) do to Java. |
||||
|
||||
Using Google Mock involves three basic steps: |
||||
|
||||
1. Use some simple macros to describe the interface you want to mock, and they will expand to the implementation of your mock class; |
||||
1. Create some mock objects and specify its expectations and behavior using an intuitive syntax; |
||||
1. Exercise code that uses the mock objects. Google Mock will catch any violation of the expectations as soon as it arises. |
||||
|
||||
# Why Google Mock? # |
||||
While mock objects help you remove unnecessary dependencies in tests and make them fast and reliable, using mocks manually in C++ is _hard_: |
||||
|
||||
* Someone has to implement the mocks. The job is usually tedious and error-prone. No wonder people go great distance to avoid it. |
||||
* The quality of those manually written mocks is a bit, uh, unpredictable. You may see some really polished ones, but you may also see some that were hacked up in a hurry and have all sorts of ad hoc restrictions. |
||||
* The knowledge you gained from using one mock doesn't transfer to the next. |
||||
|
||||
In contrast, Java and Python programmers have some fine mock frameworks, which automate the creation of mocks. As a result, mocking is a proven effective technique and widely adopted practice in those communities. Having the right tool absolutely makes the difference. |
||||
|
||||
Google Mock was built to help C++ programmers. It was inspired by [jMock](http://www.jmock.org/) and [EasyMock](http://www.easymock.org/), but designed with C++'s specifics in mind. It is your friend if any of the following problems is bothering you: |
||||
|
||||
* You are stuck with a sub-optimal design and wish you had done more prototyping before it was too late, but prototyping in C++ is by no means "rapid". |
||||
* Your tests are slow as they depend on too many libraries or use expensive resources (e.g. a database). |
||||
* Your tests are brittle as some resources they use are unreliable (e.g. the network). |
||||
* You want to test how your code handles a failure (e.g. a file checksum error), but it's not easy to cause one. |
||||
* You need to make sure that your module interacts with other modules in the right way, but it's hard to observe the interaction; therefore you resort to observing the side effects at the end of the action, which is awkward at best. |
||||
* You want to "mock out" your dependencies, except that they don't have mock implementations yet; and, frankly, you aren't thrilled by some of those hand-written mocks. |
||||
|
||||
We encourage you to use Google Mock as: |
||||
|
||||
* a _design_ tool, for it lets you experiment with your interface design early and often. More iterations lead to better designs! |
||||
* a _testing_ tool to cut your tests' outbound dependencies and probe the interaction between your module and its collaborators. |
||||
|
||||
# Getting Started # |
||||
Using Google Mock is easy! Inside your C++ source file, just `#include` `"gtest/gtest.h"` and `"gmock/gmock.h"`, and you are ready to go. |
||||
|
||||
# A Case for Mock Turtles # |
||||
Let's look at an example. Suppose you are developing a graphics program that relies on a LOGO-like API for drawing. How would you test that it does the right thing? Well, you can run it and compare the screen with a golden screen snapshot, but let's admit it: tests like this are expensive to run and fragile (What if you just upgraded to a shiny new graphics card that has better anti-aliasing? Suddenly you have to update all your golden images.). It would be too painful if all your tests are like this. Fortunately, you learned about Dependency Injection and know the right thing to do: instead of having your application talk to the drawing API directly, wrap the API in an interface (say, `Turtle`) and code to that interface: |
||||
|
||||
``` |
||||
class Turtle { |
||||
... |
||||
virtual ~Turtle() {} |
||||
virtual void PenUp() = 0; |
||||
virtual void PenDown() = 0; |
||||
virtual void Forward(int distance) = 0; |
||||
virtual void Turn(int degrees) = 0; |
||||
virtual void GoTo(int x, int y) = 0; |
||||
virtual int GetX() const = 0; |
||||
virtual int GetY() const = 0; |
||||
}; |
||||
``` |
||||
|
||||
(Note that the destructor of `Turtle` **must** be virtual, as is the case for **all** classes you intend to inherit from - otherwise the destructor of the derived class will not be called when you delete an object through a base pointer, and you'll get corrupted program states like memory leaks.) |
||||
|
||||
You can control whether the turtle's movement will leave a trace using `PenUp()` and `PenDown()`, and control its movement using `Forward()`, `Turn()`, and `GoTo()`. Finally, `GetX()` and `GetY()` tell you the current position of the turtle. |
||||
|
||||
Your program will normally use a real implementation of this interface. In tests, you can use a mock implementation instead. This allows you to easily check what drawing primitives your program is calling, with what arguments, and in which order. Tests written this way are much more robust (they won't break because your new machine does anti-aliasing differently), easier to read and maintain (the intent of a test is expressed in the code, not in some binary images), and run _much, much faster_. |
||||
|
||||
# Writing the Mock Class # |
||||
If you are lucky, the mocks you need to use have already been implemented by some nice people. If, however, you find yourself in the position to write a mock class, relax - Google Mock turns this task into a fun game! (Well, almost.) |
||||
|
||||
## How to Define It ## |
||||
Using the `Turtle` interface as example, here are the simple steps you need to follow: |
||||
|
||||
1. Derive a class `MockTurtle` from `Turtle`. |
||||
1. Take a _virtual_ function of `Turtle` (while it's possible to [mock non-virtual methods using templates](http://code.google.com/p/googlemock/wiki/V1_6_CookBook#Mocking_Nonvirtual_Methods), it's much more involved). Count how many arguments it has. |
||||
1. In the `public:` section of the child class, write `MOCK_METHODn();` (or `MOCK_CONST_METHODn();` if you are mocking a `const` method), where `n` is the number of the arguments; if you counted wrong, shame on you, and a compiler error will tell you so. |
||||
1. Now comes the fun part: you take the function signature, cut-and-paste the _function name_ as the _first_ argument to the macro, and leave what's left as the _second_ argument (in case you're curious, this is the _type of the function_). |
||||
1. Repeat until all virtual functions you want to mock are done. |
||||
|
||||
After the process, you should have something like: |
||||
|
||||
``` |
||||
#include "gmock/gmock.h" // Brings in Google Mock. |
||||
class MockTurtle : public Turtle { |
||||
public: |
||||
... |
||||
MOCK_METHOD0(PenUp, void()); |
||||
MOCK_METHOD0(PenDown, void()); |
||||
MOCK_METHOD1(Forward, void(int distance)); |
||||
MOCK_METHOD1(Turn, void(int degrees)); |
||||
MOCK_METHOD2(GoTo, void(int x, int y)); |
||||
MOCK_CONST_METHOD0(GetX, int()); |
||||
MOCK_CONST_METHOD0(GetY, int()); |
||||
}; |
||||
``` |
||||
|
||||
You don't need to define these mock methods somewhere else - the `MOCK_METHOD*` macros will generate the definitions for you. It's that simple! Once you get the hang of it, you can pump out mock classes faster than your source-control system can handle your check-ins. |
||||
|
||||
**Tip:** If even this is too much work for you, you'll find the |
||||
`gmock_gen.py` tool in Google Mock's `scripts/generator/` directory (courtesy of the [cppclean](http://code.google.com/p/cppclean/) project) useful. This command-line |
||||
tool requires that you have Python 2.4 installed. You give it a C++ file and the name of an abstract class defined in it, |
||||
and it will print the definition of the mock class for you. Due to the |
||||
complexity of the C++ language, this script may not always work, but |
||||
it can be quite handy when it does. For more details, read the [user documentation](http://code.google.com/p/googlemock/source/browse/trunk/scripts/generator/README). |
||||
|
||||
## Where to Put It ## |
||||
When you define a mock class, you need to decide where to put its definition. Some people put it in a `*_test.cc`. This is fine when the interface being mocked (say, `Foo`) is owned by the same person or team. Otherwise, when the owner of `Foo` changes it, your test could break. (You can't really expect `Foo`'s maintainer to fix every test that uses `Foo`, can you?) |
||||
|
||||
So, the rule of thumb is: if you need to mock `Foo` and it's owned by others, define the mock class in `Foo`'s package (better, in a `testing` sub-package such that you can clearly separate production code and testing utilities), and put it in a `mock_foo.h`. Then everyone can reference `mock_foo.h` from their tests. If `Foo` ever changes, there is only one copy of `MockFoo` to change, and only tests that depend on the changed methods need to be fixed. |
||||
|
||||
Another way to do it: you can introduce a thin layer `FooAdaptor` on top of `Foo` and code to this new interface. Since you own `FooAdaptor`, you can absorb changes in `Foo` much more easily. While this is more work initially, carefully choosing the adaptor interface can make your code easier to write and more readable (a net win in the long run), as you can choose `FooAdaptor` to fit your specific domain much better than `Foo` does. |
||||
|
||||
# Using Mocks in Tests # |
||||
Once you have a mock class, using it is easy. The typical work flow is: |
||||
|
||||
1. Import the Google Mock names from the `testing` namespace such that you can use them unqualified (You only have to do it once per file. Remember that namespaces are a good idea and good for your health.). |
||||
1. Create some mock objects. |
||||
1. Specify your expectations on them (How many times will a method be called? With what arguments? What should it do? etc.). |
||||
1. Exercise some code that uses the mocks; optionally, check the result using Google Test assertions. If a mock method is called more than expected or with wrong arguments, you'll get an error immediately. |
||||
1. When a mock is destructed, Google Mock will automatically check whether all expectations on it have been satisfied. |
||||
|
||||
Here's an example: |
||||
|
||||
``` |
||||
#include "path/to/mock-turtle.h" |
||||
#include "gmock/gmock.h" |
||||
#include "gtest/gtest.h" |
||||
using ::testing::AtLeast; // #1 |
||||
|
||||
TEST(PainterTest, CanDrawSomething) { |
||||
MockTurtle turtle; // #2 |
||||
EXPECT_CALL(turtle, PenDown()) // #3 |
||||
.Times(AtLeast(1)); |
||||
|
||||
Painter painter(&turtle); // #4 |
||||
|
||||
EXPECT_TRUE(painter.DrawCircle(0, 0, 10)); |
||||
} // #5 |
||||
|
||||
int main(int argc, char** argv) { |
||||
// The following line must be executed to initialize Google Mock |
||||
// (and Google Test) before running the tests. |
||||
::testing::InitGoogleMock(&argc, argv); |
||||
return RUN_ALL_TESTS(); |
||||
} |
||||
``` |
||||
|
||||
As you might have guessed, this test checks that `PenDown()` is called at least once. If the `painter` object didn't call this method, your test will fail with a message like this: |
||||
|
||||
``` |
||||
path/to/my_test.cc:119: Failure |
||||
Actual function call count doesn't match this expectation: |
||||
Actually: never called; |
||||
Expected: called at least once. |
||||
``` |
||||
|
||||
**Tip 1:** If you run the test from an Emacs buffer, you can hit `<Enter>` on the line number displayed in the error message to jump right to the failed expectation. |
||||
|
||||
**Tip 2:** If your mock objects are never deleted, the final verification won't happen. Therefore it's a good idea to use a heap leak checker in your tests when you allocate mocks on the heap. |
||||
|
||||
**Important note:** Google Mock requires expectations to be set **before** the mock functions are called, otherwise the behavior is **undefined**. In particular, you mustn't interleave `EXPECT_CALL()`s and calls to the mock functions. |
||||
|
||||
This means `EXPECT_CALL()` should be read as expecting that a call will occur _in the future_, not that a call has occurred. Why does Google Mock work like that? Well, specifying the expectation beforehand allows Google Mock to report a violation as soon as it arises, when the context (stack trace, etc) is still available. This makes debugging much easier. |
||||
|
||||
Admittedly, this test is contrived and doesn't do much. You can easily achieve the same effect without using Google Mock. However, as we shall reveal soon, Google Mock allows you to do _much more_ with the mocks. |
||||
|
||||
## Using Google Mock with Any Testing Framework ## |
||||
If you want to use something other than Google Test (e.g. [CppUnit](http://apps.sourceforge.net/mediawiki/cppunit/index.php?title=Main_Page) or |
||||
[CxxTest](http://cxxtest.tigris.org/)) as your testing framework, just change the `main()` function in the previous section to: |
||||
``` |
||||
int main(int argc, char** argv) { |
||||
// The following line causes Google Mock to throw an exception on failure, |
||||
// which will be interpreted by your testing framework as a test failure. |
||||
::testing::GTEST_FLAG(throw_on_failure) = true; |
||||
::testing::InitGoogleMock(&argc, argv); |
||||
... whatever your testing framework requires ... |
||||
} |
||||
``` |
||||
|
||||
This approach has a catch: it makes Google Mock throw an exception |
||||
from a mock object's destructor sometimes. With some compilers, this |
||||
sometimes causes the test program to crash. You'll still be able to |
||||
notice that the test has failed, but it's not a graceful failure. |
||||
|
||||
A better solution is to use Google Test's |
||||
[event listener API](http://code.google.com/p/googletest/wiki/V1_6_AdvancedGuide#Extending_Google_Test_by_Handling_Test_Events) |
||||
to report a test failure to your testing framework properly. You'll need to |
||||
implement the `OnTestPartResult()` method of the event listener interface, but it |
||||
should be straightforward. |
||||
|
||||
If this turns out to be too much work, we suggest that you stick with |
||||
Google Test, which works with Google Mock seamlessly (in fact, it is |
||||
technically part of Google Mock.). If there is a reason that you |
||||
cannot use Google Test, please let us know. |
||||
|
||||
# Setting Expectations # |
||||
The key to using a mock object successfully is to set the _right expectations_ on it. If you set the expectations too strict, your test will fail as the result of unrelated changes. If you set them too loose, bugs can slip through. You want to do it just right such that your test can catch exactly the kind of bugs you intend it to catch. Google Mock provides the necessary means for you to do it "just right." |
||||
|
||||
## General Syntax ## |
||||
In Google Mock we use the `EXPECT_CALL()` macro to set an expectation on a mock method. The general syntax is: |
||||
|
||||
``` |
||||
EXPECT_CALL(mock_object, method(matchers)) |
||||
.Times(cardinality) |
||||
.WillOnce(action) |
||||
.WillRepeatedly(action); |
||||
``` |
||||
|
||||
The macro has two arguments: first the mock object, and then the method and its arguments. Note that the two are separated by a comma (`,`), not a period (`.`). (Why using a comma? The answer is that it was necessary for technical reasons.) |
||||
|
||||
The macro can be followed by some optional _clauses_ that provide more information about the expectation. We'll discuss how each clause works in the coming sections. |
||||
|
||||
This syntax is designed to make an expectation read like English. For example, you can probably guess that |
||||
|
||||
``` |
||||
using ::testing::Return;... |
||||
EXPECT_CALL(turtle, GetX()) |
||||
.Times(5) |
||||
.WillOnce(Return(100)) |
||||
.WillOnce(Return(150)) |
||||
.WillRepeatedly(Return(200)); |
||||
``` |
||||
|
||||
says that the `turtle` object's `GetX()` method will be called five times, it will return 100 the first time, 150 the second time, and then 200 every time. Some people like to call this style of syntax a Domain-Specific Language (DSL). |
||||
|
||||
**Note:** Why do we use a macro to do this? It serves two purposes: first it makes expectations easily identifiable (either by `grep` or by a human reader), and second it allows Google Mock to include the source file location of a failed expectation in messages, making debugging easier. |
||||
|
||||
## Matchers: What Arguments Do We Expect? ## |
||||
When a mock function takes arguments, we must specify what arguments we are expecting; for example: |
||||
|
||||
``` |
||||
// Expects the turtle to move forward by 100 units. |
||||
EXPECT_CALL(turtle, Forward(100)); |
||||
``` |
||||
|
||||
Sometimes you may not want to be too specific (Remember that talk about tests being too rigid? Over specification leads to brittle tests and obscures the intent of tests. Therefore we encourage you to specify only what's necessary - no more, no less.). If you care to check that `Forward()` will be called but aren't interested in its actual argument, write `_` as the argument, which means "anything goes": |
||||
|
||||
``` |
||||
using ::testing::_; |
||||
... |
||||
// Expects the turtle to move forward. |
||||
EXPECT_CALL(turtle, Forward(_)); |
||||
``` |
||||
|
||||
`_` is an instance of what we call **matchers**. A matcher is like a predicate and can test whether an argument is what we'd expect. You can use a matcher inside `EXPECT_CALL()` wherever a function argument is expected. |
||||
|
||||
A list of built-in matchers can be found in the [CheatSheet](V1_6_CheatSheet.md). For example, here's the `Ge` (greater than or equal) matcher: |
||||
|
||||
``` |
||||
using ::testing::Ge;... |
||||
EXPECT_CALL(turtle, Forward(Ge(100))); |
||||
``` |
||||
|
||||
This checks that the turtle will be told to go forward by at least 100 units. |
||||
|
||||
## Cardinalities: How Many Times Will It Be Called? ## |
||||
The first clause we can specify following an `EXPECT_CALL()` is `Times()`. We call its argument a **cardinality** as it tells _how many times_ the call should occur. It allows us to repeat an expectation many times without actually writing it as many times. More importantly, a cardinality can be "fuzzy", just like a matcher can be. This allows a user to express the intent of a test exactly. |
||||
|
||||
An interesting special case is when we say `Times(0)`. You may have guessed - it means that the function shouldn't be called with the given arguments at all, and Google Mock will report a Google Test failure whenever the function is (wrongfully) called. |
||||
|
||||
We've seen `AtLeast(n)` as an example of fuzzy cardinalities earlier. For the list of built-in cardinalities you can use, see the [CheatSheet](V1_6_CheatSheet.md). |
||||
|
||||
The `Times()` clause can be omitted. **If you omit `Times()`, Google Mock will infer the cardinality for you.** The rules are easy to remember: |
||||
|
||||
* If **neither** `WillOnce()` **nor** `WillRepeatedly()` is in the `EXPECT_CALL()`, the inferred cardinality is `Times(1)`. |
||||
* If there are `n WillOnce()`'s but **no** `WillRepeatedly()`, where `n` >= 1, the cardinality is `Times(n)`. |
||||
* If there are `n WillOnce()`'s and **one** `WillRepeatedly()`, where `n` >= 0, the cardinality is `Times(AtLeast(n))`. |
||||
|
||||
**Quick quiz:** what do you think will happen if a function is expected to be called twice but actually called four times? |
||||
|
||||
## Actions: What Should It Do? ## |
||||
Remember that a mock object doesn't really have a working implementation? We as users have to tell it what to do when a method is invoked. This is easy in Google Mock. |
||||
|
||||
First, if the return type of a mock function is a built-in type or a pointer, the function has a **default action** (a `void` function will just return, a `bool` function will return `false`, and other functions will return 0). If you don't say anything, this behavior will be used. |
||||
|
||||
Second, if a mock function doesn't have a default action, or the default action doesn't suit you, you can specify the action to be taken each time the expectation matches using a series of `WillOnce()` clauses followed by an optional `WillRepeatedly()`. For example, |
||||
|
||||
``` |
||||
using ::testing::Return;... |
||||
EXPECT_CALL(turtle, GetX()) |
||||
.WillOnce(Return(100)) |
||||
.WillOnce(Return(200)) |
||||
.WillOnce(Return(300)); |
||||
``` |
||||
|
||||
This says that `turtle.GetX()` will be called _exactly three times_ (Google Mock inferred this from how many `WillOnce()` clauses we've written, since we didn't explicitly write `Times()`), and will return 100, 200, and 300 respectively. |
||||
|
||||
``` |
||||
using ::testing::Return;... |
||||
EXPECT_CALL(turtle, GetY()) |
||||
.WillOnce(Return(100)) |
||||
.WillOnce(Return(200)) |
||||
.WillRepeatedly(Return(300)); |
||||
``` |
||||
|
||||
says that `turtle.GetY()` will be called _at least twice_ (Google Mock knows this as we've written two `WillOnce()` clauses and a `WillRepeatedly()` while having no explicit `Times()`), will return 100 the first time, 200 the second time, and 300 from the third time on. |
||||
|
||||
Of course, if you explicitly write a `Times()`, Google Mock will not try to infer the cardinality itself. What if the number you specified is larger than there are `WillOnce()` clauses? Well, after all `WillOnce()`s are used up, Google Mock will do the _default_ action for the function every time (unless, of course, you have a `WillRepeatedly()`.). |
||||
|
||||
What can we do inside `WillOnce()` besides `Return()`? You can return a reference using `ReturnRef(variable)`, or invoke a pre-defined function, among [others](http://code.google.com/p/googlemock/wiki/V1_6_CheatSheet#Actions). |
||||
|
||||
**Important note:** The `EXPECT_CALL()` statement evaluates the action clause only once, even though the action may be performed many times. Therefore you must be careful about side effects. The following may not do what you want: |
||||
|
||||
``` |
||||
int n = 100; |
||||
EXPECT_CALL(turtle, GetX()) |
||||
.Times(4) |
||||
.WillRepeatedly(Return(n++)); |
||||
``` |
||||
|
||||
Instead of returning 100, 101, 102, ..., consecutively, this mock function will always return 100 as `n++` is only evaluated once. Similarly, `Return(new Foo)` will create a new `Foo` object when the `EXPECT_CALL()` is executed, and will return the same pointer every time. If you want the side effect to happen every time, you need to define a custom action, which we'll teach in the [CookBook](V1_6_CookBook.md). |
||||
|
||||
Time for another quiz! What do you think the following means? |
||||
|
||||
``` |
||||
using ::testing::Return;... |
||||
EXPECT_CALL(turtle, GetY()) |
||||
.Times(4) |
||||
.WillOnce(Return(100)); |
||||
``` |
||||
|
||||
Obviously `turtle.GetY()` is expected to be called four times. But if you think it will return 100 every time, think twice! Remember that one `WillOnce()` clause will be consumed each time the function is invoked and the default action will be taken afterwards. So the right answer is that `turtle.GetY()` will return 100 the first time, but **return 0 from the second time on**, as returning 0 is the default action for `int` functions. |
||||
|
||||
## Using Multiple Expectations ## |
||||
So far we've only shown examples where you have a single expectation. More realistically, you're going to specify expectations on multiple mock methods, which may be from multiple mock objects. |
||||
|
||||
By default, when a mock method is invoked, Google Mock will search the expectations in the **reverse order** they are defined, and stop when an active expectation that matches the arguments is found (you can think of it as "newer rules override older ones."). If the matching expectation cannot take any more calls, you will get an upper-bound-violated failure. Here's an example: |
||||
|
||||
``` |
||||
using ::testing::_;... |
||||
EXPECT_CALL(turtle, Forward(_)); // #1 |
||||
EXPECT_CALL(turtle, Forward(10)) // #2 |
||||
.Times(2); |
||||
``` |
||||
|
||||
If `Forward(10)` is called three times in a row, the third time it will be an error, as the last matching expectation (#2) has been saturated. If, however, the third `Forward(10)` call is replaced by `Forward(20)`, then it would be OK, as now #1 will be the matching expectation. |
||||
|
||||
**Side note:** Why does Google Mock search for a match in the _reverse_ order of the expectations? The reason is that this allows a user to set up the default expectations in a mock object's constructor or the test fixture's set-up phase and then customize the mock by writing more specific expectations in the test body. So, if you have two expectations on the same method, you want to put the one with more specific matchers **after** the other, or the more specific rule would be shadowed by the more general one that comes after it. |
||||
|
||||
## Ordered vs Unordered Calls ## |
||||
By default, an expectation can match a call even though an earlier expectation hasn't been satisfied. In other words, the calls don't have to occur in the order the expectations are specified. |
||||
|
||||
Sometimes, you may want all the expected calls to occur in a strict order. To say this in Google Mock is easy: |
||||
|
||||
``` |
||||
using ::testing::InSequence;... |
||||
TEST(FooTest, DrawsLineSegment) { |
||||
... |
||||
{ |
||||
InSequence dummy; |
||||
|
||||
EXPECT_CALL(turtle, PenDown()); |
||||
EXPECT_CALL(turtle, Forward(100)); |
||||
EXPECT_CALL(turtle, PenUp()); |
||||
} |
||||
Foo(); |
||||
} |
||||
``` |
||||
|
||||
By creating an object of type `InSequence`, all expectations in its scope are put into a _sequence_ and have to occur _sequentially_. Since we are just relying on the constructor and destructor of this object to do the actual work, its name is really irrelevant. |
||||
|
||||
In this example, we test that `Foo()` calls the three expected functions in the order as written. If a call is made out-of-order, it will be an error. |
||||
|
||||
(What if you care about the relative order of some of the calls, but not all of them? Can you specify an arbitrary partial order? The answer is ... yes! If you are impatient, the details can be found in the [CookBook](V1_6_CookBook.md).) |
||||
|
||||
## All Expectations Are Sticky (Unless Said Otherwise) ## |
||||
Now let's do a quick quiz to see how well you can use this mock stuff already. How would you test that the turtle is asked to go to the origin _exactly twice_ (you want to ignore any other instructions it receives)? |
||||
|
||||
After you've come up with your answer, take a look at ours and compare notes (solve it yourself first - don't cheat!): |
||||
|
||||
``` |
||||
using ::testing::_;... |
||||
EXPECT_CALL(turtle, GoTo(_, _)) // #1 |
||||
.Times(AnyNumber()); |
||||
EXPECT_CALL(turtle, GoTo(0, 0)) // #2 |
||||
.Times(2); |
||||
``` |
||||
|
||||
Suppose `turtle.GoTo(0, 0)` is called three times. In the third time, Google Mock will see that the arguments match expectation #2 (remember that we always pick the last matching expectation). Now, since we said that there should be only two such calls, Google Mock will report an error immediately. This is basically what we've told you in the "Using Multiple Expectations" section above. |
||||
|
||||
This example shows that **expectations in Google Mock are "sticky" by default**, in the sense that they remain active even after we have reached their invocation upper bounds. This is an important rule to remember, as it affects the meaning of the spec, and is **different** to how it's done in many other mocking frameworks (Why'd we do that? Because we think our rule makes the common cases easier to express and understand.). |
||||
|
||||
Simple? Let's see if you've really understood it: what does the following code say? |
||||
|
||||
``` |
||||
using ::testing::Return; |
||||
... |
||||
for (int i = n; i > 0; i--) { |
||||
EXPECT_CALL(turtle, GetX()) |
||||
.WillOnce(Return(10*i)); |
||||
} |
||||
``` |
||||
|
||||
If you think it says that `turtle.GetX()` will be called `n` times and will return 10, 20, 30, ..., consecutively, think twice! The problem is that, as we said, expectations are sticky. So, the second time `turtle.GetX()` is called, the last (latest) `EXPECT_CALL()` statement will match, and will immediately lead to an "upper bound exceeded" error - this piece of code is not very useful! |
||||
|
||||
One correct way of saying that `turtle.GetX()` will return 10, 20, 30, ..., is to explicitly say that the expectations are _not_ sticky. In other words, they should _retire_ as soon as they are saturated: |
||||
|
||||
``` |
||||
using ::testing::Return; |
||||
... |
||||
for (int i = n; i > 0; i--) { |
||||
EXPECT_CALL(turtle, GetX()) |
||||
.WillOnce(Return(10*i)) |
||||
.RetiresOnSaturation(); |
||||
} |
||||
``` |
||||
|
||||
And, there's a better way to do it: in this case, we expect the calls to occur in a specific order, and we line up the actions to match the order. Since the order is important here, we should make it explicit using a sequence: |
||||
|
||||
``` |
||||
using ::testing::InSequence; |
||||
using ::testing::Return; |
||||
... |
||||
{ |
||||
InSequence s; |
||||
|
||||
for (int i = 1; i <= n; i++) { |
||||
EXPECT_CALL(turtle, GetX()) |
||||
.WillOnce(Return(10*i)) |
||||
.RetiresOnSaturation(); |
||||
} |
||||
} |
||||
``` |
||||
|
||||
By the way, the other situation where an expectation may _not_ be sticky is when it's in a sequence - as soon as another expectation that comes after it in the sequence has been used, it automatically retires (and will never be used to match any call). |
||||
|
||||
## Uninteresting Calls ## |
||||
A mock object may have many methods, and not all of them are that interesting. For example, in some tests we may not care about how many times `GetX()` and `GetY()` get called. |
||||
|
||||
In Google Mock, if you are not interested in a method, just don't say anything about it. If a call to this method occurs, you'll see a warning in the test output, but it won't be a failure. |
||||
|
||||
# What Now? # |
||||
Congratulations! You've learned enough about Google Mock to start using it. Now, you might want to join the [googlemock](http://groups.google.com/group/googlemock) discussion group and actually write some tests using Google Mock - it will be fun. Hey, it may even be addictive - you've been warned. |
||||
|
||||
Then, if you feel like increasing your mock quotient, you should move on to the [CookBook](V1_6_CookBook.md). You can learn many advanced features of Google Mock there -- and advance your level of enjoyment and testing bliss. |
@ -1,628 +0,0 @@ |
||||
|
||||
|
||||
Please send your questions to the |
||||
[googlemock](http://groups.google.com/group/googlemock) discussion |
||||
group. If you need help with compiler errors, make sure you have |
||||
tried [Google Mock Doctor](#How_am_I_supposed_to_make_sense_of_these_horrible_template_error.md) first. |
||||
|
||||
## When I call a method on my mock object, the method for the real object is invoked instead. What's the problem? ## |
||||
|
||||
In order for a method to be mocked, it must be _virtual_, unless you use the [high-perf dependency injection technique](http://code.google.com/p/googlemock/wiki/V1_6_CookBook#Mocking_Nonvirtual_Methods). |
||||
|
||||
## I wrote some matchers. After I upgraded to a new version of Google Mock, they no longer compile. What's going on? ## |
||||
|
||||
After version 1.4.0 of Google Mock was released, we had an idea on how |
||||
to make it easier to write matchers that can generate informative |
||||
messages efficiently. We experimented with this idea and liked what |
||||
we saw. Therefore we decided to implement it. |
||||
|
||||
Unfortunately, this means that if you have defined your own matchers |
||||
by implementing `MatcherInterface` or using `MakePolymorphicMatcher()`, |
||||
your definitions will no longer compile. Matchers defined using the |
||||
`MATCHER*` family of macros are not affected. |
||||
|
||||
Sorry for the hassle if your matchers are affected. We believe it's |
||||
in everyone's long-term interest to make this change sooner than |
||||
later. Fortunately, it's usually not hard to migrate an existing |
||||
matcher to the new API. Here's what you need to do: |
||||
|
||||
If you wrote your matcher like this: |
||||
``` |
||||
// Old matcher definition that doesn't work with the latest |
||||
// Google Mock. |
||||
using ::testing::MatcherInterface; |
||||
... |
||||
class MyWonderfulMatcher : public MatcherInterface<MyType> { |
||||
public: |
||||
... |
||||
virtual bool Matches(MyType value) const { |
||||
// Returns true if value matches. |
||||
return value.GetFoo() > 5; |
||||
} |
||||
... |
||||
}; |
||||
``` |
||||
|
||||
you'll need to change it to: |
||||
``` |
||||
// New matcher definition that works with the latest Google Mock. |
||||
using ::testing::MatcherInterface; |
||||
using ::testing::MatchResultListener; |
||||
... |
||||
class MyWonderfulMatcher : public MatcherInterface<MyType> { |
||||
public: |
||||
... |
||||
virtual bool MatchAndExplain(MyType value, |
||||
MatchResultListener* listener) const { |
||||
// Returns true if value matches. |
||||
return value.GetFoo() > 5; |
||||
} |
||||
... |
||||
}; |
||||
``` |
||||
(i.e. rename `Matches()` to `MatchAndExplain()` and give it a second |
||||
argument of type `MatchResultListener*`.) |
||||
|
||||
If you were also using `ExplainMatchResultTo()` to improve the matcher |
||||
message: |
||||
``` |
||||
// Old matcher definition that doesn't work with the lastest |
||||
// Google Mock. |
||||
using ::testing::MatcherInterface; |
||||
... |
||||
class MyWonderfulMatcher : public MatcherInterface<MyType> { |
||||
public: |
||||
... |
||||
virtual bool Matches(MyType value) const { |
||||
// Returns true if value matches. |
||||
return value.GetFoo() > 5; |
||||
} |
||||
|
||||
virtual void ExplainMatchResultTo(MyType value, |
||||
::std::ostream* os) const { |
||||
// Prints some helpful information to os to help |
||||
// a user understand why value matches (or doesn't match). |
||||
*os << "the Foo property is " << value.GetFoo(); |
||||
} |
||||
... |
||||
}; |
||||
``` |
||||
|
||||
you should move the logic of `ExplainMatchResultTo()` into |
||||
`MatchAndExplain()`, using the `MatchResultListener` argument where |
||||
the `::std::ostream` was used: |
||||
``` |
||||
// New matcher definition that works with the latest Google Mock. |
||||
using ::testing::MatcherInterface; |
||||
using ::testing::MatchResultListener; |
||||
... |
||||
class MyWonderfulMatcher : public MatcherInterface<MyType> { |
||||
public: |
||||
... |
||||
virtual bool MatchAndExplain(MyType value, |
||||
MatchResultListener* listener) const { |
||||
// Returns true if value matches. |
||||
*listener << "the Foo property is " << value.GetFoo(); |
||||
return value.GetFoo() > 5; |
||||
} |
||||
... |
||||
}; |
||||
``` |
||||
|
||||
If your matcher is defined using `MakePolymorphicMatcher()`: |
||||
``` |
||||
// Old matcher definition that doesn't work with the latest |
||||
// Google Mock. |
||||
using ::testing::MakePolymorphicMatcher; |
||||
... |
||||
class MyGreatMatcher { |
||||
public: |
||||
... |
||||
bool Matches(MyType value) const { |
||||
// Returns true if value matches. |
||||
return value.GetBar() < 42; |
||||
} |
||||
... |
||||
}; |
||||
... MakePolymorphicMatcher(MyGreatMatcher()) ... |
||||
``` |
||||
|
||||
you should rename the `Matches()` method to `MatchAndExplain()` and |
||||
add a `MatchResultListener*` argument (the same as what you need to do |
||||
for matchers defined by implementing `MatcherInterface`): |
||||
``` |
||||
// New matcher definition that works with the latest Google Mock. |
||||
using ::testing::MakePolymorphicMatcher; |
||||
using ::testing::MatchResultListener; |
||||
... |
||||
class MyGreatMatcher { |
||||
public: |
||||
... |
||||
bool MatchAndExplain(MyType value, |
||||
MatchResultListener* listener) const { |
||||
// Returns true if value matches. |
||||
return value.GetBar() < 42; |
||||
} |
||||
... |
||||
}; |
||||
... MakePolymorphicMatcher(MyGreatMatcher()) ... |
||||
``` |
||||
|
||||
If your polymorphic matcher uses `ExplainMatchResultTo()` for better |
||||
failure messages: |
||||
``` |
||||
// Old matcher definition that doesn't work with the latest |
||||
// Google Mock. |
||||
using ::testing::MakePolymorphicMatcher; |
||||
... |
||||
class MyGreatMatcher { |
||||
public: |
||||
... |
||||
bool Matches(MyType value) const { |
||||
// Returns true if value matches. |
||||
return value.GetBar() < 42; |
||||
} |
||||
... |
||||
}; |
||||
void ExplainMatchResultTo(const MyGreatMatcher& matcher, |
||||
MyType value, |
||||
::std::ostream* os) { |
||||
// Prints some helpful information to os to help |
||||
// a user understand why value matches (or doesn't match). |
||||
*os << "the Bar property is " << value.GetBar(); |
||||
} |
||||
... MakePolymorphicMatcher(MyGreatMatcher()) ... |
||||
``` |
||||
|
||||
you'll need to move the logic inside `ExplainMatchResultTo()` to |
||||
`MatchAndExplain()`: |
||||
``` |
||||
// New matcher definition that works with the latest Google Mock. |
||||
using ::testing::MakePolymorphicMatcher; |
||||
using ::testing::MatchResultListener; |
||||
... |
||||
class MyGreatMatcher { |
||||
public: |
||||
... |
||||
bool MatchAndExplain(MyType value, |
||||
MatchResultListener* listener) const { |
||||
// Returns true if value matches. |
||||
*listener << "the Bar property is " << value.GetBar(); |
||||
return value.GetBar() < 42; |
||||
} |
||||
... |
||||
}; |
||||
... MakePolymorphicMatcher(MyGreatMatcher()) ... |
||||
``` |
||||
|
||||
For more information, you can read these |
||||
[two](http://code.google.com/p/googlemock/wiki/V1_6_CookBook#Writing_New_Monomorphic_Matchers) |
||||
[recipes](http://code.google.com/p/googlemock/wiki/V1_6_CookBook#Writing_New_Polymorphic_Matchers) |
||||
from the cookbook. As always, you |
||||
are welcome to post questions on `googlemock@googlegroups.com` if you |
||||
need any help. |
||||
|
||||
## When using Google Mock, do I have to use Google Test as the testing framework? I have my favorite testing framework and don't want to switch. ## |
||||
|
||||
Google Mock works out of the box with Google Test. However, it's easy |
||||
to configure it to work with any testing framework of your choice. |
||||
[Here](http://code.google.com/p/googlemock/wiki/V1_6_ForDummies#Using_Google_Mock_with_Any_Testing_Framework) is how. |
||||
|
||||
## How am I supposed to make sense of these horrible template errors? ## |
||||
|
||||
If you are confused by the compiler errors gcc threw at you, |
||||
try consulting the _Google Mock Doctor_ tool first. What it does is to |
||||
scan stdin for gcc error messages, and spit out diagnoses on the |
||||
problems (we call them diseases) your code has. |
||||
|
||||
To "install", run command: |
||||
``` |
||||
alias gmd='<path to googlemock>/scripts/gmock_doctor.py' |
||||
``` |
||||
|
||||
To use it, do: |
||||
``` |
||||
<your-favorite-build-command> <your-test> 2>&1 | gmd |
||||
``` |
||||
|
||||
For example: |
||||
``` |
||||
make my_test 2>&1 | gmd |
||||
``` |
||||
|
||||
Or you can run `gmd` and copy-n-paste gcc's error messages to it. |
||||
|
||||
## Can I mock a variadic function? ## |
||||
|
||||
You cannot mock a variadic function (i.e. a function taking ellipsis |
||||
(`...`) arguments) directly in Google Mock. |
||||
|
||||
The problem is that in general, there is _no way_ for a mock object to |
||||
know how many arguments are passed to the variadic method, and what |
||||
the arguments' types are. Only the _author of the base class_ knows |
||||
the protocol, and we cannot look into his head. |
||||
|
||||
Therefore, to mock such a function, the _user_ must teach the mock |
||||
object how to figure out the number of arguments and their types. One |
||||
way to do it is to provide overloaded versions of the function. |
||||
|
||||
Ellipsis arguments are inherited from C and not really a C++ feature. |
||||
They are unsafe to use and don't work with arguments that have |
||||
constructors or destructors. Therefore we recommend to avoid them in |
||||
C++ as much as possible. |
||||
|
||||
## MSVC gives me warning C4301 or C4373 when I define a mock method with a const parameter. Why? ## |
||||
|
||||
If you compile this using Microsoft Visual C++ 2005 SP1: |
||||
``` |
||||
class Foo { |
||||
... |
||||
virtual void Bar(const int i) = 0; |
||||
}; |
||||
|
||||
class MockFoo : public Foo { |
||||
... |
||||
MOCK_METHOD1(Bar, void(const int i)); |
||||
}; |
||||
``` |
||||
You may get the following warning: |
||||
``` |
||||
warning C4301: 'MockFoo::Bar': overriding virtual function only differs from 'Foo::Bar' by const/volatile qualifier |
||||
``` |
||||
|
||||
This is a MSVC bug. The same code compiles fine with gcc ,for |
||||
example. If you use Visual C++ 2008 SP1, you would get the warning: |
||||
``` |
||||
warning C4373: 'MockFoo::Bar': virtual function overrides 'Foo::Bar', previous versions of the compiler did not override when parameters only differed by const/volatile qualifiers |
||||
``` |
||||
|
||||
In C++, if you _declare_ a function with a `const` parameter, the |
||||
`const` modifier is _ignored_. Therefore, the `Foo` base class above |
||||
is equivalent to: |
||||
``` |
||||
class Foo { |
||||
... |
||||
virtual void Bar(int i) = 0; // int or const int? Makes no difference. |
||||
}; |
||||
``` |
||||
|
||||
In fact, you can _declare_ Bar() with an `int` parameter, and _define_ |
||||
it with a `const int` parameter. The compiler will still match them |
||||
up. |
||||
|
||||
Since making a parameter `const` is meaningless in the method |
||||
_declaration_, we recommend to remove it in both `Foo` and `MockFoo`. |
||||
That should workaround the VC bug. |
||||
|
||||
Note that we are talking about the _top-level_ `const` modifier here. |
||||
If the function parameter is passed by pointer or reference, declaring |
||||
the _pointee_ or _referee_ as `const` is still meaningful. For |
||||
example, the following two declarations are _not_ equivalent: |
||||
``` |
||||
void Bar(int* p); // Neither p nor *p is const. |
||||
void Bar(const int* p); // p is not const, but *p is. |
||||
``` |
||||
|
||||
## I have a huge mock class, and Microsoft Visual C++ runs out of memory when compiling it. What can I do? ## |
||||
|
||||
We've noticed that when the `/clr` compiler flag is used, Visual C++ |
||||
uses 5~6 times as much memory when compiling a mock class. We suggest |
||||
to avoid `/clr` when compiling native C++ mocks. |
||||
|
||||
## I can't figure out why Google Mock thinks my expectations are not satisfied. What should I do? ## |
||||
|
||||
You might want to run your test with |
||||
`--gmock_verbose=info`. This flag lets Google Mock print a trace |
||||
of every mock function call it receives. By studying the trace, |
||||
you'll gain insights on why the expectations you set are not met. |
||||
|
||||
## How can I assert that a function is NEVER called? ## |
||||
|
||||
``` |
||||
EXPECT_CALL(foo, Bar(_)) |
||||
.Times(0); |
||||
``` |
||||
|
||||
## I have a failed test where Google Mock tells me TWICE that a particular expectation is not satisfied. Isn't this redundant? ## |
||||
|
||||
When Google Mock detects a failure, it prints relevant information |
||||
(the mock function arguments, the state of relevant expectations, and |
||||
etc) to help the user debug. If another failure is detected, Google |
||||
Mock will do the same, including printing the state of relevant |
||||
expectations. |
||||
|
||||
Sometimes an expectation's state didn't change between two failures, |
||||
and you'll see the same description of the state twice. They are |
||||
however _not_ redundant, as they refer to _different points in time_. |
||||
The fact they are the same _is_ interesting information. |
||||
|
||||
## I get a heap check failure when using a mock object, but using a real object is fine. What can be wrong? ## |
||||
|
||||
Does the class (hopefully a pure interface) you are mocking have a |
||||
virtual destructor? |
||||
|
||||
Whenever you derive from a base class, make sure its destructor is |
||||
virtual. Otherwise Bad Things will happen. Consider the following |
||||
code: |
||||
|
||||
``` |
||||
class Base { |
||||
public: |
||||
// Not virtual, but should be. |
||||
~Base() { ... } |
||||
... |
||||
}; |
||||
|
||||
class Derived : public Base { |
||||
public: |
||||
... |
||||
private: |
||||
std::string value_; |
||||
}; |
||||
|
||||
... |
||||
Base* p = new Derived; |
||||
... |
||||
delete p; // Surprise! ~Base() will be called, but ~Derived() will not |
||||
// - value_ is leaked. |
||||
``` |
||||
|
||||
By changing `~Base()` to virtual, `~Derived()` will be correctly |
||||
called when `delete p` is executed, and the heap checker |
||||
will be happy. |
||||
|
||||
## The "newer expectations override older ones" rule makes writing expectations awkward. Why does Google Mock do that? ## |
||||
|
||||
When people complain about this, often they are referring to code like: |
||||
|
||||
``` |
||||
// foo.Bar() should be called twice, return 1 the first time, and return |
||||
// 2 the second time. However, I have to write the expectations in the |
||||
// reverse order. This sucks big time!!! |
||||
EXPECT_CALL(foo, Bar()) |
||||
.WillOnce(Return(2)) |
||||
.RetiresOnSaturation(); |
||||
EXPECT_CALL(foo, Bar()) |
||||
.WillOnce(Return(1)) |
||||
.RetiresOnSaturation(); |
||||
``` |
||||
|
||||
The problem is that they didn't pick the **best** way to express the test's |
||||
intent. |
||||
|
||||
By default, expectations don't have to be matched in _any_ particular |
||||
order. If you want them to match in a certain order, you need to be |
||||
explicit. This is Google Mock's (and jMock's) fundamental philosophy: it's |
||||
easy to accidentally over-specify your tests, and we want to make it |
||||
harder to do so. |
||||
|
||||
There are two better ways to write the test spec. You could either |
||||
put the expectations in sequence: |
||||
|
||||
``` |
||||
// foo.Bar() should be called twice, return 1 the first time, and return |
||||
// 2 the second time. Using a sequence, we can write the expectations |
||||
// in their natural order. |
||||
{ |
||||
InSequence s; |
||||
EXPECT_CALL(foo, Bar()) |
||||
.WillOnce(Return(1)) |
||||
.RetiresOnSaturation(); |
||||
EXPECT_CALL(foo, Bar()) |
||||
.WillOnce(Return(2)) |
||||
.RetiresOnSaturation(); |
||||
} |
||||
``` |
||||
|
||||
or you can put the sequence of actions in the same expectation: |
||||
|
||||
``` |
||||
// foo.Bar() should be called twice, return 1 the first time, and return |
||||
// 2 the second time. |
||||
EXPECT_CALL(foo, Bar()) |
||||
.WillOnce(Return(1)) |
||||
.WillOnce(Return(2)) |
||||
.RetiresOnSaturation(); |
||||
``` |
||||
|
||||
Back to the original questions: why does Google Mock search the |
||||
expectations (and `ON_CALL`s) from back to front? Because this |
||||
allows a user to set up a mock's behavior for the common case early |
||||
(e.g. in the mock's constructor or the test fixture's set-up phase) |
||||
and customize it with more specific rules later. If Google Mock |
||||
searches from front to back, this very useful pattern won't be |
||||
possible. |
||||
|
||||
## Google Mock prints a warning when a function without EXPECT\_CALL is called, even if I have set its behavior using ON\_CALL. Would it be reasonable not to show the warning in this case? ## |
||||
|
||||
When choosing between being neat and being safe, we lean toward the |
||||
latter. So the answer is that we think it's better to show the |
||||
warning. |
||||
|
||||
Often people write `ON_CALL`s in the mock object's |
||||
constructor or `SetUp()`, as the default behavior rarely changes from |
||||
test to test. Then in the test body they set the expectations, which |
||||
are often different for each test. Having an `ON_CALL` in the set-up |
||||
part of a test doesn't mean that the calls are expected. If there's |
||||
no `EXPECT_CALL` and the method is called, it's possibly an error. If |
||||
we quietly let the call go through without notifying the user, bugs |
||||
may creep in unnoticed. |
||||
|
||||
If, however, you are sure that the calls are OK, you can write |
||||
|
||||
``` |
||||
EXPECT_CALL(foo, Bar(_)) |
||||
.WillRepeatedly(...); |
||||
``` |
||||
|
||||
instead of |
||||
|
||||
``` |
||||
ON_CALL(foo, Bar(_)) |
||||
.WillByDefault(...); |
||||
``` |
||||
|
||||
This tells Google Mock that you do expect the calls and no warning should be |
||||
printed. |
||||
|
||||
Also, you can control the verbosity using the `--gmock_verbose` flag. |
||||
If you find the output too noisy when debugging, just choose a less |
||||
verbose level. |
||||
|
||||
## How can I delete the mock function's argument in an action? ## |
||||
|
||||
If you find yourself needing to perform some action that's not |
||||
supported by Google Mock directly, remember that you can define your own |
||||
actions using |
||||
[MakeAction()](http://code.google.com/p/googlemock/wiki/V1_6_CookBook#Writing_New_Actions) or |
||||
[MakePolymorphicAction()](http://code.google.com/p/googlemock/wiki/V1_6_CookBook#Writing_New_Polymorphic_Actions), |
||||
or you can write a stub function and invoke it using |
||||
[Invoke()](http://code.google.com/p/googlemock/wiki/V1_6_CookBook#Using_Functions_Methods_Functors). |
||||
|
||||
## MOCK\_METHODn()'s second argument looks funny. Why don't you use the MOCK\_METHODn(Method, return\_type, arg\_1, ..., arg\_n) syntax? ## |
||||
|
||||
What?! I think it's beautiful. :-) |
||||
|
||||
While which syntax looks more natural is a subjective matter to some |
||||
extent, Google Mock's syntax was chosen for several practical advantages it |
||||
has. |
||||
|
||||
Try to mock a function that takes a map as an argument: |
||||
``` |
||||
virtual int GetSize(const map<int, std::string>& m); |
||||
``` |
||||
|
||||
Using the proposed syntax, it would be: |
||||
``` |
||||
MOCK_METHOD1(GetSize, int, const map<int, std::string>& m); |
||||
``` |
||||
|
||||
Guess what? You'll get a compiler error as the compiler thinks that |
||||
`const map<int, std::string>& m` are **two**, not one, arguments. To work |
||||
around this you can use `typedef` to give the map type a name, but |
||||
that gets in the way of your work. Google Mock's syntax avoids this |
||||
problem as the function's argument types are protected inside a pair |
||||
of parentheses: |
||||
``` |
||||
// This compiles fine. |
||||
MOCK_METHOD1(GetSize, int(const map<int, std::string>& m)); |
||||
``` |
||||
|
||||
You still need a `typedef` if the return type contains an unprotected |
||||
comma, but that's much rarer. |
||||
|
||||
Other advantages include: |
||||
1. `MOCK_METHOD1(Foo, int, bool)` can leave a reader wonder whether the method returns `int` or `bool`, while there won't be such confusion using Google Mock's syntax. |
||||
1. The way Google Mock describes a function type is nothing new, although many people may not be familiar with it. The same syntax was used in C, and the `function` library in `tr1` uses this syntax extensively. Since `tr1` will become a part of the new version of STL, we feel very comfortable to be consistent with it. |
||||
1. The function type syntax is also used in other parts of Google Mock's API (e.g. the action interface) in order to make the implementation tractable. A user needs to learn it anyway in order to utilize Google Mock's more advanced features. We'd as well stick to the same syntax in `MOCK_METHOD*`! |
||||
|
||||
## My code calls a static/global function. Can I mock it? ## |
||||
|
||||
You can, but you need to make some changes. |
||||
|
||||
In general, if you find yourself needing to mock a static function, |
||||
it's a sign that your modules are too tightly coupled (and less |
||||
flexible, less reusable, less testable, etc). You are probably better |
||||
off defining a small interface and call the function through that |
||||
interface, which then can be easily mocked. It's a bit of work |
||||
initially, but usually pays for itself quickly. |
||||
|
||||
This Google Testing Blog |
||||
[post](http://googletesting.blogspot.com/2008/06/defeat-static-cling.html) |
||||
says it excellently. Check it out. |
||||
|
||||
## My mock object needs to do complex stuff. It's a lot of pain to specify the actions. Google Mock sucks! ## |
||||
|
||||
I know it's not a question, but you get an answer for free any way. :-) |
||||
|
||||
With Google Mock, you can create mocks in C++ easily. And people might be |
||||
tempted to use them everywhere. Sometimes they work great, and |
||||
sometimes you may find them, well, a pain to use. So, what's wrong in |
||||
the latter case? |
||||
|
||||
When you write a test without using mocks, you exercise the code and |
||||
assert that it returns the correct value or that the system is in an |
||||
expected state. This is sometimes called "state-based testing". |
||||
|
||||
Mocks are great for what some call "interaction-based" testing: |
||||
instead of checking the system state at the very end, mock objects |
||||
verify that they are invoked the right way and report an error as soon |
||||
as it arises, giving you a handle on the precise context in which the |
||||
error was triggered. This is often more effective and economical to |
||||
do than state-based testing. |
||||
|
||||
If you are doing state-based testing and using a test double just to |
||||
simulate the real object, you are probably better off using a fake. |
||||
Using a mock in this case causes pain, as it's not a strong point for |
||||
mocks to perform complex actions. If you experience this and think |
||||
that mocks suck, you are just not using the right tool for your |
||||
problem. Or, you might be trying to solve the wrong problem. :-) |
||||
|
||||
## I got a warning "Uninteresting function call encountered - default action taken.." Should I panic? ## |
||||
|
||||
By all means, NO! It's just an FYI. |
||||
|
||||
What it means is that you have a mock function, you haven't set any |
||||
expectations on it (by Google Mock's rule this means that you are not |
||||
interested in calls to this function and therefore it can be called |
||||
any number of times), and it is called. That's OK - you didn't say |
||||
it's not OK to call the function! |
||||
|
||||
What if you actually meant to disallow this function to be called, but |
||||
forgot to write `EXPECT_CALL(foo, Bar()).Times(0)`? While |
||||
one can argue that it's the user's fault, Google Mock tries to be nice and |
||||
prints you a note. |
||||
|
||||
So, when you see the message and believe that there shouldn't be any |
||||
uninteresting calls, you should investigate what's going on. To make |
||||
your life easier, Google Mock prints the function name and arguments |
||||
when an uninteresting call is encountered. |
||||
|
||||
## I want to define a custom action. Should I use Invoke() or implement the action interface? ## |
||||
|
||||
Either way is fine - you want to choose the one that's more convenient |
||||
for your circumstance. |
||||
|
||||
Usually, if your action is for a particular function type, defining it |
||||
using `Invoke()` should be easier; if your action can be used in |
||||
functions of different types (e.g. if you are defining |
||||
`Return(value)`), `MakePolymorphicAction()` is |
||||
easiest. Sometimes you want precise control on what types of |
||||
functions the action can be used in, and implementing |
||||
`ActionInterface` is the way to go here. See the implementation of |
||||
`Return()` in `include/gmock/gmock-actions.h` for an example. |
||||
|
||||
## I'm using the set-argument-pointee action, and the compiler complains about "conflicting return type specified". What does it mean? ## |
||||
|
||||
You got this error as Google Mock has no idea what value it should return |
||||
when the mock method is called. `SetArgPointee()` says what the |
||||
side effect is, but doesn't say what the return value should be. You |
||||
need `DoAll()` to chain a `SetArgPointee()` with a `Return()`. |
||||
|
||||
See this [recipe](http://code.google.com/p/googlemock/wiki/V1_6_CookBook#Mocking_Side_Effects) for more details and an example. |
||||
|
||||
|
||||
## My question is not in your FAQ! ## |
||||
|
||||
If you cannot find the answer to your question in this FAQ, there are |
||||
some other resources you can use: |
||||
|
||||
1. read other [wiki pages](http://code.google.com/p/googlemock/w/list), |
||||
1. search the mailing list [archive](http://groups.google.com/group/googlemock/topics), |
||||
1. ask it on [googlemock@googlegroups.com](mailto:googlemock@googlegroups.com) and someone will answer it (to prevent spam, we require you to join the [discussion group](http://groups.google.com/group/googlemock) before you can post.). |
||||
|
||||
Please note that creating an issue in the |
||||
[issue tracker](http://code.google.com/p/googlemock/issues/list) is _not_ |
||||
a good way to get your answer, as it is monitored infrequently by a |
||||
very small number of people. |
||||
|
||||
When asking a question, it's helpful to provide as much of the |
||||
following information as possible (people cannot help you if there's |
||||
not enough information in your question): |
||||
|
||||
* the version (or the revision number if you check out from SVN directly) of Google Mock you use (Google Mock is under active development, so it's possible that your problem has been solved in a later version), |
||||
* your operating system, |
||||
* the name and version of your compiler, |
||||
* the complete command line flags you give to your compiler, |
||||
* the complete compiler error messages (if the question is about compilation), |
||||
* the _actual_ code (ideally, a minimal but complete program) that has the problem you encounter. |
@ -1,556 +0,0 @@ |
||||
|
||||
|
||||
# Defining a Mock Class # |
||||
|
||||
## Mocking a Normal Class ## |
||||
|
||||
Given |
||||
``` |
||||
class Foo { |
||||
... |
||||
virtual ~Foo(); |
||||
virtual int GetSize() const = 0; |
||||
virtual string Describe(const char* name) = 0; |
||||
virtual string Describe(int type) = 0; |
||||
virtual bool Process(Bar elem, int count) = 0; |
||||
}; |
||||
``` |
||||
(note that `~Foo()` **must** be virtual) we can define its mock as |
||||
``` |
||||
#include "gmock/gmock.h" |
||||
|
||||
class MockFoo : public Foo { |
||||
MOCK_CONST_METHOD0(GetSize, int()); |
||||
MOCK_METHOD1(Describe, string(const char* name)); |
||||
MOCK_METHOD1(Describe, string(int type)); |
||||
MOCK_METHOD2(Process, bool(Bar elem, int count)); |
||||
}; |
||||
``` |
||||
|
||||
To create a "nice" mock object which ignores all uninteresting calls, |
||||
or a "strict" mock object, which treats them as failures: |
||||
``` |
||||
NiceMock<MockFoo> nice_foo; // The type is a subclass of MockFoo. |
||||
StrictMock<MockFoo> strict_foo; // The type is a subclass of MockFoo. |
||||
``` |
||||
|
||||
## Mocking a Class Template ## |
||||
|
||||
To mock |
||||
``` |
||||
template <typename Elem> |
||||
class StackInterface { |
||||
public: |
||||
... |
||||
virtual ~StackInterface(); |
||||
virtual int GetSize() const = 0; |
||||
virtual void Push(const Elem& x) = 0; |
||||
}; |
||||
``` |
||||
(note that `~StackInterface()` **must** be virtual) just append `_T` to the `MOCK_*` macros: |
||||
``` |
||||
template <typename Elem> |
||||
class MockStack : public StackInterface<Elem> { |
||||
public: |
||||
... |
||||
MOCK_CONST_METHOD0_T(GetSize, int()); |
||||
MOCK_METHOD1_T(Push, void(const Elem& x)); |
||||
}; |
||||
``` |
||||
|
||||
## Specifying Calling Conventions for Mock Functions ## |
||||
|
||||
If your mock function doesn't use the default calling convention, you |
||||
can specify it by appending `_WITH_CALLTYPE` to any of the macros |
||||
described in the previous two sections and supplying the calling |
||||
convention as the first argument to the macro. For example, |
||||
``` |
||||
MOCK_METHOD_1_WITH_CALLTYPE(STDMETHODCALLTYPE, Foo, bool(int n)); |
||||
MOCK_CONST_METHOD2_WITH_CALLTYPE(STDMETHODCALLTYPE, Bar, int(double x, double y)); |
||||
``` |
||||
where `STDMETHODCALLTYPE` is defined by `<objbase.h>` on Windows. |
||||
|
||||
# Using Mocks in Tests # |
||||
|
||||
The typical flow is: |
||||
1. Import the Google Mock names you need to use. All Google Mock names are in the `testing` namespace unless they are macros or otherwise noted. |
||||
1. Create the mock objects. |
||||
1. Optionally, set the default actions of the mock objects. |
||||
1. Set your expectations on the mock objects (How will they be called? What wil they do?). |
||||
1. Exercise code that uses the mock objects; if necessary, check the result using [Google Test](http://code.google.com/p/googletest/) assertions. |
||||
1. When a mock objects is destructed, Google Mock automatically verifies that all expectations on it have been satisfied. |
||||
|
||||
Here is an example: |
||||
``` |
||||
using ::testing::Return; // #1 |
||||
|
||||
TEST(BarTest, DoesThis) { |
||||
MockFoo foo; // #2 |
||||
|
||||
ON_CALL(foo, GetSize()) // #3 |
||||
.WillByDefault(Return(1)); |
||||
// ... other default actions ... |
||||
|
||||
EXPECT_CALL(foo, Describe(5)) // #4 |
||||
.Times(3) |
||||
.WillRepeatedly(Return("Category 5")); |
||||
// ... other expectations ... |
||||
|
||||
EXPECT_EQ("good", MyProductionFunction(&foo)); // #5 |
||||
} // #6 |
||||
``` |
||||
|
||||
# Setting Default Actions # |
||||
|
||||
Google Mock has a **built-in default action** for any function that |
||||
returns `void`, `bool`, a numeric value, or a pointer. |
||||
|
||||
To customize the default action for functions with return type `T` globally: |
||||
``` |
||||
using ::testing::DefaultValue; |
||||
|
||||
DefaultValue<T>::Set(value); // Sets the default value to be returned. |
||||
// ... use the mocks ... |
||||
DefaultValue<T>::Clear(); // Resets the default value. |
||||
``` |
||||
|
||||
To customize the default action for a particular method, use `ON_CALL()`: |
||||
``` |
||||
ON_CALL(mock_object, method(matchers)) |
||||
.With(multi_argument_matcher) ? |
||||
.WillByDefault(action); |
||||
``` |
||||
|
||||
# Setting Expectations # |
||||
|
||||
`EXPECT_CALL()` sets **expectations** on a mock method (How will it be |
||||
called? What will it do?): |
||||
``` |
||||
EXPECT_CALL(mock_object, method(matchers)) |
||||
.With(multi_argument_matcher) ? |
||||
.Times(cardinality) ? |
||||
.InSequence(sequences) * |
||||
.After(expectations) * |
||||
.WillOnce(action) * |
||||
.WillRepeatedly(action) ? |
||||
.RetiresOnSaturation(); ? |
||||
``` |
||||
|
||||
If `Times()` is omitted, the cardinality is assumed to be: |
||||
|
||||
* `Times(1)` when there is neither `WillOnce()` nor `WillRepeatedly()`; |
||||
* `Times(n)` when there are `n WillOnce()`s but no `WillRepeatedly()`, where `n` >= 1; or |
||||
* `Times(AtLeast(n))` when there are `n WillOnce()`s and a `WillRepeatedly()`, where `n` >= 0. |
||||
|
||||
A method with no `EXPECT_CALL()` is free to be invoked _any number of times_, and the default action will be taken each time. |
||||
|
||||
# Matchers # |
||||
|
||||
A **matcher** matches a _single_ argument. You can use it inside |
||||
`ON_CALL()` or `EXPECT_CALL()`, or use it to validate a value |
||||
directly: |
||||
|
||||
| `EXPECT_THAT(value, matcher)` | Asserts that `value` matches `matcher`. | |
||||
|:------------------------------|:----------------------------------------| |
||||
| `ASSERT_THAT(value, matcher)` | The same as `EXPECT_THAT(value, matcher)`, except that it generates a **fatal** failure. | |
||||
|
||||
Built-in matchers (where `argument` is the function argument) are |
||||
divided into several categories: |
||||
|
||||
## Wildcard ## |
||||
|`_`|`argument` can be any value of the correct type.| |
||||
|:--|:-----------------------------------------------| |
||||
|`A<type>()` or `An<type>()`|`argument` can be any value of type `type`. | |
||||
|
||||
## Generic Comparison ## |
||||
|
||||
|`Eq(value)` or `value`|`argument == value`| |
||||
|:---------------------|:------------------| |
||||
|`Ge(value)` |`argument >= value`| |
||||
|`Gt(value)` |`argument > value` | |
||||
|`Le(value)` |`argument <= value`| |
||||
|`Lt(value)` |`argument < value` | |
||||
|`Ne(value)` |`argument != value`| |
||||
|`IsNull()` |`argument` is a `NULL` pointer (raw or smart).| |
||||
|`NotNull()` |`argument` is a non-null pointer (raw or smart).| |
||||
|`Ref(variable)` |`argument` is a reference to `variable`.| |
||||
|`TypedEq<type>(value)`|`argument` has type `type` and is equal to `value`. You may need to use this instead of `Eq(value)` when the mock function is overloaded.| |
||||
|
||||
Except `Ref()`, these matchers make a _copy_ of `value` in case it's |
||||
modified or destructed later. If the compiler complains that `value` |
||||
doesn't have a public copy constructor, try wrap it in `ByRef()`, |
||||
e.g. `Eq(ByRef(non_copyable_value))`. If you do that, make sure |
||||
`non_copyable_value` is not changed afterwards, or the meaning of your |
||||
matcher will be changed. |
||||
|
||||
## Floating-Point Matchers ## |
||||
|
||||
|`DoubleEq(a_double)`|`argument` is a `double` value approximately equal to `a_double`, treating two NaNs as unequal.| |
||||
|:-------------------|:----------------------------------------------------------------------------------------------| |
||||
|`FloatEq(a_float)` |`argument` is a `float` value approximately equal to `a_float`, treating two NaNs as unequal. | |
||||
|`NanSensitiveDoubleEq(a_double)`|`argument` is a `double` value approximately equal to `a_double`, treating two NaNs as equal. | |
||||
|`NanSensitiveFloatEq(a_float)`|`argument` is a `float` value approximately equal to `a_float`, treating two NaNs as equal. | |
||||
|
||||
The above matchers use ULP-based comparison (the same as used in |
||||
[Google Test](http://code.google.com/p/googletest/)). They |
||||
automatically pick a reasonable error bound based on the absolute |
||||
value of the expected value. `DoubleEq()` and `FloatEq()` conform to |
||||
the IEEE standard, which requires comparing two NaNs for equality to |
||||
return false. The `NanSensitive*` version instead treats two NaNs as |
||||
equal, which is often what a user wants. |
||||
|
||||
|`DoubleNear(a_double, max_abs_error)`|`argument` is a `double` value close to `a_double` (absolute error <= `max_abs_error`), treating two NaNs as unequal.| |
||||
|:------------------------------------|:--------------------------------------------------------------------------------------------------------------------| |
||||
|`FloatNear(a_float, max_abs_error)` |`argument` is a `float` value close to `a_float` (absolute error <= `max_abs_error`), treating two NaNs as unequal. | |
||||
|`NanSensitiveDoubleNear(a_double, max_abs_error)`|`argument` is a `double` value close to `a_double` (absolute error <= `max_abs_error`), treating two NaNs as equal. | |
||||
|`NanSensitiveFloatNear(a_float, max_abs_error)`|`argument` is a `float` value close to `a_float` (absolute error <= `max_abs_error`), treating two NaNs as equal. | |
||||
|
||||
## String Matchers ## |
||||
|
||||
The `argument` can be either a C string or a C++ string object: |
||||
|
||||
|`ContainsRegex(string)`|`argument` matches the given regular expression.| |
||||
|:----------------------|:-----------------------------------------------| |
||||
|`EndsWith(suffix)` |`argument` ends with string `suffix`. | |
||||
|`HasSubstr(string)` |`argument` contains `string` as a sub-string. | |
||||
|`MatchesRegex(string)` |`argument` matches the given regular expression with the match starting at the first character and ending at the last character.| |
||||
|`StartsWith(prefix)` |`argument` starts with string `prefix`. | |
||||
|`StrCaseEq(string)` |`argument` is equal to `string`, ignoring case. | |
||||
|`StrCaseNe(string)` |`argument` is not equal to `string`, ignoring case.| |
||||
|`StrEq(string)` |`argument` is equal to `string`. | |
||||
|`StrNe(string)` |`argument` is not equal to `string`. | |
||||
|
||||
`ContainsRegex()` and `MatchesRegex()` use the regular expression |
||||
syntax defined |
||||
[here](http://code.google.com/p/googletest/wiki/AdvancedGuide#Regular_Expression_Syntax). |
||||
`StrCaseEq()`, `StrCaseNe()`, `StrEq()`, and `StrNe()` work for wide |
||||
strings as well. |
||||
|
||||
## Container Matchers ## |
||||
|
||||
Most STL-style containers support `==`, so you can use |
||||
`Eq(expected_container)` or simply `expected_container` to match a |
||||
container exactly. If you want to write the elements in-line, |
||||
match them more flexibly, or get more informative messages, you can use: |
||||
|
||||
| `ContainerEq(container)` | The same as `Eq(container)` except that the failure message also includes which elements are in one container but not the other. | |
||||
|:-------------------------|:---------------------------------------------------------------------------------------------------------------------------------| |
||||
| `Contains(e)` | `argument` contains an element that matches `e`, which can be either a value or a matcher. | |
||||
| `Each(e)` | `argument` is a container where _every_ element matches `e`, which can be either a value or a matcher. | |
||||
| `ElementsAre(e0, e1, ..., en)` | `argument` has `n + 1` elements, where the i-th element matches `ei`, which can be a value or a matcher. 0 to 10 arguments are allowed. | |
||||
| `ElementsAreArray({ e0, e1, ..., en })`, `ElementsAreArray(array)`, or `ElementsAreArray(array, count)` | The same as `ElementsAre()` except that the expected element values/matchers come from an initializer list, vector, or C-style array. | |
||||
| `IsEmpty()` | `argument` is an empty container (`container.empty()`). | |
||||
| `Pointwise(m, container)` | `argument` contains the same number of elements as in `container`, and for all i, (the i-th element in `argument`, the i-th element in `container`) match `m`, which is a matcher on 2-tuples. E.g. `Pointwise(Le(), upper_bounds)` verifies that each element in `argument` doesn't exceed the corresponding element in `upper_bounds`. See more detail below. | |
||||
| `SizeIs(m)` | `argument` is a container whose size matches `m`. E.g. `SizeIs(2)` or `SizeIs(Lt(2))`. | |
||||
| `UnorderedElementsAre(e0, e1, ..., en)` | `argument` has `n + 1` elements, and under some permutation each element matches an `ei` (for a different `i`), which can be a value or a matcher. 0 to 10 arguments are allowed. | |
||||
| `UnorderedElementsAreArray({ e0, e1, ..., en })`, `UnorderedElementsAreArray(array)`, or `UnorderedElementsAreArray(array, count)` | The same as `UnorderedElementsAre()` except that the expected element values/matchers come from an initializer list, vector, or C-style array. | |
||||
| `WhenSorted(m)` | When `argument` is sorted using the `<` operator, it matches container matcher `m`. E.g. `WhenSorted(UnorderedElementsAre(1, 2, 3))` verifies that `argument` contains elements `1`, `2`, and `3`, ignoring order. | |
||||
| `WhenSortedBy(comparator, m)` | The same as `WhenSorted(m)`, except that the given comparator instead of `<` is used to sort `argument`. E.g. `WhenSortedBy(std::greater<int>(), ElementsAre(3, 2, 1))`. | |
||||
|
||||
Notes: |
||||
|
||||
* These matchers can also match: |
||||
1. a native array passed by reference (e.g. in `Foo(const int (&a)[5])`), and |
||||
1. an array passed as a pointer and a count (e.g. in `Bar(const T* buffer, int len)` -- see [Multi-argument Matchers](#Multiargument_Matchers.md)). |
||||
* The array being matched may be multi-dimensional (i.e. its elements can be arrays). |
||||
* `m` in `Pointwise(m, ...)` should be a matcher for `std::tr1::tuple<T, U>` where `T` and `U` are the element type of the actual container and the expected container, respectively. For example, to compare two `Foo` containers where `Foo` doesn't support `operator==` but has an `Equals()` method, one might write: |
||||
|
||||
``` |
||||
using ::std::tr1::get; |
||||
MATCHER(FooEq, "") { |
||||
return get<0>(arg).Equals(get<1>(arg)); |
||||
} |
||||
... |
||||
EXPECT_THAT(actual_foos, Pointwise(FooEq(), expected_foos)); |
||||
``` |
||||
|
||||
## Member Matchers ## |
||||
|
||||
|`Field(&class::field, m)`|`argument.field` (or `argument->field` when `argument` is a plain pointer) matches matcher `m`, where `argument` is an object of type _class_.| |
||||
|:------------------------|:---------------------------------------------------------------------------------------------------------------------------------------------| |
||||
|`Key(e)` |`argument.first` matches `e`, which can be either a value or a matcher. E.g. `Contains(Key(Le(5)))` can verify that a `map` contains a key `<= 5`.| |
||||
|`Pair(m1, m2)` |`argument` is an `std::pair` whose `first` field matches `m1` and `second` field matches `m2`. | |
||||
|`Property(&class::property, m)`|`argument.property()` (or `argument->property()` when `argument` is a plain pointer) matches matcher `m`, where `argument` is an object of type _class_.| |
||||
|
||||
## Matching the Result of a Function or Functor ## |
||||
|
||||
|`ResultOf(f, m)`|`f(argument)` matches matcher `m`, where `f` is a function or functor.| |
||||
|:---------------|:---------------------------------------------------------------------| |
||||
|
||||
## Pointer Matchers ## |
||||
|
||||
|`Pointee(m)`|`argument` (either a smart pointer or a raw pointer) points to a value that matches matcher `m`.| |
||||
|:-----------|:-----------------------------------------------------------------------------------------------| |
||||
|
||||
## Multiargument Matchers ## |
||||
|
||||
Technically, all matchers match a _single_ value. A "multi-argument" |
||||
matcher is just one that matches a _tuple_. The following matchers can |
||||
be used to match a tuple `(x, y)`: |
||||
|
||||
|`Eq()`|`x == y`| |
||||
|:-----|:-------| |
||||
|`Ge()`|`x >= y`| |
||||
|`Gt()`|`x > y` | |
||||
|`Le()`|`x <= y`| |
||||
|`Lt()`|`x < y` | |
||||
|`Ne()`|`x != y`| |
||||
|
||||
You can use the following selectors to pick a subset of the arguments |
||||
(or reorder them) to participate in the matching: |
||||
|
||||
|`AllArgs(m)`|Equivalent to `m`. Useful as syntactic sugar in `.With(AllArgs(m))`.| |
||||
|:-----------|:-------------------------------------------------------------------| |
||||
|`Args<N1, N2, ..., Nk>(m)`|The tuple of the `k` selected (using 0-based indices) arguments matches `m`, e.g. `Args<1, 2>(Eq())`.| |
||||
|
||||
## Composite Matchers ## |
||||
|
||||
You can make a matcher from one or more other matchers: |
||||
|
||||
|`AllOf(m1, m2, ..., mn)`|`argument` matches all of the matchers `m1` to `mn`.| |
||||
|:-----------------------|:---------------------------------------------------| |
||||
|`AnyOf(m1, m2, ..., mn)`|`argument` matches at least one of the matchers `m1` to `mn`.| |
||||
|`Not(m)` |`argument` doesn't match matcher `m`. | |
||||
|
||||
## Adapters for Matchers ## |
||||
|
||||
|`MatcherCast<T>(m)`|casts matcher `m` to type `Matcher<T>`.| |
||||
|:------------------|:--------------------------------------| |
||||
|`SafeMatcherCast<T>(m)`| [safely casts](http://code.google.com/p/googlemock/wiki/V1_7_CookBook#Casting_Matchers) matcher `m` to type `Matcher<T>`. | |
||||
|`Truly(predicate)` |`predicate(argument)` returns something considered by C++ to be true, where `predicate` is a function or functor.| |
||||
|
||||
## Matchers as Predicates ## |
||||
|
||||
|`Matches(m)(value)`|evaluates to `true` if `value` matches `m`. You can use `Matches(m)` alone as a unary functor.| |
||||
|:------------------|:---------------------------------------------------------------------------------------------| |
||||
|`ExplainMatchResult(m, value, result_listener)`|evaluates to `true` if `value` matches `m`, explaining the result to `result_listener`. | |
||||
|`Value(value, m)` |evaluates to `true` if `value` matches `m`. | |
||||
|
||||
## Defining Matchers ## |
||||
|
||||
| `MATCHER(IsEven, "") { return (arg % 2) == 0; }` | Defines a matcher `IsEven()` to match an even number. | |
||||
|:-------------------------------------------------|:------------------------------------------------------| |
||||
| `MATCHER_P(IsDivisibleBy, n, "") { *result_listener << "where the remainder is " << (arg % n); return (arg % n) == 0; }` | Defines a macher `IsDivisibleBy(n)` to match a number divisible by `n`. | |
||||
| `MATCHER_P2(IsBetween, a, b, std::string(negation ? "isn't" : "is") + " between " + PrintToString(a) + " and " + PrintToString(b)) { return a <= arg && arg <= b; }` | Defines a matcher `IsBetween(a, b)` to match a value in the range [`a`, `b`]. | |
||||
|
||||
**Notes:** |
||||
|
||||
1. The `MATCHER*` macros cannot be used inside a function or class. |
||||
1. The matcher body must be _purely functional_ (i.e. it cannot have any side effect, and the result must not depend on anything other than the value being matched and the matcher parameters). |
||||
1. You can use `PrintToString(x)` to convert a value `x` of any type to a string. |
||||
|
||||
## Matchers as Test Assertions ## |
||||
|
||||
|`ASSERT_THAT(expression, m)`|Generates a [fatal failure](http://code.google.com/p/googletest/wiki/Primer#Assertions) if the value of `expression` doesn't match matcher `m`.| |
||||
|:---------------------------|:----------------------------------------------------------------------------------------------------------------------------------------------| |
||||
|`EXPECT_THAT(expression, m)`|Generates a non-fatal failure if the value of `expression` doesn't match matcher `m`. | |
||||
|
||||
# Actions # |
||||
|
||||
**Actions** specify what a mock function should do when invoked. |
||||
|
||||
## Returning a Value ## |
||||
|
||||
|`Return()`|Return from a `void` mock function.| |
||||
|:---------|:----------------------------------| |
||||
|`Return(value)`|Return `value`. If the type of `value` is different to the mock function's return type, `value` is converted to the latter type <i>at the time the expectation is set</i>, not when the action is executed.| |
||||
|`ReturnArg<N>()`|Return the `N`-th (0-based) argument.| |
||||
|`ReturnNew<T>(a1, ..., ak)`|Return `new T(a1, ..., ak)`; a different object is created each time.| |
||||
|`ReturnNull()`|Return a null pointer. | |
||||
|`ReturnPointee(ptr)`|Return the value pointed to by `ptr`.| |
||||
|`ReturnRef(variable)`|Return a reference to `variable`. | |
||||
|`ReturnRefOfCopy(value)`|Return a reference to a copy of `value`; the copy lives as long as the action.| |
||||
|
||||
## Side Effects ## |
||||
|
||||
|`Assign(&variable, value)`|Assign `value` to variable.| |
||||
|:-------------------------|:--------------------------| |
||||
| `DeleteArg<N>()` | Delete the `N`-th (0-based) argument, which must be a pointer. | |
||||
| `SaveArg<N>(pointer)` | Save the `N`-th (0-based) argument to `*pointer`. | |
||||
| `SaveArgPointee<N>(pointer)` | Save the value pointed to by the `N`-th (0-based) argument to `*pointer`. | |
||||
| `SetArgReferee<N>(value)` | Assign value to the variable referenced by the `N`-th (0-based) argument. | |
||||
|`SetArgPointee<N>(value)` |Assign `value` to the variable pointed by the `N`-th (0-based) argument.| |
||||
|`SetArgumentPointee<N>(value)`|Same as `SetArgPointee<N>(value)`. Deprecated. Will be removed in v1.7.0.| |
||||
|`SetArrayArgument<N>(first, last)`|Copies the elements in source range [`first`, `last`) to the array pointed to by the `N`-th (0-based) argument, which can be either a pointer or an iterator. The action does not take ownership of the elements in the source range.| |
||||
|`SetErrnoAndReturn(error, value)`|Set `errno` to `error` and return `value`.| |
||||
|`Throw(exception)` |Throws the given exception, which can be any copyable value. Available since v1.1.0.| |
||||
|
||||
## Using a Function or a Functor as an Action ## |
||||
|
||||
|`Invoke(f)`|Invoke `f` with the arguments passed to the mock function, where `f` can be a global/static function or a functor.| |
||||
|:----------|:-----------------------------------------------------------------------------------------------------------------| |
||||
|`Invoke(object_pointer, &class::method)`|Invoke the {method on the object with the arguments passed to the mock function. | |
||||
|`InvokeWithoutArgs(f)`|Invoke `f`, which can be a global/static function or a functor. `f` must take no arguments. | |
||||
|`InvokeWithoutArgs(object_pointer, &class::method)`|Invoke the method on the object, which takes no arguments. | |
||||
|`InvokeArgument<N>(arg1, arg2, ..., argk)`|Invoke the mock function's `N`-th (0-based) argument, which must be a function or a functor, with the `k` arguments.| |
||||
|
||||
The return value of the invoked function is used as the return value |
||||
of the action. |
||||
|
||||
When defining a function or functor to be used with `Invoke*()`, you can declare any unused parameters as `Unused`: |
||||
``` |
||||
double Distance(Unused, double x, double y) { return sqrt(x*x + y*y); } |
||||
... |
||||
EXPECT_CALL(mock, Foo("Hi", _, _)).WillOnce(Invoke(Distance)); |
||||
``` |
||||
|
||||
In `InvokeArgument<N>(...)`, if an argument needs to be passed by reference, wrap it inside `ByRef()`. For example, |
||||
``` |
||||
InvokeArgument<2>(5, string("Hi"), ByRef(foo)) |
||||
``` |
||||
calls the mock function's #2 argument, passing to it `5` and `string("Hi")` by value, and `foo` by reference. |
||||
|
||||
## Default Action ## |
||||
|
||||
|`DoDefault()`|Do the default action (specified by `ON_CALL()` or the built-in one).| |
||||
|:------------|:--------------------------------------------------------------------| |
||||
|
||||
**Note:** due to technical reasons, `DoDefault()` cannot be used inside a composite action - trying to do so will result in a run-time error. |
||||
|
||||
## Composite Actions ## |
||||
|
||||
|`DoAll(a1, a2, ..., an)`|Do all actions `a1` to `an` and return the result of `an` in each invocation. The first `n - 1` sub-actions must return void. | |
||||
|:-----------------------|:-----------------------------------------------------------------------------------------------------------------------------| |
||||
|`IgnoreResult(a)` |Perform action `a` and ignore its result. `a` must not return void. | |
||||
|`WithArg<N>(a)` |Pass the `N`-th (0-based) argument of the mock function to action `a` and perform it. | |
||||
|`WithArgs<N1, N2, ..., Nk>(a)`|Pass the selected (0-based) arguments of the mock function to action `a` and perform it. | |
||||
|`WithoutArgs(a)` |Perform action `a` without any arguments. | |
||||
|
||||
## Defining Actions ## |
||||
|
||||
| `ACTION(Sum) { return arg0 + arg1; }` | Defines an action `Sum()` to return the sum of the mock function's argument #0 and #1. | |
||||
|:--------------------------------------|:---------------------------------------------------------------------------------------| |
||||
| `ACTION_P(Plus, n) { return arg0 + n; }` | Defines an action `Plus(n)` to return the sum of the mock function's argument #0 and `n`. | |
||||
| `ACTION_Pk(Foo, p1, ..., pk) { statements; }` | Defines a parameterized action `Foo(p1, ..., pk)` to execute the given `statements`. | |
||||
|
||||
The `ACTION*` macros cannot be used inside a function or class. |
||||
|
||||
# Cardinalities # |
||||
|
||||
These are used in `Times()` to specify how many times a mock function will be called: |
||||
|
||||
|`AnyNumber()`|The function can be called any number of times.| |
||||
|:------------|:----------------------------------------------| |
||||
|`AtLeast(n)` |The call is expected at least `n` times. | |
||||
|`AtMost(n)` |The call is expected at most `n` times. | |
||||
|`Between(m, n)`|The call is expected between `m` and `n` (inclusive) times.| |
||||
|`Exactly(n) or n`|The call is expected exactly `n` times. In particular, the call should never happen when `n` is 0.| |
||||
|
||||
# Expectation Order # |
||||
|
||||
By default, the expectations can be matched in _any_ order. If some |
||||
or all expectations must be matched in a given order, there are two |
||||
ways to specify it. They can be used either independently or |
||||
together. |
||||
|
||||
## The After Clause ## |
||||
|
||||
``` |
||||
using ::testing::Expectation; |
||||
... |
||||
Expectation init_x = EXPECT_CALL(foo, InitX()); |
||||
Expectation init_y = EXPECT_CALL(foo, InitY()); |
||||
EXPECT_CALL(foo, Bar()) |
||||
.After(init_x, init_y); |
||||
``` |
||||
says that `Bar()` can be called only after both `InitX()` and |
||||
`InitY()` have been called. |
||||
|
||||
If you don't know how many pre-requisites an expectation has when you |
||||
write it, you can use an `ExpectationSet` to collect them: |
||||
|
||||
``` |
||||
using ::testing::ExpectationSet; |
||||
... |
||||
ExpectationSet all_inits; |
||||
for (int i = 0; i < element_count; i++) { |
||||
all_inits += EXPECT_CALL(foo, InitElement(i)); |
||||
} |
||||
EXPECT_CALL(foo, Bar()) |
||||
.After(all_inits); |
||||
``` |
||||
says that `Bar()` can be called only after all elements have been |
||||
initialized (but we don't care about which elements get initialized |
||||
before the others). |
||||
|
||||
Modifying an `ExpectationSet` after using it in an `.After()` doesn't |
||||
affect the meaning of the `.After()`. |
||||
|
||||
## Sequences ## |
||||
|
||||
When you have a long chain of sequential expectations, it's easier to |
||||
specify the order using **sequences**, which don't require you to given |
||||
each expectation in the chain a different name. <i>All expected<br> |
||||
calls</i> in the same sequence must occur in the order they are |
||||
specified. |
||||
|
||||
``` |
||||
using ::testing::Sequence; |
||||
Sequence s1, s2; |
||||
... |
||||
EXPECT_CALL(foo, Reset()) |
||||
.InSequence(s1, s2) |
||||
.WillOnce(Return(true)); |
||||
EXPECT_CALL(foo, GetSize()) |
||||
.InSequence(s1) |
||||
.WillOnce(Return(1)); |
||||
EXPECT_CALL(foo, Describe(A<const char*>())) |
||||
.InSequence(s2) |
||||
.WillOnce(Return("dummy")); |
||||
``` |
||||
says that `Reset()` must be called before _both_ `GetSize()` _and_ |
||||
`Describe()`, and the latter two can occur in any order. |
||||
|
||||
To put many expectations in a sequence conveniently: |
||||
``` |
||||
using ::testing::InSequence; |
||||
{ |
||||
InSequence dummy; |
||||
|
||||
EXPECT_CALL(...)...; |
||||
EXPECT_CALL(...)...; |
||||
... |
||||
EXPECT_CALL(...)...; |
||||
} |
||||
``` |
||||
says that all expected calls in the scope of `dummy` must occur in |
||||
strict order. The name `dummy` is irrelevant.) |
||||
|
||||
# Verifying and Resetting a Mock # |
||||
|
||||
Google Mock will verify the expectations on a mock object when it is destructed, or you can do it earlier: |
||||
``` |
||||
using ::testing::Mock; |
||||
... |
||||
// Verifies and removes the expectations on mock_obj; |
||||
// returns true iff successful. |
||||
Mock::VerifyAndClearExpectations(&mock_obj); |
||||
... |
||||
// Verifies and removes the expectations on mock_obj; |
||||
// also removes the default actions set by ON_CALL(); |
||||
// returns true iff successful. |
||||
Mock::VerifyAndClear(&mock_obj); |
||||
``` |
||||
|
||||
You can also tell Google Mock that a mock object can be leaked and doesn't |
||||
need to be verified: |
||||
``` |
||||
Mock::AllowLeak(&mock_obj); |
||||
``` |
||||
|
||||
# Mock Classes # |
||||
|
||||
Google Mock defines a convenient mock class template |
||||
``` |
||||
class MockFunction<R(A1, ..., An)> { |
||||
public: |
||||
MOCK_METHODn(Call, R(A1, ..., An)); |
||||
}; |
||||
``` |
||||
See this [recipe](http://code.google.com/p/googlemock/wiki/V1_7_CookBook#Using_Check_Points) for one application of it. |
||||
|
||||
# Flags # |
||||
|
||||
| `--gmock_catch_leaked_mocks=0` | Don't report leaked mock objects as failures. | |
||||
|:-------------------------------|:----------------------------------------------| |
||||
| `--gmock_verbose=LEVEL` | Sets the default verbosity level (`info`, `warning`, or `error`) of Google Mock messages. | |
File diff suppressed because it is too large
Load Diff
@ -1,12 +0,0 @@ |
||||
This page lists all documentation wiki pages for Google Mock **(the SVN trunk version)** |
||||
- **if you use a released version of Google Mock, please read the documentation for that specific version instead.** |
||||
|
||||
* [ForDummies](V1_7_ForDummies.md) -- start here if you are new to Google Mock. |
||||
* [CheatSheet](V1_7_CheatSheet.md) -- a quick reference. |
||||
* [CookBook](V1_7_CookBook.md) -- recipes for doing various tasks using Google Mock. |
||||
* [FrequentlyAskedQuestions](V1_7_FrequentlyAskedQuestions.md) -- check here before asking a question on the mailing list. |
||||
|
||||
To contribute code to Google Mock, read: |
||||
|
||||
* [DevGuide](DevGuide.md) -- read this _before_ writing your first patch. |
||||
* [Pump Manual](http://code.google.com/p/googletest/wiki/PumpManual) -- how we generate some of Google Mock's source files. |
@ -1,439 +0,0 @@ |
||||
|
||||
|
||||
(**Note:** If you get compiler errors that you don't understand, be sure to consult [Google Mock Doctor](http://code.google.com/p/googlemock/wiki/V1_7_FrequentlyAskedQuestions#How_am_I_supposed_to_make_sense_of_these_horrible_template_error).) |
||||
|
||||
# What Is Google C++ Mocking Framework? # |
||||
When you write a prototype or test, often it's not feasible or wise to rely on real objects entirely. A **mock object** implements the same interface as a real object (so it can be used as one), but lets you specify at run time how it will be used and what it should do (which methods will be called? in which order? how many times? with what arguments? what will they return? etc). |
||||
|
||||
**Note:** It is easy to confuse the term _fake objects_ with mock objects. Fakes and mocks actually mean very different things in the Test-Driven Development (TDD) community: |
||||
|
||||
* **Fake** objects have working implementations, but usually take some shortcut (perhaps to make the operations less expensive), which makes them not suitable for production. An in-memory file system would be an example of a fake. |
||||
* **Mocks** are objects pre-programmed with _expectations_, which form a specification of the calls they are expected to receive. |
||||
|
||||
If all this seems too abstract for you, don't worry - the most important thing to remember is that a mock allows you to check the _interaction_ between itself and code that uses it. The difference between fakes and mocks will become much clearer once you start to use mocks. |
||||
|
||||
**Google C++ Mocking Framework** (or **Google Mock** for short) is a library (sometimes we also call it a "framework" to make it sound cool) for creating mock classes and using them. It does to C++ what [jMock](http://www.jmock.org/) and [EasyMock](http://www.easymock.org/) do to Java. |
||||
|
||||
Using Google Mock involves three basic steps: |
||||
|
||||
1. Use some simple macros to describe the interface you want to mock, and they will expand to the implementation of your mock class; |
||||
1. Create some mock objects and specify its expectations and behavior using an intuitive syntax; |
||||
1. Exercise code that uses the mock objects. Google Mock will catch any violation of the expectations as soon as it arises. |
||||
|
||||
# Why Google Mock? # |
||||
While mock objects help you remove unnecessary dependencies in tests and make them fast and reliable, using mocks manually in C++ is _hard_: |
||||
|
||||
* Someone has to implement the mocks. The job is usually tedious and error-prone. No wonder people go great distance to avoid it. |
||||
* The quality of those manually written mocks is a bit, uh, unpredictable. You may see some really polished ones, but you may also see some that were hacked up in a hurry and have all sorts of ad hoc restrictions. |
||||
* The knowledge you gained from using one mock doesn't transfer to the next. |
||||
|
||||
In contrast, Java and Python programmers have some fine mock frameworks, which automate the creation of mocks. As a result, mocking is a proven effective technique and widely adopted practice in those communities. Having the right tool absolutely makes the difference. |
||||
|
||||
Google Mock was built to help C++ programmers. It was inspired by [jMock](http://www.jmock.org/) and [EasyMock](http://www.easymock.org/), but designed with C++'s specifics in mind. It is your friend if any of the following problems is bothering you: |
||||
|
||||
* You are stuck with a sub-optimal design and wish you had done more prototyping before it was too late, but prototyping in C++ is by no means "rapid". |
||||
* Your tests are slow as they depend on too many libraries or use expensive resources (e.g. a database). |
||||
* Your tests are brittle as some resources they use are unreliable (e.g. the network). |
||||
* You want to test how your code handles a failure (e.g. a file checksum error), but it's not easy to cause one. |
||||
* You need to make sure that your module interacts with other modules in the right way, but it's hard to observe the interaction; therefore you resort to observing the side effects at the end of the action, which is awkward at best. |
||||
* You want to "mock out" your dependencies, except that they don't have mock implementations yet; and, frankly, you aren't thrilled by some of those hand-written mocks. |
||||
|
||||
We encourage you to use Google Mock as: |
||||
|
||||
* a _design_ tool, for it lets you experiment with your interface design early and often. More iterations lead to better designs! |
||||
* a _testing_ tool to cut your tests' outbound dependencies and probe the interaction between your module and its collaborators. |
||||
|
||||
# Getting Started # |
||||
Using Google Mock is easy! Inside your C++ source file, just `#include` `"gtest/gtest.h"` and `"gmock/gmock.h"`, and you are ready to go. |
||||
|
||||
# A Case for Mock Turtles # |
||||
Let's look at an example. Suppose you are developing a graphics program that relies on a LOGO-like API for drawing. How would you test that it does the right thing? Well, you can run it and compare the screen with a golden screen snapshot, but let's admit it: tests like this are expensive to run and fragile (What if you just upgraded to a shiny new graphics card that has better anti-aliasing? Suddenly you have to update all your golden images.). It would be too painful if all your tests are like this. Fortunately, you learned about Dependency Injection and know the right thing to do: instead of having your application talk to the drawing API directly, wrap the API in an interface (say, `Turtle`) and code to that interface: |
||||
|
||||
``` |
||||
class Turtle { |
||||
... |
||||
virtual ~Turtle() {} |
||||
virtual void PenUp() = 0; |
||||
virtual void PenDown() = 0; |
||||
virtual void Forward(int distance) = 0; |
||||
virtual void Turn(int degrees) = 0; |
||||
virtual void GoTo(int x, int y) = 0; |
||||
virtual int GetX() const = 0; |
||||
virtual int GetY() const = 0; |
||||
}; |
||||
``` |
||||
|
||||
(Note that the destructor of `Turtle` **must** be virtual, as is the case for **all** classes you intend to inherit from - otherwise the destructor of the derived class will not be called when you delete an object through a base pointer, and you'll get corrupted program states like memory leaks.) |
||||
|
||||
You can control whether the turtle's movement will leave a trace using `PenUp()` and `PenDown()`, and control its movement using `Forward()`, `Turn()`, and `GoTo()`. Finally, `GetX()` and `GetY()` tell you the current position of the turtle. |
||||
|
||||
Your program will normally use a real implementation of this interface. In tests, you can use a mock implementation instead. This allows you to easily check what drawing primitives your program is calling, with what arguments, and in which order. Tests written this way are much more robust (they won't break because your new machine does anti-aliasing differently), easier to read and maintain (the intent of a test is expressed in the code, not in some binary images), and run _much, much faster_. |
||||
|
||||
# Writing the Mock Class # |
||||
If you are lucky, the mocks you need to use have already been implemented by some nice people. If, however, you find yourself in the position to write a mock class, relax - Google Mock turns this task into a fun game! (Well, almost.) |
||||
|
||||
## How to Define It ## |
||||
Using the `Turtle` interface as example, here are the simple steps you need to follow: |
||||
|
||||
1. Derive a class `MockTurtle` from `Turtle`. |
||||
1. Take a _virtual_ function of `Turtle` (while it's possible to [mock non-virtual methods using templates](http://code.google.com/p/googlemock/wiki/V1_7_CookBook#Mocking_Nonvirtual_Methods), it's much more involved). Count how many arguments it has. |
||||
1. In the `public:` section of the child class, write `MOCK_METHODn();` (or `MOCK_CONST_METHODn();` if you are mocking a `const` method), where `n` is the number of the arguments; if you counted wrong, shame on you, and a compiler error will tell you so. |
||||
1. Now comes the fun part: you take the function signature, cut-and-paste the _function name_ as the _first_ argument to the macro, and leave what's left as the _second_ argument (in case you're curious, this is the _type of the function_). |
||||
1. Repeat until all virtual functions you want to mock are done. |
||||
|
||||
After the process, you should have something like: |
||||
|
||||
``` |
||||
#include "gmock/gmock.h" // Brings in Google Mock. |
||||
class MockTurtle : public Turtle { |
||||
public: |
||||
... |
||||
MOCK_METHOD0(PenUp, void()); |
||||
MOCK_METHOD0(PenDown, void()); |
||||
MOCK_METHOD1(Forward, void(int distance)); |
||||
MOCK_METHOD1(Turn, void(int degrees)); |
||||
MOCK_METHOD2(GoTo, void(int x, int y)); |
||||
MOCK_CONST_METHOD0(GetX, int()); |
||||
MOCK_CONST_METHOD0(GetY, int()); |
||||
}; |
||||
``` |
||||
|
||||
You don't need to define these mock methods somewhere else - the `MOCK_METHOD*` macros will generate the definitions for you. It's that simple! Once you get the hang of it, you can pump out mock classes faster than your source-control system can handle your check-ins. |
||||
|
||||
**Tip:** If even this is too much work for you, you'll find the |
||||
`gmock_gen.py` tool in Google Mock's `scripts/generator/` directory (courtesy of the [cppclean](http://code.google.com/p/cppclean/) project) useful. This command-line |
||||
tool requires that you have Python 2.4 installed. You give it a C++ file and the name of an abstract class defined in it, |
||||
and it will print the definition of the mock class for you. Due to the |
||||
complexity of the C++ language, this script may not always work, but |
||||
it can be quite handy when it does. For more details, read the [user documentation](http://code.google.com/p/googlemock/source/browse/trunk/scripts/generator/README). |
||||
|
||||
## Where to Put It ## |
||||
When you define a mock class, you need to decide where to put its definition. Some people put it in a `*_test.cc`. This is fine when the interface being mocked (say, `Foo`) is owned by the same person or team. Otherwise, when the owner of `Foo` changes it, your test could break. (You can't really expect `Foo`'s maintainer to fix every test that uses `Foo`, can you?) |
||||
|
||||
So, the rule of thumb is: if you need to mock `Foo` and it's owned by others, define the mock class in `Foo`'s package (better, in a `testing` sub-package such that you can clearly separate production code and testing utilities), and put it in a `mock_foo.h`. Then everyone can reference `mock_foo.h` from their tests. If `Foo` ever changes, there is only one copy of `MockFoo` to change, and only tests that depend on the changed methods need to be fixed. |
||||
|
||||
Another way to do it: you can introduce a thin layer `FooAdaptor` on top of `Foo` and code to this new interface. Since you own `FooAdaptor`, you can absorb changes in `Foo` much more easily. While this is more work initially, carefully choosing the adaptor interface can make your code easier to write and more readable (a net win in the long run), as you can choose `FooAdaptor` to fit your specific domain much better than `Foo` does. |
||||
|
||||
# Using Mocks in Tests # |
||||
Once you have a mock class, using it is easy. The typical work flow is: |
||||
|
||||
1. Import the Google Mock names from the `testing` namespace such that you can use them unqualified (You only have to do it once per file. Remember that namespaces are a good idea and good for your health.). |
||||
1. Create some mock objects. |
||||
1. Specify your expectations on them (How many times will a method be called? With what arguments? What should it do? etc.). |
||||
1. Exercise some code that uses the mocks; optionally, check the result using Google Test assertions. If a mock method is called more than expected or with wrong arguments, you'll get an error immediately. |
||||
1. When a mock is destructed, Google Mock will automatically check whether all expectations on it have been satisfied. |
||||
|
||||
Here's an example: |
||||
|
||||
``` |
||||
#include "path/to/mock-turtle.h" |
||||
#include "gmock/gmock.h" |
||||
#include "gtest/gtest.h" |
||||
using ::testing::AtLeast; // #1 |
||||
|
||||
TEST(PainterTest, CanDrawSomething) { |
||||
MockTurtle turtle; // #2 |
||||
EXPECT_CALL(turtle, PenDown()) // #3 |
||||
.Times(AtLeast(1)); |
||||
|
||||
Painter painter(&turtle); // #4 |
||||
|
||||
EXPECT_TRUE(painter.DrawCircle(0, 0, 10)); |
||||
} // #5 |
||||
|
||||
int main(int argc, char** argv) { |
||||
// The following line must be executed to initialize Google Mock |
||||
// (and Google Test) before running the tests. |
||||
::testing::InitGoogleMock(&argc, argv); |
||||
return RUN_ALL_TESTS(); |
||||
} |
||||
``` |
||||
|
||||
As you might have guessed, this test checks that `PenDown()` is called at least once. If the `painter` object didn't call this method, your test will fail with a message like this: |
||||
|
||||
``` |
||||
path/to/my_test.cc:119: Failure |
||||
Actual function call count doesn't match this expectation: |
||||
Actually: never called; |
||||
Expected: called at least once. |
||||
``` |
||||
|
||||
**Tip 1:** If you run the test from an Emacs buffer, you can hit `<Enter>` on the line number displayed in the error message to jump right to the failed expectation. |
||||
|
||||
**Tip 2:** If your mock objects are never deleted, the final verification won't happen. Therefore it's a good idea to use a heap leak checker in your tests when you allocate mocks on the heap. |
||||
|
||||
**Important note:** Google Mock requires expectations to be set **before** the mock functions are called, otherwise the behavior is **undefined**. In particular, you mustn't interleave `EXPECT_CALL()`s and calls to the mock functions. |
||||
|
||||
This means `EXPECT_CALL()` should be read as expecting that a call will occur _in the future_, not that a call has occurred. Why does Google Mock work like that? Well, specifying the expectation beforehand allows Google Mock to report a violation as soon as it arises, when the context (stack trace, etc) is still available. This makes debugging much easier. |
||||
|
||||
Admittedly, this test is contrived and doesn't do much. You can easily achieve the same effect without using Google Mock. However, as we shall reveal soon, Google Mock allows you to do _much more_ with the mocks. |
||||
|
||||
## Using Google Mock with Any Testing Framework ## |
||||
If you want to use something other than Google Test (e.g. [CppUnit](http://apps.sourceforge.net/mediawiki/cppunit/index.php?title=Main_Page) or |
||||
[CxxTest](http://cxxtest.tigris.org/)) as your testing framework, just change the `main()` function in the previous section to: |
||||
``` |
||||
int main(int argc, char** argv) { |
||||
// The following line causes Google Mock to throw an exception on failure, |
||||
// which will be interpreted by your testing framework as a test failure. |
||||
::testing::GTEST_FLAG(throw_on_failure) = true; |
||||
::testing::InitGoogleMock(&argc, argv); |
||||
... whatever your testing framework requires ... |
||||
} |
||||
``` |
||||
|
||||
This approach has a catch: it makes Google Mock throw an exception |
||||
from a mock object's destructor sometimes. With some compilers, this |
||||
sometimes causes the test program to crash. You'll still be able to |
||||
notice that the test has failed, but it's not a graceful failure. |
||||
|
||||
A better solution is to use Google Test's |
||||
[event listener API](http://code.google.com/p/googletest/wiki/AdvancedGuide#Extending_Google_Test_by_Handling_Test_Events) |
||||
to report a test failure to your testing framework properly. You'll need to |
||||
implement the `OnTestPartResult()` method of the event listener interface, but it |
||||
should be straightforward. |
||||
|
||||
If this turns out to be too much work, we suggest that you stick with |
||||
Google Test, which works with Google Mock seamlessly (in fact, it is |
||||
technically part of Google Mock.). If there is a reason that you |
||||
cannot use Google Test, please let us know. |
||||
|
||||
# Setting Expectations # |
||||
The key to using a mock object successfully is to set the _right expectations_ on it. If you set the expectations too strict, your test will fail as the result of unrelated changes. If you set them too loose, bugs can slip through. You want to do it just right such that your test can catch exactly the kind of bugs you intend it to catch. Google Mock provides the necessary means for you to do it "just right." |
||||
|
||||
## General Syntax ## |
||||
In Google Mock we use the `EXPECT_CALL()` macro to set an expectation on a mock method. The general syntax is: |
||||
|
||||
``` |
||||
EXPECT_CALL(mock_object, method(matchers)) |
||||
.Times(cardinality) |
||||
.WillOnce(action) |
||||
.WillRepeatedly(action); |
||||
``` |
||||
|
||||
The macro has two arguments: first the mock object, and then the method and its arguments. Note that the two are separated by a comma (`,`), not a period (`.`). (Why using a comma? The answer is that it was necessary for technical reasons.) |
||||
|
||||
The macro can be followed by some optional _clauses_ that provide more information about the expectation. We'll discuss how each clause works in the coming sections. |
||||
|
||||
This syntax is designed to make an expectation read like English. For example, you can probably guess that |
||||
|
||||
``` |
||||
using ::testing::Return;... |
||||
EXPECT_CALL(turtle, GetX()) |
||||
.Times(5) |
||||
.WillOnce(Return(100)) |
||||
.WillOnce(Return(150)) |
||||
.WillRepeatedly(Return(200)); |
||||
``` |
||||
|
||||
says that the `turtle` object's `GetX()` method will be called five times, it will return 100 the first time, 150 the second time, and then 200 every time. Some people like to call this style of syntax a Domain-Specific Language (DSL). |
||||
|
||||
**Note:** Why do we use a macro to do this? It serves two purposes: first it makes expectations easily identifiable (either by `grep` or by a human reader), and second it allows Google Mock to include the source file location of a failed expectation in messages, making debugging easier. |
||||
|
||||
## Matchers: What Arguments Do We Expect? ## |
||||
When a mock function takes arguments, we must specify what arguments we are expecting; for example: |
||||
|
||||
``` |
||||
// Expects the turtle to move forward by 100 units. |
||||
EXPECT_CALL(turtle, Forward(100)); |
||||
``` |
||||
|
||||
Sometimes you may not want to be too specific (Remember that talk about tests being too rigid? Over specification leads to brittle tests and obscures the intent of tests. Therefore we encourage you to specify only what's necessary - no more, no less.). If you care to check that `Forward()` will be called but aren't interested in its actual argument, write `_` as the argument, which means "anything goes": |
||||
|
||||
``` |
||||
using ::testing::_; |
||||
... |
||||
// Expects the turtle to move forward. |
||||
EXPECT_CALL(turtle, Forward(_)); |
||||
``` |
||||
|
||||
`_` is an instance of what we call **matchers**. A matcher is like a predicate and can test whether an argument is what we'd expect. You can use a matcher inside `EXPECT_CALL()` wherever a function argument is expected. |
||||
|
||||
A list of built-in matchers can be found in the [CheatSheet](V1_7_CheatSheet.md). For example, here's the `Ge` (greater than or equal) matcher: |
||||
|
||||
``` |
||||
using ::testing::Ge;... |
||||
EXPECT_CALL(turtle, Forward(Ge(100))); |
||||
``` |
||||
|
||||
This checks that the turtle will be told to go forward by at least 100 units. |
||||
|
||||
## Cardinalities: How Many Times Will It Be Called? ## |
||||
The first clause we can specify following an `EXPECT_CALL()` is `Times()`. We call its argument a **cardinality** as it tells _how many times_ the call should occur. It allows us to repeat an expectation many times without actually writing it as many times. More importantly, a cardinality can be "fuzzy", just like a matcher can be. This allows a user to express the intent of a test exactly. |
||||
|
||||
An interesting special case is when we say `Times(0)`. You may have guessed - it means that the function shouldn't be called with the given arguments at all, and Google Mock will report a Google Test failure whenever the function is (wrongfully) called. |
||||
|
||||
We've seen `AtLeast(n)` as an example of fuzzy cardinalities earlier. For the list of built-in cardinalities you can use, see the [CheatSheet](V1_7_CheatSheet.md). |
||||
|
||||
The `Times()` clause can be omitted. **If you omit `Times()`, Google Mock will infer the cardinality for you.** The rules are easy to remember: |
||||
|
||||
* If **neither** `WillOnce()` **nor** `WillRepeatedly()` is in the `EXPECT_CALL()`, the inferred cardinality is `Times(1)`. |
||||
* If there are `n WillOnce()`'s but **no** `WillRepeatedly()`, where `n` >= 1, the cardinality is `Times(n)`. |
||||
* If there are `n WillOnce()`'s and **one** `WillRepeatedly()`, where `n` >= 0, the cardinality is `Times(AtLeast(n))`. |
||||
|
||||
**Quick quiz:** what do you think will happen if a function is expected to be called twice but actually called four times? |
||||
|
||||
## Actions: What Should It Do? ## |
||||
Remember that a mock object doesn't really have a working implementation? We as users have to tell it what to do when a method is invoked. This is easy in Google Mock. |
||||
|
||||
First, if the return type of a mock function is a built-in type or a pointer, the function has a **default action** (a `void` function will just return, a `bool` function will return `false`, and other functions will return 0). If you don't say anything, this behavior will be used. |
||||
|
||||
Second, if a mock function doesn't have a default action, or the default action doesn't suit you, you can specify the action to be taken each time the expectation matches using a series of `WillOnce()` clauses followed by an optional `WillRepeatedly()`. For example, |
||||
|
||||
``` |
||||
using ::testing::Return;... |
||||
EXPECT_CALL(turtle, GetX()) |
||||
.WillOnce(Return(100)) |
||||
.WillOnce(Return(200)) |
||||
.WillOnce(Return(300)); |
||||
``` |
||||
|
||||
This says that `turtle.GetX()` will be called _exactly three times_ (Google Mock inferred this from how many `WillOnce()` clauses we've written, since we didn't explicitly write `Times()`), and will return 100, 200, and 300 respectively. |
||||
|
||||
``` |
||||
using ::testing::Return;... |
||||
EXPECT_CALL(turtle, GetY()) |
||||
.WillOnce(Return(100)) |
||||
.WillOnce(Return(200)) |
||||
.WillRepeatedly(Return(300)); |
||||
``` |
||||
|
||||
says that `turtle.GetY()` will be called _at least twice_ (Google Mock knows this as we've written two `WillOnce()` clauses and a `WillRepeatedly()` while having no explicit `Times()`), will return 100 the first time, 200 the second time, and 300 from the third time on. |
||||
|
||||
Of course, if you explicitly write a `Times()`, Google Mock will not try to infer the cardinality itself. What if the number you specified is larger than there are `WillOnce()` clauses? Well, after all `WillOnce()`s are used up, Google Mock will do the _default_ action for the function every time (unless, of course, you have a `WillRepeatedly()`.). |
||||
|
||||
What can we do inside `WillOnce()` besides `Return()`? You can return a reference using `ReturnRef(variable)`, or invoke a pre-defined function, among [others](http://code.google.com/p/googlemock/wiki/V1_7_CheatSheet#Actions). |
||||
|
||||
**Important note:** The `EXPECT_CALL()` statement evaluates the action clause only once, even though the action may be performed many times. Therefore you must be careful about side effects. The following may not do what you want: |
||||
|
||||
``` |
||||
int n = 100; |
||||
EXPECT_CALL(turtle, GetX()) |
||||
.Times(4) |
||||
.WillRepeatedly(Return(n++)); |
||||
``` |
||||
|
||||
Instead of returning 100, 101, 102, ..., consecutively, this mock function will always return 100 as `n++` is only evaluated once. Similarly, `Return(new Foo)` will create a new `Foo` object when the `EXPECT_CALL()` is executed, and will return the same pointer every time. If you want the side effect to happen every time, you need to define a custom action, which we'll teach in the [CookBook](V1_7_CookBook.md). |
||||
|
||||
Time for another quiz! What do you think the following means? |
||||
|
||||
``` |
||||
using ::testing::Return;... |
||||
EXPECT_CALL(turtle, GetY()) |
||||
.Times(4) |
||||
.WillOnce(Return(100)); |
||||
``` |
||||
|
||||
Obviously `turtle.GetY()` is expected to be called four times. But if you think it will return 100 every time, think twice! Remember that one `WillOnce()` clause will be consumed each time the function is invoked and the default action will be taken afterwards. So the right answer is that `turtle.GetY()` will return 100 the first time, but **return 0 from the second time on**, as returning 0 is the default action for `int` functions. |
||||
|
||||
## Using Multiple Expectations ## |
||||
So far we've only shown examples where you have a single expectation. More realistically, you're going to specify expectations on multiple mock methods, which may be from multiple mock objects. |
||||
|
||||
By default, when a mock method is invoked, Google Mock will search the expectations in the **reverse order** they are defined, and stop when an active expectation that matches the arguments is found (you can think of it as "newer rules override older ones."). If the matching expectation cannot take any more calls, you will get an upper-bound-violated failure. Here's an example: |
||||
|
||||
``` |
||||
using ::testing::_;... |
||||
EXPECT_CALL(turtle, Forward(_)); // #1 |
||||
EXPECT_CALL(turtle, Forward(10)) // #2 |
||||
.Times(2); |
||||
``` |
||||
|
||||
If `Forward(10)` is called three times in a row, the third time it will be an error, as the last matching expectation (#2) has been saturated. If, however, the third `Forward(10)` call is replaced by `Forward(20)`, then it would be OK, as now #1 will be the matching expectation. |
||||
|
||||
**Side note:** Why does Google Mock search for a match in the _reverse_ order of the expectations? The reason is that this allows a user to set up the default expectations in a mock object's constructor or the test fixture's set-up phase and then customize the mock by writing more specific expectations in the test body. So, if you have two expectations on the same method, you want to put the one with more specific matchers **after** the other, or the more specific rule would be shadowed by the more general one that comes after it. |
||||
|
||||
## Ordered vs Unordered Calls ## |
||||
By default, an expectation can match a call even though an earlier expectation hasn't been satisfied. In other words, the calls don't have to occur in the order the expectations are specified. |
||||
|
||||
Sometimes, you may want all the expected calls to occur in a strict order. To say this in Google Mock is easy: |
||||
|
||||
``` |
||||
using ::testing::InSequence;... |
||||
TEST(FooTest, DrawsLineSegment) { |
||||
... |
||||
{ |
||||
InSequence dummy; |
||||
|
||||
EXPECT_CALL(turtle, PenDown()); |
||||
EXPECT_CALL(turtle, Forward(100)); |
||||
EXPECT_CALL(turtle, PenUp()); |
||||
} |
||||
Foo(); |
||||
} |
||||
``` |
||||
|
||||
By creating an object of type `InSequence`, all expectations in its scope are put into a _sequence_ and have to occur _sequentially_. Since we are just relying on the constructor and destructor of this object to do the actual work, its name is really irrelevant. |
||||
|
||||
In this example, we test that `Foo()` calls the three expected functions in the order as written. If a call is made out-of-order, it will be an error. |
||||
|
||||
(What if you care about the relative order of some of the calls, but not all of them? Can you specify an arbitrary partial order? The answer is ... yes! If you are impatient, the details can be found in the [CookBook](V1_7_CookBook#Expecting_Partially_Ordered_Calls.md).) |
||||
|
||||
## All Expectations Are Sticky (Unless Said Otherwise) ## |
||||
Now let's do a quick quiz to see how well you can use this mock stuff already. How would you test that the turtle is asked to go to the origin _exactly twice_ (you want to ignore any other instructions it receives)? |
||||
|
||||
After you've come up with your answer, take a look at ours and compare notes (solve it yourself first - don't cheat!): |
||||
|
||||
``` |
||||
using ::testing::_;... |
||||
EXPECT_CALL(turtle, GoTo(_, _)) // #1 |
||||
.Times(AnyNumber()); |
||||
EXPECT_CALL(turtle, GoTo(0, 0)) // #2 |
||||
.Times(2); |
||||
``` |
||||
|
||||
Suppose `turtle.GoTo(0, 0)` is called three times. In the third time, Google Mock will see that the arguments match expectation #2 (remember that we always pick the last matching expectation). Now, since we said that there should be only two such calls, Google Mock will report an error immediately. This is basically what we've told you in the "Using Multiple Expectations" section above. |
||||
|
||||
This example shows that **expectations in Google Mock are "sticky" by default**, in the sense that they remain active even after we have reached their invocation upper bounds. This is an important rule to remember, as it affects the meaning of the spec, and is **different** to how it's done in many other mocking frameworks (Why'd we do that? Because we think our rule makes the common cases easier to express and understand.). |
||||
|
||||
Simple? Let's see if you've really understood it: what does the following code say? |
||||
|
||||
``` |
||||
using ::testing::Return; |
||||
... |
||||
for (int i = n; i > 0; i--) { |
||||
EXPECT_CALL(turtle, GetX()) |
||||
.WillOnce(Return(10*i)); |
||||
} |
||||
``` |
||||
|
||||
If you think it says that `turtle.GetX()` will be called `n` times and will return 10, 20, 30, ..., consecutively, think twice! The problem is that, as we said, expectations are sticky. So, the second time `turtle.GetX()` is called, the last (latest) `EXPECT_CALL()` statement will match, and will immediately lead to an "upper bound exceeded" error - this piece of code is not very useful! |
||||
|
||||
One correct way of saying that `turtle.GetX()` will return 10, 20, 30, ..., is to explicitly say that the expectations are _not_ sticky. In other words, they should _retire_ as soon as they are saturated: |
||||
|
||||
``` |
||||
using ::testing::Return; |
||||
... |
||||
for (int i = n; i > 0; i--) { |
||||
EXPECT_CALL(turtle, GetX()) |
||||
.WillOnce(Return(10*i)) |
||||
.RetiresOnSaturation(); |
||||
} |
||||
``` |
||||
|
||||
And, there's a better way to do it: in this case, we expect the calls to occur in a specific order, and we line up the actions to match the order. Since the order is important here, we should make it explicit using a sequence: |
||||
|
||||
``` |
||||
using ::testing::InSequence; |
||||
using ::testing::Return; |
||||
... |
||||
{ |
||||
InSequence s; |
||||
|
||||
for (int i = 1; i <= n; i++) { |
||||
EXPECT_CALL(turtle, GetX()) |
||||
.WillOnce(Return(10*i)) |
||||
.RetiresOnSaturation(); |
||||
} |
||||
} |
||||
``` |
||||
|
||||
By the way, the other situation where an expectation may _not_ be sticky is when it's in a sequence - as soon as another expectation that comes after it in the sequence has been used, it automatically retires (and will never be used to match any call). |
||||
|
||||
## Uninteresting Calls ## |
||||
A mock object may have many methods, and not all of them are that interesting. For example, in some tests we may not care about how many times `GetX()` and `GetY()` get called. |
||||
|
||||
In Google Mock, if you are not interested in a method, just don't say anything about it. If a call to this method occurs, you'll see a warning in the test output, but it won't be a failure. |
||||
|
||||
# What Now? # |
||||
Congratulations! You've learned enough about Google Mock to start using it. Now, you might want to join the [googlemock](http://groups.google.com/group/googlemock) discussion group and actually write some tests using Google Mock - it will be fun. Hey, it may even be addictive - you've been warned. |
||||
|
||||
Then, if you feel like increasing your mock quotient, you should move on to the [CookBook](V1_7_CookBook.md). You can learn many advanced features of Google Mock there -- and advance your level of enjoyment and testing bliss. |
@ -1,628 +0,0 @@ |
||||
|
||||
|
||||
Please send your questions to the |
||||
[googlemock](http://groups.google.com/group/googlemock) discussion |
||||
group. If you need help with compiler errors, make sure you have |
||||
tried [Google Mock Doctor](#How_am_I_supposed_to_make_sense_of_these_horrible_template_error.md) first. |
||||
|
||||
## When I call a method on my mock object, the method for the real object is invoked instead. What's the problem? ## |
||||
|
||||
In order for a method to be mocked, it must be _virtual_, unless you use the [high-perf dependency injection technique](http://code.google.com/p/googlemock/wiki/V1_7_CookBook#Mocking_Nonvirtual_Methods). |
||||
|
||||
## I wrote some matchers. After I upgraded to a new version of Google Mock, they no longer compile. What's going on? ## |
||||
|
||||
After version 1.4.0 of Google Mock was released, we had an idea on how |
||||
to make it easier to write matchers that can generate informative |
||||
messages efficiently. We experimented with this idea and liked what |
||||
we saw. Therefore we decided to implement it. |
||||
|
||||
Unfortunately, this means that if you have defined your own matchers |
||||
by implementing `MatcherInterface` or using `MakePolymorphicMatcher()`, |
||||
your definitions will no longer compile. Matchers defined using the |
||||
`MATCHER*` family of macros are not affected. |
||||
|
||||
Sorry for the hassle if your matchers are affected. We believe it's |
||||
in everyone's long-term interest to make this change sooner than |
||||
later. Fortunately, it's usually not hard to migrate an existing |
||||
matcher to the new API. Here's what you need to do: |
||||
|
||||
If you wrote your matcher like this: |
||||
``` |
||||
// Old matcher definition that doesn't work with the latest |
||||
// Google Mock. |
||||
using ::testing::MatcherInterface; |
||||
... |
||||
class MyWonderfulMatcher : public MatcherInterface<MyType> { |
||||
public: |
||||
... |
||||
virtual bool Matches(MyType value) const { |
||||
// Returns true if value matches. |
||||
return value.GetFoo() > 5; |
||||
} |
||||
... |
||||
}; |
||||
``` |
||||
|
||||
you'll need to change it to: |
||||
``` |
||||
// New matcher definition that works with the latest Google Mock. |
||||
using ::testing::MatcherInterface; |
||||
using ::testing::MatchResultListener; |
||||
... |
||||
class MyWonderfulMatcher : public MatcherInterface<MyType> { |
||||
public: |
||||
... |
||||
virtual bool MatchAndExplain(MyType value, |
||||
MatchResultListener* listener) const { |
||||
// Returns true if value matches. |
||||
return value.GetFoo() > 5; |
||||
} |
||||
... |
||||
}; |
||||
``` |
||||
(i.e. rename `Matches()` to `MatchAndExplain()` and give it a second |
||||
argument of type `MatchResultListener*`.) |
||||
|
||||
If you were also using `ExplainMatchResultTo()` to improve the matcher |
||||
message: |
||||
``` |
||||
// Old matcher definition that doesn't work with the lastest |
||||
// Google Mock. |
||||
using ::testing::MatcherInterface; |
||||
... |
||||
class MyWonderfulMatcher : public MatcherInterface<MyType> { |
||||
public: |
||||
... |
||||
virtual bool Matches(MyType value) const { |
||||
// Returns true if value matches. |
||||
return value.GetFoo() > 5; |
||||
} |
||||
|
||||
virtual void ExplainMatchResultTo(MyType value, |
||||
::std::ostream* os) const { |
||||
// Prints some helpful information to os to help |
||||
// a user understand why value matches (or doesn't match). |
||||
*os << "the Foo property is " << value.GetFoo(); |
||||
} |
||||
... |
||||
}; |
||||
``` |
||||
|
||||
you should move the logic of `ExplainMatchResultTo()` into |
||||
`MatchAndExplain()`, using the `MatchResultListener` argument where |
||||
the `::std::ostream` was used: |
||||
``` |
||||
// New matcher definition that works with the latest Google Mock. |
||||
using ::testing::MatcherInterface; |
||||
using ::testing::MatchResultListener; |
||||
... |
||||
class MyWonderfulMatcher : public MatcherInterface<MyType> { |
||||
public: |
||||
... |
||||
virtual bool MatchAndExplain(MyType value, |
||||
MatchResultListener* listener) const { |
||||
// Returns true if value matches. |
||||
*listener << "the Foo property is " << value.GetFoo(); |
||||
return value.GetFoo() > 5; |
||||
} |
||||
... |
||||
}; |
||||
``` |
||||
|
||||
If your matcher is defined using `MakePolymorphicMatcher()`: |
||||
``` |
||||
// Old matcher definition that doesn't work with the latest |
||||
// Google Mock. |
||||
using ::testing::MakePolymorphicMatcher; |
||||
... |
||||
class MyGreatMatcher { |
||||
public: |
||||
... |
||||
bool Matches(MyType value) const { |
||||
// Returns true if value matches. |
||||
return value.GetBar() < 42; |
||||
} |
||||
... |
||||
}; |
||||
... MakePolymorphicMatcher(MyGreatMatcher()) ... |
||||
``` |
||||
|
||||
you should rename the `Matches()` method to `MatchAndExplain()` and |
||||
add a `MatchResultListener*` argument (the same as what you need to do |
||||
for matchers defined by implementing `MatcherInterface`): |
||||
``` |
||||
// New matcher definition that works with the latest Google Mock. |
||||
using ::testing::MakePolymorphicMatcher; |
||||
using ::testing::MatchResultListener; |
||||
... |
||||
class MyGreatMatcher { |
||||
public: |
||||
... |
||||
bool MatchAndExplain(MyType value, |
||||
MatchResultListener* listener) const { |
||||
// Returns true if value matches. |
||||
return value.GetBar() < 42; |
||||
} |
||||
... |
||||
}; |
||||
... MakePolymorphicMatcher(MyGreatMatcher()) ... |
||||
``` |
||||
|
||||
If your polymorphic matcher uses `ExplainMatchResultTo()` for better |
||||
failure messages: |
||||
``` |
||||
// Old matcher definition that doesn't work with the latest |
||||
// Google Mock. |
||||
using ::testing::MakePolymorphicMatcher; |
||||
... |
||||
class MyGreatMatcher { |
||||
public: |
||||
... |
||||
bool Matches(MyType value) const { |
||||
// Returns true if value matches. |
||||
return value.GetBar() < 42; |
||||
} |
||||
... |
||||
}; |
||||
void ExplainMatchResultTo(const MyGreatMatcher& matcher, |
||||
MyType value, |
||||
::std::ostream* os) { |
||||
// Prints some helpful information to os to help |
||||
// a user understand why value matches (or doesn't match). |
||||
*os << "the Bar property is " << value.GetBar(); |
||||
} |
||||
... MakePolymorphicMatcher(MyGreatMatcher()) ... |
||||
``` |
||||
|
||||
you'll need to move the logic inside `ExplainMatchResultTo()` to |
||||
`MatchAndExplain()`: |
||||
``` |
||||
// New matcher definition that works with the latest Google Mock. |
||||
using ::testing::MakePolymorphicMatcher; |
||||
using ::testing::MatchResultListener; |
||||
... |
||||
class MyGreatMatcher { |
||||
public: |
||||
... |
||||
bool MatchAndExplain(MyType value, |
||||
MatchResultListener* listener) const { |
||||
// Returns true if value matches. |
||||
*listener << "the Bar property is " << value.GetBar(); |
||||
return value.GetBar() < 42; |
||||
} |
||||
... |
||||
}; |
||||
... MakePolymorphicMatcher(MyGreatMatcher()) ... |
||||
``` |
||||
|
||||
For more information, you can read these |
||||
[two](http://code.google.com/p/googlemock/wiki/V1_7_CookBook#Writing_New_Monomorphic_Matchers) |
||||
[recipes](http://code.google.com/p/googlemock/wiki/V1_7_CookBook#Writing_New_Polymorphic_Matchers) |
||||
from the cookbook. As always, you |
||||
are welcome to post questions on `googlemock@googlegroups.com` if you |
||||
need any help. |
||||
|
||||
## When using Google Mock, do I have to use Google Test as the testing framework? I have my favorite testing framework and don't want to switch. ## |
||||
|
||||
Google Mock works out of the box with Google Test. However, it's easy |
||||
to configure it to work with any testing framework of your choice. |
||||
[Here](http://code.google.com/p/googlemock/wiki/V1_7_ForDummies#Using_Google_Mock_with_Any_Testing_Framework) is how. |
||||
|
||||
## How am I supposed to make sense of these horrible template errors? ## |
||||
|
||||
If you are confused by the compiler errors gcc threw at you, |
||||
try consulting the _Google Mock Doctor_ tool first. What it does is to |
||||
scan stdin for gcc error messages, and spit out diagnoses on the |
||||
problems (we call them diseases) your code has. |
||||
|
||||
To "install", run command: |
||||
``` |
||||
alias gmd='<path to googlemock>/scripts/gmock_doctor.py' |
||||
``` |
||||
|
||||
To use it, do: |
||||
``` |
||||
<your-favorite-build-command> <your-test> 2>&1 | gmd |
||||
``` |
||||
|
||||
For example: |
||||
``` |
||||
make my_test 2>&1 | gmd |
||||
``` |
||||
|
||||
Or you can run `gmd` and copy-n-paste gcc's error messages to it. |
||||
|
||||
## Can I mock a variadic function? ## |
||||
|
||||
You cannot mock a variadic function (i.e. a function taking ellipsis |
||||
(`...`) arguments) directly in Google Mock. |
||||
|
||||
The problem is that in general, there is _no way_ for a mock object to |
||||
know how many arguments are passed to the variadic method, and what |
||||
the arguments' types are. Only the _author of the base class_ knows |
||||
the protocol, and we cannot look into his head. |
||||
|
||||
Therefore, to mock such a function, the _user_ must teach the mock |
||||
object how to figure out the number of arguments and their types. One |
||||
way to do it is to provide overloaded versions of the function. |
||||
|
||||
Ellipsis arguments are inherited from C and not really a C++ feature. |
||||
They are unsafe to use and don't work with arguments that have |
||||
constructors or destructors. Therefore we recommend to avoid them in |
||||
C++ as much as possible. |
||||
|
||||
## MSVC gives me warning C4301 or C4373 when I define a mock method with a const parameter. Why? ## |
||||
|
||||
If you compile this using Microsoft Visual C++ 2005 SP1: |
||||
``` |
||||
class Foo { |
||||
... |
||||
virtual void Bar(const int i) = 0; |
||||
}; |
||||
|
||||
class MockFoo : public Foo { |
||||
... |
||||
MOCK_METHOD1(Bar, void(const int i)); |
||||
}; |
||||
``` |
||||
You may get the following warning: |
||||
``` |
||||
warning C4301: 'MockFoo::Bar': overriding virtual function only differs from 'Foo::Bar' by const/volatile qualifier |
||||
``` |
||||
|
||||
This is a MSVC bug. The same code compiles fine with gcc ,for |
||||
example. If you use Visual C++ 2008 SP1, you would get the warning: |
||||
``` |
||||
warning C4373: 'MockFoo::Bar': virtual function overrides 'Foo::Bar', previous versions of the compiler did not override when parameters only differed by const/volatile qualifiers |
||||
``` |
||||
|
||||
In C++, if you _declare_ a function with a `const` parameter, the |
||||
`const` modifier is _ignored_. Therefore, the `Foo` base class above |
||||
is equivalent to: |
||||
``` |
||||
class Foo { |
||||
... |
||||
virtual void Bar(int i) = 0; // int or const int? Makes no difference. |
||||
}; |
||||
``` |
||||
|
||||
In fact, you can _declare_ Bar() with an `int` parameter, and _define_ |
||||
it with a `const int` parameter. The compiler will still match them |
||||
up. |
||||
|
||||
Since making a parameter `const` is meaningless in the method |
||||
_declaration_, we recommend to remove it in both `Foo` and `MockFoo`. |
||||
That should workaround the VC bug. |
||||
|
||||
Note that we are talking about the _top-level_ `const` modifier here. |
||||
If the function parameter is passed by pointer or reference, declaring |
||||
the _pointee_ or _referee_ as `const` is still meaningful. For |
||||
example, the following two declarations are _not_ equivalent: |
||||
``` |
||||
void Bar(int* p); // Neither p nor *p is const. |
||||
void Bar(const int* p); // p is not const, but *p is. |
||||
``` |
||||
|
||||
## I have a huge mock class, and Microsoft Visual C++ runs out of memory when compiling it. What can I do? ## |
||||
|
||||
We've noticed that when the `/clr` compiler flag is used, Visual C++ |
||||
uses 5~6 times as much memory when compiling a mock class. We suggest |
||||
to avoid `/clr` when compiling native C++ mocks. |
||||
|
||||
## I can't figure out why Google Mock thinks my expectations are not satisfied. What should I do? ## |
||||
|
||||
You might want to run your test with |
||||
`--gmock_verbose=info`. This flag lets Google Mock print a trace |
||||
of every mock function call it receives. By studying the trace, |
||||
you'll gain insights on why the expectations you set are not met. |
||||
|
||||
## How can I assert that a function is NEVER called? ## |
||||
|
||||
``` |
||||
EXPECT_CALL(foo, Bar(_)) |
||||
.Times(0); |
||||
``` |
||||
|
||||
## I have a failed test where Google Mock tells me TWICE that a particular expectation is not satisfied. Isn't this redundant? ## |
||||
|
||||
When Google Mock detects a failure, it prints relevant information |
||||
(the mock function arguments, the state of relevant expectations, and |
||||
etc) to help the user debug. If another failure is detected, Google |
||||
Mock will do the same, including printing the state of relevant |
||||
expectations. |
||||
|
||||
Sometimes an expectation's state didn't change between two failures, |
||||
and you'll see the same description of the state twice. They are |
||||
however _not_ redundant, as they refer to _different points in time_. |
||||
The fact they are the same _is_ interesting information. |
||||
|
||||
## I get a heap check failure when using a mock object, but using a real object is fine. What can be wrong? ## |
||||
|
||||
Does the class (hopefully a pure interface) you are mocking have a |
||||
virtual destructor? |
||||
|
||||
Whenever you derive from a base class, make sure its destructor is |
||||
virtual. Otherwise Bad Things will happen. Consider the following |
||||
code: |
||||
|
||||
``` |
||||
class Base { |
||||
public: |
||||
// Not virtual, but should be. |
||||
~Base() { ... } |
||||
... |
||||
}; |
||||
|
||||
class Derived : public Base { |
||||
public: |
||||
... |
||||
private: |
||||
std::string value_; |
||||
}; |
||||
|
||||
... |
||||
Base* p = new Derived; |
||||
... |
||||
delete p; // Surprise! ~Base() will be called, but ~Derived() will not |
||||
// - value_ is leaked. |
||||
``` |
||||
|
||||
By changing `~Base()` to virtual, `~Derived()` will be correctly |
||||
called when `delete p` is executed, and the heap checker |
||||
will be happy. |
||||
|
||||
## The "newer expectations override older ones" rule makes writing expectations awkward. Why does Google Mock do that? ## |
||||
|
||||
When people complain about this, often they are referring to code like: |
||||
|
||||
``` |
||||
// foo.Bar() should be called twice, return 1 the first time, and return |
||||
// 2 the second time. However, I have to write the expectations in the |
||||
// reverse order. This sucks big time!!! |
||||
EXPECT_CALL(foo, Bar()) |
||||
.WillOnce(Return(2)) |
||||
.RetiresOnSaturation(); |
||||
EXPECT_CALL(foo, Bar()) |
||||
.WillOnce(Return(1)) |
||||
.RetiresOnSaturation(); |
||||
``` |
||||
|
||||
The problem is that they didn't pick the **best** way to express the test's |
||||
intent. |
||||
|
||||
By default, expectations don't have to be matched in _any_ particular |
||||
order. If you want them to match in a certain order, you need to be |
||||
explicit. This is Google Mock's (and jMock's) fundamental philosophy: it's |
||||
easy to accidentally over-specify your tests, and we want to make it |
||||
harder to do so. |
||||
|
||||
There are two better ways to write the test spec. You could either |
||||
put the expectations in sequence: |
||||
|
||||
``` |
||||
// foo.Bar() should be called twice, return 1 the first time, and return |
||||
// 2 the second time. Using a sequence, we can write the expectations |
||||
// in their natural order. |
||||
{ |
||||
InSequence s; |
||||
EXPECT_CALL(foo, Bar()) |
||||
.WillOnce(Return(1)) |
||||
.RetiresOnSaturation(); |
||||
EXPECT_CALL(foo, Bar()) |
||||
.WillOnce(Return(2)) |
||||
.RetiresOnSaturation(); |
||||
} |
||||
``` |
||||
|
||||
or you can put the sequence of actions in the same expectation: |
||||
|
||||
``` |
||||
// foo.Bar() should be called twice, return 1 the first time, and return |
||||
// 2 the second time. |
||||
EXPECT_CALL(foo, Bar()) |
||||
.WillOnce(Return(1)) |
||||
.WillOnce(Return(2)) |
||||
.RetiresOnSaturation(); |
||||
``` |
||||
|
||||
Back to the original questions: why does Google Mock search the |
||||
expectations (and `ON_CALL`s) from back to front? Because this |
||||
allows a user to set up a mock's behavior for the common case early |
||||
(e.g. in the mock's constructor or the test fixture's set-up phase) |
||||
and customize it with more specific rules later. If Google Mock |
||||
searches from front to back, this very useful pattern won't be |
||||
possible. |
||||
|
||||
## Google Mock prints a warning when a function without EXPECT\_CALL is called, even if I have set its behavior using ON\_CALL. Would it be reasonable not to show the warning in this case? ## |
||||
|
||||
When choosing between being neat and being safe, we lean toward the |
||||
latter. So the answer is that we think it's better to show the |
||||
warning. |
||||
|
||||
Often people write `ON_CALL`s in the mock object's |
||||
constructor or `SetUp()`, as the default behavior rarely changes from |
||||
test to test. Then in the test body they set the expectations, which |
||||
are often different for each test. Having an `ON_CALL` in the set-up |
||||
part of a test doesn't mean that the calls are expected. If there's |
||||
no `EXPECT_CALL` and the method is called, it's possibly an error. If |
||||
we quietly let the call go through without notifying the user, bugs |
||||
may creep in unnoticed. |
||||
|
||||
If, however, you are sure that the calls are OK, you can write |
||||
|
||||
``` |
||||
EXPECT_CALL(foo, Bar(_)) |
||||
.WillRepeatedly(...); |
||||
``` |
||||
|
||||
instead of |
||||
|
||||
``` |
||||
ON_CALL(foo, Bar(_)) |
||||
.WillByDefault(...); |
||||
``` |
||||
|
||||
This tells Google Mock that you do expect the calls and no warning should be |
||||
printed. |
||||
|
||||
Also, you can control the verbosity using the `--gmock_verbose` flag. |
||||
If you find the output too noisy when debugging, just choose a less |
||||
verbose level. |
||||
|
||||
## How can I delete the mock function's argument in an action? ## |
||||
|
||||
If you find yourself needing to perform some action that's not |
||||
supported by Google Mock directly, remember that you can define your own |
||||
actions using |
||||
[MakeAction()](http://code.google.com/p/googlemock/wiki/V1_7_CookBook#Writing_New_Actions) or |
||||
[MakePolymorphicAction()](http://code.google.com/p/googlemock/wiki/V1_7_CookBook#Writing_New_Polymorphic_Actions), |
||||
or you can write a stub function and invoke it using |
||||
[Invoke()](http://code.google.com/p/googlemock/wiki/V1_7_CookBook#Using_Functions_Methods_Functors). |
||||
|
||||
## MOCK\_METHODn()'s second argument looks funny. Why don't you use the MOCK\_METHODn(Method, return\_type, arg\_1, ..., arg\_n) syntax? ## |
||||
|
||||
What?! I think it's beautiful. :-) |
||||
|
||||
While which syntax looks more natural is a subjective matter to some |
||||
extent, Google Mock's syntax was chosen for several practical advantages it |
||||
has. |
||||
|
||||
Try to mock a function that takes a map as an argument: |
||||
``` |
||||
virtual int GetSize(const map<int, std::string>& m); |
||||
``` |
||||
|
||||
Using the proposed syntax, it would be: |
||||
``` |
||||
MOCK_METHOD1(GetSize, int, const map<int, std::string>& m); |
||||
``` |
||||
|
||||
Guess what? You'll get a compiler error as the compiler thinks that |
||||
`const map<int, std::string>& m` are **two**, not one, arguments. To work |
||||
around this you can use `typedef` to give the map type a name, but |
||||
that gets in the way of your work. Google Mock's syntax avoids this |
||||
problem as the function's argument types are protected inside a pair |
||||
of parentheses: |
||||
``` |
||||
// This compiles fine. |
||||
MOCK_METHOD1(GetSize, int(const map<int, std::string>& m)); |
||||
``` |
||||
|
||||
You still need a `typedef` if the return type contains an unprotected |
||||
comma, but that's much rarer. |
||||
|
||||
Other advantages include: |
||||
1. `MOCK_METHOD1(Foo, int, bool)` can leave a reader wonder whether the method returns `int` or `bool`, while there won't be such confusion using Google Mock's syntax. |
||||
1. The way Google Mock describes a function type is nothing new, although many people may not be familiar with it. The same syntax was used in C, and the `function` library in `tr1` uses this syntax extensively. Since `tr1` will become a part of the new version of STL, we feel very comfortable to be consistent with it. |
||||
1. The function type syntax is also used in other parts of Google Mock's API (e.g. the action interface) in order to make the implementation tractable. A user needs to learn it anyway in order to utilize Google Mock's more advanced features. We'd as well stick to the same syntax in `MOCK_METHOD*`! |
||||
|
||||
## My code calls a static/global function. Can I mock it? ## |
||||
|
||||
You can, but you need to make some changes. |
||||
|
||||
In general, if you find yourself needing to mock a static function, |
||||
it's a sign that your modules are too tightly coupled (and less |
||||
flexible, less reusable, less testable, etc). You are probably better |
||||
off defining a small interface and call the function through that |
||||
interface, which then can be easily mocked. It's a bit of work |
||||
initially, but usually pays for itself quickly. |
||||
|
||||
This Google Testing Blog |
||||
[post](http://googletesting.blogspot.com/2008/06/defeat-static-cling.html) |
||||
says it excellently. Check it out. |
||||
|
||||
## My mock object needs to do complex stuff. It's a lot of pain to specify the actions. Google Mock sucks! ## |
||||
|
||||
I know it's not a question, but you get an answer for free any way. :-) |
||||
|
||||
With Google Mock, you can create mocks in C++ easily. And people might be |
||||
tempted to use them everywhere. Sometimes they work great, and |
||||
sometimes you may find them, well, a pain to use. So, what's wrong in |
||||
the latter case? |
||||
|
||||
When you write a test without using mocks, you exercise the code and |
||||
assert that it returns the correct value or that the system is in an |
||||
expected state. This is sometimes called "state-based testing". |
||||
|
||||
Mocks are great for what some call "interaction-based" testing: |
||||
instead of checking the system state at the very end, mock objects |
||||
verify that they are invoked the right way and report an error as soon |
||||
as it arises, giving you a handle on the precise context in which the |
||||
error was triggered. This is often more effective and economical to |
||||
do than state-based testing. |
||||
|
||||
If you are doing state-based testing and using a test double just to |
||||
simulate the real object, you are probably better off using a fake. |
||||
Using a mock in this case causes pain, as it's not a strong point for |
||||
mocks to perform complex actions. If you experience this and think |
||||
that mocks suck, you are just not using the right tool for your |
||||
problem. Or, you might be trying to solve the wrong problem. :-) |
||||
|
||||
## I got a warning "Uninteresting function call encountered - default action taken.." Should I panic? ## |
||||
|
||||
By all means, NO! It's just an FYI. |
||||
|
||||
What it means is that you have a mock function, you haven't set any |
||||
expectations on it (by Google Mock's rule this means that you are not |
||||
interested in calls to this function and therefore it can be called |
||||
any number of times), and it is called. That's OK - you didn't say |
||||
it's not OK to call the function! |
||||
|
||||
What if you actually meant to disallow this function to be called, but |
||||
forgot to write `EXPECT_CALL(foo, Bar()).Times(0)`? While |
||||
one can argue that it's the user's fault, Google Mock tries to be nice and |
||||
prints you a note. |
||||
|
||||
So, when you see the message and believe that there shouldn't be any |
||||
uninteresting calls, you should investigate what's going on. To make |
||||
your life easier, Google Mock prints the function name and arguments |
||||
when an uninteresting call is encountered. |
||||
|
||||
## I want to define a custom action. Should I use Invoke() or implement the action interface? ## |
||||
|
||||
Either way is fine - you want to choose the one that's more convenient |
||||
for your circumstance. |
||||
|
||||
Usually, if your action is for a particular function type, defining it |
||||
using `Invoke()` should be easier; if your action can be used in |
||||
functions of different types (e.g. if you are defining |
||||
`Return(value)`), `MakePolymorphicAction()` is |
||||
easiest. Sometimes you want precise control on what types of |
||||
functions the action can be used in, and implementing |
||||
`ActionInterface` is the way to go here. See the implementation of |
||||
`Return()` in `include/gmock/gmock-actions.h` for an example. |
||||
|
||||
## I'm using the set-argument-pointee action, and the compiler complains about "conflicting return type specified". What does it mean? ## |
||||
|
||||
You got this error as Google Mock has no idea what value it should return |
||||
when the mock method is called. `SetArgPointee()` says what the |
||||
side effect is, but doesn't say what the return value should be. You |
||||
need `DoAll()` to chain a `SetArgPointee()` with a `Return()`. |
||||
|
||||
See this [recipe](http://code.google.com/p/googlemock/wiki/V1_7_CookBook#Mocking_Side_Effects) for more details and an example. |
||||
|
||||
|
||||
## My question is not in your FAQ! ## |
||||
|
||||
If you cannot find the answer to your question in this FAQ, there are |
||||
some other resources you can use: |
||||
|
||||
1. read other [wiki pages](http://code.google.com/p/googlemock/w/list), |
||||
1. search the mailing list [archive](http://groups.google.com/group/googlemock/topics), |
||||
1. ask it on [googlemock@googlegroups.com](mailto:googlemock@googlegroups.com) and someone will answer it (to prevent spam, we require you to join the [discussion group](http://groups.google.com/group/googlemock) before you can post.). |
||||
|
||||
Please note that creating an issue in the |
||||
[issue tracker](http://code.google.com/p/googlemock/issues/list) is _not_ |
||||
a good way to get your answer, as it is monitored infrequently by a |
||||
very small number of people. |
||||
|
||||
When asking a question, it's helpful to provide as much of the |
||||
following information as possible (people cannot help you if there's |
||||
not enough information in your question): |
||||
|
||||
* the version (or the revision number if you check out from SVN directly) of Google Mock you use (Google Mock is under active development, so it's possible that your problem has been solved in a later version), |
||||
* your operating system, |
||||
* the name and version of your compiler, |
||||
* the complete command line flags you give to your compiler, |
||||
* the complete compiler error messages (if the question is about compilation), |
||||
* the _actual_ code (ideally, a minimal but complete program) that has the problem you encounter. |
@ -0,0 +1,52 @@ |
||||
# Copyright 2017 Google Inc. |
||||
# All Rights Reserved. |
||||
# |
||||
# |
||||
# Redistribution and use in source and binary forms, with or without |
||||
# modification, are permitted provided that the following conditions are |
||||
# met: |
||||
# |
||||
# * Redistributions of source code must retain the above copyright |
||||
# notice, this list of conditions and the following disclaimer. |
||||
# * Redistributions in binary form must reproduce the above |
||||
# copyright notice, this list of conditions and the following disclaimer |
||||
# in the documentation and/or other materials provided with the |
||||
# distribution. |
||||
# * Neither the name of Google Inc. nor the names of its |
||||
# contributors may be used to endorse or promote products derived from |
||||
# this software without specific prior written permission. |
||||
# |
||||
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
||||
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
||||
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR |
||||
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT |
||||
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, |
||||
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT |
||||
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, |
||||
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY |
||||
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT |
||||
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE |
||||
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |
||||
# |
||||
# Author: misterg@google.com (Gennadiy Civil) |
||||
# |
||||
# Bazel Build for Google C++ Testing Framework(Google Test)-googlemock |
||||
|
||||
""" gmock own tests """ |
||||
|
||||
cc_test( |
||||
name = "gmock_all_test", |
||||
size = "small", |
||||
srcs = glob( |
||||
include = [ |
||||
"gmock-*.cc", |
||||
], |
||||
), |
||||
linkopts = select({ |
||||
"//:win": [], |
||||
"//conditions:default": [ |
||||
"-pthread", |
||||
], |
||||
}), |
||||
deps = ["//:gtest"], |
||||
) |
@ -0,0 +1,9 @@ |
||||
libdir=@CMAKE_INSTALL_FULL_LIBDIR@ |
||||
includedir=@CMAKE_INSTALL_FULL_INCLUDEDIR@ |
||||
|
||||
Name: gtest |
||||
Description: GoogleTest (without main() function) |
||||
Version: @PROJECT_VERSION@ |
||||
URL: https://github.com/google/googletest |
||||
Libs: -L${libdir} -lgtest @CMAKE_THREAD_LIBS_INIT@ |
||||
Cflags: -I${includedir} @GTEST_HAS_PTHREAD_MACRO@ @CMAKE_THREAD_LIBS_INIT@ |
@ -0,0 +1,10 @@ |
||||
libdir=@CMAKE_INSTALL_FULL_LIBDIR@ |
||||
includedir=@CMAKE_INSTALL_FULL_INCLUDEDIR@ |
||||
|
||||
Name: gtest_main |
||||
Description: GoogleTest (with main() function) |
||||
Version: @PROJECT_VERSION@ |
||||
URL: https://github.com/google/googletest |
||||
Requires: gtest |
||||
Libs: -L${libdir} -lgtest_main @CMAKE_THREAD_LIBS_INIT@ |
||||
Cflags: -I${includedir} @GTEST_HAS_PTHREAD_MACRO@ @CMAKE_THREAD_LIBS_INIT@ |
@ -0,0 +1,146 @@ |
||||
## Using GoogleTest from various build systems ## |
||||
|
||||
GoogleTest comes with pkg-config files that can be used to determine all |
||||
necessary flags for compiling and linking to GoogleTest (and GoogleMock). |
||||
Pkg-config is a standardised plain-text format containing |
||||
|
||||
* the includedir (-I) path |
||||
* necessary macro (-D) definitions |
||||
* further required flags (-pthread) |
||||
* the library (-L) path |
||||
* the library (-l) to link to |
||||
|
||||
All current build systems support pkg-config in one way or another. For |
||||
all examples here we assume you want to compile the sample |
||||
`samples/sample3_unittest.cc`. |
||||
|
||||
|
||||
### CMake ### |
||||
|
||||
Using `pkg-config` in CMake is fairly easy: |
||||
|
||||
``` |
||||
cmake_minimum_required(VERSION 3.0) |
||||
|
||||
cmake_policy(SET CMP0048 NEW) |
||||
project(my_gtest_pkgconfig VERSION 0.0.1 LANGUAGES CXX) |
||||
|
||||
find_package(PkgConfig) |
||||
pkg_search_module(GTEST REQUIRED gtest_main) |
||||
|
||||
add_executable(testapp samples/sample3_unittest.cc) |
||||
target_link_libraries(testapp ${GTEST_LDFLAGS}) |
||||
target_compile_options(testapp PUBLIC ${GTEST_CFLAGS}) |
||||
|
||||
include(CTest) |
||||
add_test(first_and_only_test testapp) |
||||
``` |
||||
|
||||
It is generally recommended that you use `target_compile_options` + `_CFLAGS` |
||||
over `target_include_directories` + `_INCLUDE_DIRS` as the former includes not |
||||
just -I flags (GoogleTest might require a macro indicating to internal headers |
||||
that all libraries have been compiled with threading enabled. In addition, |
||||
GoogleTest might also require `-pthread` in the compiling step, and as such |
||||
splitting the pkg-config `Cflags` variable into include dirs and macros for |
||||
`target_compile_definitions()` might still miss this). The same recommendation |
||||
goes for using `_LDFLAGS` over the more commonplace `_LIBRARIES`, which |
||||
happens to discard `-L` flags and `-pthread`. |
||||
|
||||
|
||||
### Autotools ### |
||||
|
||||
Finding GoogleTest in Autoconf and using it from Automake is also fairly easy: |
||||
|
||||
In your `configure.ac`: |
||||
|
||||
``` |
||||
AC_PREREQ([2.69]) |
||||
AC_INIT([my_gtest_pkgconfig], [0.0.1]) |
||||
AC_CONFIG_SRCDIR([samples/sample3_unittest.cc]) |
||||
AC_PROG_CXX |
||||
|
||||
PKG_CHECK_MODULES([GTEST], [gtest_main]) |
||||
|
||||
AM_INIT_AUTOMAKE([foreign subdir-objects]) |
||||
AC_CONFIG_FILES([Makefile]) |
||||
AC_OUTPUT |
||||
``` |
||||
|
||||
and in your `Makefile.am`: |
||||
|
||||
``` |
||||
check_PROGRAMS = testapp |
||||
TESTS = $(check_PROGRAMS) |
||||
|
||||
testapp_SOURCES = samples/sample3_unittest.cc |
||||
testapp_CXXFLAGS = $(GTEST_CFLAGS) |
||||
testapp_LDADD = $(GTEST_LIBS) |
||||
``` |
||||
|
||||
|
||||
### Meson ### |
||||
|
||||
Meson natively uses pkgconfig to query dependencies: |
||||
|
||||
``` |
||||
project('my_gtest_pkgconfig', 'cpp', version : '0.0.1') |
||||
|
||||
gtest_dep = dependency('gtest_main') |
||||
|
||||
testapp = executable( |
||||
'testapp', |
||||
files(['samples/sample3_unittest.cc']), |
||||
dependencies : gtest_dep, |
||||
install : false) |
||||
|
||||
test('first_and_only_test', testapp) |
||||
``` |
||||
|
||||
|
||||
### Plain Makefiles ### |
||||
|
||||
Since `pkg-config` is a small Unix command-line utility, it can be used |
||||
in handwritten `Makefile`s too: |
||||
|
||||
``` |
||||
GTEST_CFLAGS = `pkg-config --cflags gtest_main` |
||||
GTEST_LIBS = `pkg-config --libs gtest_main` |
||||
|
||||
.PHONY: tests all |
||||
|
||||
tests: all |
||||
./testapp |
||||
|
||||
all: testapp |
||||
|
||||
testapp: testapp.o |
||||
$(CXX) $(CXXFLAGS) $(LDFLAGS) $< -o $@ $(GTEST_LIBS) |
||||
|
||||
testapp.o: samples/sample3_unittest.cc |
||||
$(CXX) $(CPPFLAGS) $(CXXFLAGS) $< -c -o $@ $(GTEST_CFLAGS) |
||||
``` |
||||
|
||||
|
||||
### Help! pkg-config can't find GoogleTest! ### |
||||
|
||||
Let's say you have a `CMakeLists.txt` along the lines of the one in this |
||||
tutorial and you try to run `cmake`. It is very possible that you get a |
||||
failure along the lines of: |
||||
|
||||
``` |
||||
-- Checking for one of the modules 'gtest_main' |
||||
CMake Error at /usr/share/cmake/Modules/FindPkgConfig.cmake:640 (message): |
||||
None of the required 'gtest_main' found |
||||
``` |
||||
|
||||
These failures are common if you installed GoogleTest yourself and have not |
||||
sourced it from a distro or other package manager. If so, you need to tell |
||||
pkg-config where it can find the `.pc` files containing the information. |
||||
Say you installed GoogleTest to `/usr/local`, then it might be that the |
||||
`.pc` files are installed under `/usr/local/lib64/pkgconfig`. If you set |
||||
|
||||
``` |
||||
export PKG_CONFIG_PATH=/usr/local/lib64/pkgconfig |
||||
``` |
||||
|
||||
pkg-config will also try to look in `PKG_CONFIG_PATH` to find `gtest_main.pc`. |
File diff suppressed because it is too large
Load Diff
@ -1,12 +0,0 @@ |
||||
This page lists all official documentation wiki pages for Google Test **1.5.0** -- **if you use a different version of Google Test, make sure to read the documentation for that version instead.** |
||||
|
||||
* [Primer](V1_5_Primer.md) -- start here if you are new to Google Test. |
||||
* [Samples](Samples.md) -- learn from examples. |
||||
* [AdvancedGuide](V1_5_AdvancedGuide.md) -- learn more about Google Test. |
||||
* [XcodeGuide](V1_5_XcodeGuide.md) -- how to use Google Test in Xcode on Mac. |
||||
* [Frequently-Asked Questions](V1_5_FAQ.md) -- check here before asking a question on the mailing list. |
||||
|
||||
To contribute code to Google Test, read: |
||||
|
||||
* DevGuide -- read this _before_ writing your first patch. |
||||
* [PumpManual](V1_5_PumpManual.md) -- how we generate some of Google Test's source files. |
@ -1,497 +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_. |
||||
|
||||
# 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 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(`_expected_`, `_actual_`);`|`EXPECT_EQ(`_expected_`, `_actual_`);`| _expected_ `==` _actual_ | |
||||
|`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_ |
||||
. In `ASSERT_EQ*` and `EXPECT_EQ*` (and all other equality assertions |
||||
we'll introduce later), you should put the expression you want to test |
||||
in the position of _actual_, and put its expected value in _expected_, |
||||
as Google Test's failure messages are optimized for this convention. |
||||
|
||||
Value arguments must be comparable by the assertion's comparison operator or |
||||
you'll get a compiler error. Values must also support the `<<` operator for |
||||
streaming to an `ostream`. All built-in types support this. |
||||
|
||||
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. |
||||
|
||||
## 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(`_expected\_str_`, `_actual\_str_`);` | `EXPECT_STREQ(`_expected\_str_`, `_actual\_str_`);` | 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(`_expected\_str_`, `_actual\_str_`);`| `EXPECT_STRCASEEQ(`_expected\_str_`, `_actual\_str_`);` | 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 [AdvancedGuide Advanced |
||||
Google Test 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 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(test_case_name, test_name) { |
||||
... 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. Remember that a test case can contain any number of individual |
||||
tests. 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](V1_5_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 text 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](V1_5_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](V1_5_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. |
@ -1,177 +0,0 @@ |
||||
|
||||
|
||||
<b>P</b>ump is <b>U</b>seful for <b>M</b>eta <b>P</b>rogramming. |
||||
|
||||
# The Problem # |
||||
|
||||
Template and macro libraries often need to define many classes, |
||||
functions, or macros that vary only (or almost only) in the number of |
||||
arguments they take. It's a lot of repetitive, mechanical, and |
||||
error-prone work. |
||||
|
||||
Variadic templates and variadic macros can alleviate the problem. |
||||
However, while both are being considered by the C++ committee, neither |
||||
is in the standard yet or widely supported by compilers. Thus they |
||||
are often not a good choice, especially when your code needs to be |
||||
portable. And their capabilities are still limited. |
||||
|
||||
As a result, authors of such libraries often have to write scripts to |
||||
generate their implementation. However, our experience is that it's |
||||
tedious to write such scripts, which tend to reflect the structure of |
||||
the generated code poorly and are often hard to read and edit. For |
||||
example, a small change needed in the generated code may require some |
||||
non-intuitive, non-trivial changes in the script. This is especially |
||||
painful when experimenting with the code. |
||||
|
||||
# Our Solution # |
||||
|
||||
Pump (for Pump is Useful for Meta Programming, Pretty Useful for Meta |
||||
Programming, or Practical Utility for Meta Programming, whichever you |
||||
prefer) is a simple meta-programming tool for C++. The idea is that a |
||||
programmer writes a `foo.pump` file which contains C++ code plus meta |
||||
code that manipulates the C++ code. The meta code can handle |
||||
iterations over a range, nested iterations, local meta variable |
||||
definitions, simple arithmetic, and conditional expressions. You can |
||||
view it as a small Domain-Specific Language. The meta language is |
||||
designed to be non-intrusive (s.t. it won't confuse Emacs' C++ mode, |
||||
for example) and concise, making Pump code intuitive and easy to |
||||
maintain. |
||||
|
||||
## Highlights ## |
||||
|
||||
* The implementation is in a single Python script and thus ultra portable: no build or installation is needed and it works cross platforms. |
||||
* Pump tries to be smart with respect to [Google's style guide](http://code.google.com/p/google-styleguide/): it breaks long lines (easy to have when they are generated) at acceptable places to fit within 80 columns and indent the continuation lines correctly. |
||||
* The format is human-readable and more concise than XML. |
||||
* The format works relatively well with Emacs' C++ mode. |
||||
|
||||
## Examples ## |
||||
|
||||
The following Pump code (where meta keywords start with `$`, `[[` and `]]` are meta brackets, and `$$` starts a meta comment that ends with the line): |
||||
|
||||
``` |
||||
$var n = 3 $$ Defines a meta variable n. |
||||
$range i 0..n $$ Declares the range of meta iterator i (inclusive). |
||||
$for i [[ |
||||
$$ Meta loop. |
||||
// Foo$i does blah for $i-ary predicates. |
||||
$range j 1..i |
||||
template <size_t N $for j [[, typename A$j]]> |
||||
class Foo$i { |
||||
$if i == 0 [[ |
||||
blah a; |
||||
]] $elif i <= 2 [[ |
||||
blah b; |
||||
]] $else [[ |
||||
blah c; |
||||
]] |
||||
}; |
||||
|
||||
]] |
||||
``` |
||||
|
||||
will be translated by the Pump compiler to: |
||||
|
||||
``` |
||||
// Foo0 does blah for 0-ary predicates. |
||||
template <size_t N> |
||||
class Foo0 { |
||||
blah a; |
||||
}; |
||||
|
||||
// Foo1 does blah for 1-ary predicates. |
||||
template <size_t N, typename A1> |
||||
class Foo1 { |
||||
blah b; |
||||
}; |
||||
|
||||
// Foo2 does blah for 2-ary predicates. |
||||
template <size_t N, typename A1, typename A2> |
||||
class Foo2 { |
||||
blah b; |
||||
}; |
||||
|
||||
// Foo3 does blah for 3-ary predicates. |
||||
template <size_t N, typename A1, typename A2, typename A3> |
||||
class Foo3 { |
||||
blah c; |
||||
}; |
||||
``` |
||||
|
||||
In another example, |
||||
|
||||
``` |
||||
$range i 1..n |
||||
Func($for i + [[a$i]]); |
||||
$$ The text between i and [[ is the separator between iterations. |
||||
``` |
||||
|
||||
will generate one of the following lines (without the comments), depending on the value of `n`: |
||||
|
||||
``` |
||||
Func(); // If n is 0. |
||||
Func(a1); // If n is 1. |
||||
Func(a1 + a2); // If n is 2. |
||||
Func(a1 + a2 + a3); // If n is 3. |
||||
// And so on... |
||||
``` |
||||
|
||||
## Constructs ## |
||||
|
||||
We support the following meta programming constructs: |
||||
|
||||
| `$var id = exp` | Defines a named constant value. `$id` is valid util the end of the current meta lexical block. | |
||||
|:----------------|:-----------------------------------------------------------------------------------------------| |
||||
| $range id exp..exp | Sets the range of an iteration variable, which can be reused in multiple loops later. | |
||||
| $for id sep [[code ](.md)] | Iteration. The range of `id` must have been defined earlier. `$id` is valid in `code`. | |
||||
| `$($)` | Generates a single `$` character. | |
||||
| `$id` | Value of the named constant or iteration variable. | |
||||
| `$(exp)` | Value of the expression. | |
||||
| `$if exp [[ code ]] else_branch` | Conditional. | |
||||
| `[[ code ]]` | Meta lexical block. | |
||||
| `cpp_code` | Raw C++ code. | |
||||
| `$$ comment` | Meta comment. | |
||||
|
||||
**Note:** To give the user some freedom in formatting the Pump source |
||||
code, Pump ignores a new-line character if it's right after `$for foo` |
||||
or next to `[[` or `]]`. Without this rule you'll often be forced to write |
||||
very long lines to get the desired output. Therefore sometimes you may |
||||
need to insert an extra new-line in such places for a new-line to show |
||||
up in your output. |
||||
|
||||
## Grammar ## |
||||
|
||||
``` |
||||
code ::= atomic_code* |
||||
atomic_code ::= $var id = exp |
||||
| $var id = [[ code ]] |
||||
| $range id exp..exp |
||||
| $for id sep [[ code ]] |
||||
| $($) |
||||
| $id |
||||
| $(exp) |
||||
| $if exp [[ code ]] else_branch |
||||
| [[ code ]] |
||||
| cpp_code |
||||
sep ::= cpp_code | empty_string |
||||
else_branch ::= $else [[ code ]] |
||||
| $elif exp [[ code ]] else_branch |
||||
| empty_string |
||||
exp ::= simple_expression_in_Python_syntax |
||||
``` |
||||
|
||||
## Code ## |
||||
|
||||
You can find the source code of Pump in [scripts/pump.py](http://code.google.com/p/googletest/source/browse/trunk/scripts/pump.py). It is still |
||||
very unpolished and lacks automated tests, although it has been |
||||
successfully used many times. If you find a chance to use it in your |
||||
project, please let us know what you think! We also welcome help on |
||||
improving Pump. |
||||
|
||||
## Real Examples ## |
||||
|
||||
You can find real-world applications of Pump in [Google Test](http://www.google.com/codesearch?q=file%3A\.pump%24+package%3Ahttp%3A%2F%2Fgoogletest\.googlecode\.com) and [Google Mock](http://www.google.com/codesearch?q=file%3A\.pump%24+package%3Ahttp%3A%2F%2Fgooglemock\.googlecode\.com). The source file `foo.h.pump` generates `foo.h`. |
||||
|
||||
## Tips ## |
||||
|
||||
* If a meta variable is followed by a letter or digit, you can separate them using `[[]]`, which inserts an empty string. For example `Foo$j[[]]Helper` generate `Foo1Helper` when `j` is 1. |
||||
* To avoid extra-long Pump source lines, you can break a line anywhere you want by inserting `[[]]` followed by a new line. Since any new-line character next to `[[` or `]]` is ignored, the generated code won't contain this new line. |
@ -1,93 +0,0 @@ |
||||
|
||||
|
||||
This guide will explain how to use the Google Testing Framework in your Xcode projects on Mac OS X. This tutorial begins by quickly explaining what to do for experienced users. After the quick start, the guide goes provides additional explanation about each step. |
||||
|
||||
# Quick Start # |
||||
|
||||
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. 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" |
||||
1. Add your unit test source code to the "Compile Sources" build phase of "UnitTests" |
||||
1. Edit the "UnitTests" executable and add an environment variable named "DYLD\_FRAMEWORK\_PATH" with a value equal to the path to the framework containing the gtest.framework relative to the compiled executable. |
||||
1. Build and Go |
||||
|
||||
The following sections further explain each of the steps listed above in depth, describing in more detail how to complete it including some variations. |
||||
|
||||
# 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: |
||||
|
||||
``` |
||||
svn checkout http://googletest.googlecode.com/svn/trunk/ googletest-read-only |
||||
``` |
||||
|
||||
Alternatively, if you are working with Subversion in your own code base, you can add Google Test as an external dependency to your own Subversion repository. By following this approach, everyone that checks out your svn repository will also receive a copy of Google Test (a specific version, if you wish) without having to check it out explicitly. This makes the set up of your project simpler and reduces the copied code in the repository. |
||||
|
||||
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`). |
||||
|
||||
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. |
||||
|
||||
``` |
||||
[Computer:svn] user$ svn propget svn:externals trunk |
||||
externals/src/googletest http://googletest.googlecode.com/svn/trunk |
||||
``` |
||||
|
||||
# Add the Framework to Your Project # |
||||
|
||||
The next step is to build and add the gtest.framework to your own project. This guide describes two common ways below. |
||||
|
||||
* **Option 1** --- The simplest way to add Google Test to your own project, is to open gtest.xcodeproj (found in the xcode/ directory of the Google Test trunk) and build the framework manually. Then, add the built framework into your project using the "Add->Existing Framework..." from the context menu or "Project->Add..." from the main menu. The gtest.framework is relocatable and contains the headers and object code that you'll need to make tests. This method requires rebuilding every time you upgrade Google Test in your project. |
||||
* **Option 2** --- If you are going to be living off the trunk of Google Test, incorporating its latest features into your unit tests (or are a Google Test developer yourself). You'll want to rebuild the framework every time the source updates. to do this, you'll need to add the gtest.xcodeproj file, not the framework itself, to your own Xcode project. Then, from the build products that are revealed by the project's disclosure triangle, you can find the gtest.framework, which can be added to your targets (discussed below). |
||||
|
||||
# Make a Test Target # |
||||
|
||||
To start writing tests, make a new "Shell Tool" target. This target template is available under BSD, Cocoa, or Carbon. Add your unit test source code to the "Compile Sources" build phase of the target. |
||||
|
||||
Next, you'll want to add gtest.framework in two different ways, depending upon which option you chose above. |
||||
|
||||
* **Option 1** --- During compilation, Xcode will need to know that you are linking against the gtest.framework. Add the gtest.framework to the "Link Binary with Libraries" build phase of your test target. This will include the Google Test headers in your header search path, and will tell the linker where to find the library. |
||||
* **Option 2** --- If your working out of the trunk, you'll also want to add gtest.framework to your "Link Binary with Libraries" build phase of your test target. In addition, you'll want to add the gtest.framework as a dependency to your unit test target. This way, Xcode will make sure that gtest.framework is up to date, every time your build your target. Finally, if you don't share build directories with Google Test, you'll have to copy the gtest.framework into your own build products directory using a "Run Script" build phase. |
||||
|
||||
# Set Up the Executable Run Environment # |
||||
|
||||
Since the unit test executable is a shell tool, it doesn't have a bundle with a `Contents/Frameworks` directory, in which to place gtest.framework. Instead, the dynamic linker must be told at runtime to search for the framework in another location. This can be accomplished by setting the "DYLD\_FRAMEWORK\_PATH" environment variable in the "Edit Active Executable ..." Arguments tab, under "Variables to be set in the environment:". The path for this value is the path (relative or absolute) of the directory containing the gtest.framework. |
||||
|
||||
If you haven't set up the DYLD\_FRAMEWORK\_PATH, correctly, you might get a message like this: |
||||
|
||||
``` |
||||
[Session started at 2008-08-15 06:23:57 -0600.] |
||||
dyld: Library not loaded: @loader_path/../Frameworks/gtest.framework/Versions/A/gtest |
||||
Referenced from: /Users/username/Documents/Sandbox/gtestSample/build/Debug/WidgetFrameworkTest |
||||
Reason: image not found |
||||
``` |
||||
|
||||
To correct this problem, got to the directory containing the executable named in "Referenced from:" value in the error message above. Then, with the terminal in this location, find the relative path to the directory containing the gtest.framework. That is the value you'll need to set as the DYLD\_FRAMEWORK\_PATH. |
||||
|
||||
# Build and Go # |
||||
|
||||
Now, when you click "Build and Go", the test will be executed. Dumping out something like this: |
||||
|
||||
``` |
||||
[Session started at 2008-08-06 06:36:13 -0600.] |
||||
[==========] Running 2 tests from 1 test case. |
||||
[----------] Global test environment set-up. |
||||
[----------] 2 tests from WidgetInitializerTest |
||||
[ RUN ] WidgetInitializerTest.TestConstructor |
||||
[ OK ] WidgetInitializerTest.TestConstructor |
||||
[ RUN ] WidgetInitializerTest.TestConversion |
||||
[ OK ] WidgetInitializerTest.TestConversion |
||||
[----------] Global test environment tear-down |
||||
[==========] 2 tests from 1 test case ran. |
||||
[ PASSED ] 2 tests. |
||||
|
||||
The Debugger has exited with status 0. |
||||
``` |
||||
|
||||
# Summary # |
||||
|
||||
Unit testing is a valuable way to ensure your data model stays valid even during rapid development or refactoring. The Google Testing Framework is a great unit testing framework for C and C++ which integrates well with an Xcode development environment. |
File diff suppressed because it is too large
Load Diff
@ -1,14 +0,0 @@ |
||||
This page lists all documentation wiki pages for Google Test **1.6** |
||||
-- **if you use a released version of Google Test, please read the |
||||
documentation for that specific version instead.** |
||||
|
||||
* [Primer](V1_6_Primer.md) -- start here if you are new to Google Test. |
||||
* [Samples](V1_6_Samples.md) -- learn from examples. |
||||
* [AdvancedGuide](V1_6_AdvancedGuide.md) -- learn more about Google Test. |
||||
* [XcodeGuide](V1_6_XcodeGuide.md) -- how to use Google Test in Xcode on Mac. |
||||
* [Frequently-Asked Questions](V1_6_FAQ.md) -- check here before asking a question on the mailing list. |
||||
|
||||
To contribute code to Google Test, read: |
||||
|
||||
* [DevGuide](DevGuide.md) -- read this _before_ writing your first patch. |
||||
* [PumpManual](V1_6_PumpManual.md) -- how we generate some of Google Test's source files. |
File diff suppressed because it is too large
Load Diff
@ -1,501 +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_. |
||||
|
||||
# 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(`_expected_`, `_actual_`);`|`EXPECT_EQ(`_expected_`, `_actual_`);`| _expected_ `==` _actual_ | |
||||
|`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_ |
||||
. In `ASSERT_EQ*` and `EXPECT_EQ*` (and all other equality assertions |
||||
we'll introduce later), you should put the expression you want to test |
||||
in the position of _actual_, and put its expected value in _expected_, |
||||
as Google Test's failure messages are optimized for this convention. |
||||
|
||||
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. |
||||
|
||||
## 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(`_expected\_str_`, `_actual\_str_`);` | `EXPECT_STREQ(`_expected\_str_`, `_actual\_str_`);` | 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(`_expected\_str_`, `_actual\_str_`);`| `EXPECT_STRCASEEQ(`_expected\_str_`, `_actual\_str_`);` | 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](V1_6_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(test_case_name, test_name) { |
||||
... 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](V1_6_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 text 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](V1_6_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](V1_6_Samples.md), or continue with |
||||
[AdvancedGuide](V1_6_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. |
@ -1,177 +0,0 @@ |
||||
|
||||
|
||||
<b>P</b>ump is <b>U</b>seful for <b>M</b>eta <b>P</b>rogramming. |
||||
|
||||
# The Problem # |
||||
|
||||
Template and macro libraries often need to define many classes, |
||||
functions, or macros that vary only (or almost only) in the number of |
||||
arguments they take. It's a lot of repetitive, mechanical, and |
||||
error-prone work. |
||||
|
||||
Variadic templates and variadic macros can alleviate the problem. |
||||
However, while both are being considered by the C++ committee, neither |
||||
is in the standard yet or widely supported by compilers. Thus they |
||||
are often not a good choice, especially when your code needs to be |
||||
portable. And their capabilities are still limited. |
||||
|
||||
As a result, authors of such libraries often have to write scripts to |
||||
generate their implementation. However, our experience is that it's |
||||
tedious to write such scripts, which tend to reflect the structure of |
||||
the generated code poorly and are often hard to read and edit. For |
||||
example, a small change needed in the generated code may require some |
||||
non-intuitive, non-trivial changes in the script. This is especially |
||||
painful when experimenting with the code. |
||||
|
||||
# Our Solution # |
||||
|
||||
Pump (for Pump is Useful for Meta Programming, Pretty Useful for Meta |
||||
Programming, or Practical Utility for Meta Programming, whichever you |
||||
prefer) is a simple meta-programming tool for C++. The idea is that a |
||||
programmer writes a `foo.pump` file which contains C++ code plus meta |
||||
code that manipulates the C++ code. The meta code can handle |
||||
iterations over a range, nested iterations, local meta variable |
||||
definitions, simple arithmetic, and conditional expressions. You can |
||||
view it as a small Domain-Specific Language. The meta language is |
||||
designed to be non-intrusive (s.t. it won't confuse Emacs' C++ mode, |
||||
for example) and concise, making Pump code intuitive and easy to |
||||
maintain. |
||||
|
||||
## Highlights ## |
||||
|
||||
* The implementation is in a single Python script and thus ultra portable: no build or installation is needed and it works cross platforms. |
||||
* Pump tries to be smart with respect to [Google's style guide](http://code.google.com/p/google-styleguide/): it breaks long lines (easy to have when they are generated) at acceptable places to fit within 80 columns and indent the continuation lines correctly. |
||||
* The format is human-readable and more concise than XML. |
||||
* The format works relatively well with Emacs' C++ mode. |
||||
|
||||
## Examples ## |
||||
|
||||
The following Pump code (where meta keywords start with `$`, `[[` and `]]` are meta brackets, and `$$` starts a meta comment that ends with the line): |
||||
|
||||
``` |
||||
$var n = 3 $$ Defines a meta variable n. |
||||
$range i 0..n $$ Declares the range of meta iterator i (inclusive). |
||||
$for i [[ |
||||
$$ Meta loop. |
||||
// Foo$i does blah for $i-ary predicates. |
||||
$range j 1..i |
||||
template <size_t N $for j [[, typename A$j]]> |
||||
class Foo$i { |
||||
$if i == 0 [[ |
||||
blah a; |
||||
]] $elif i <= 2 [[ |
||||
blah b; |
||||
]] $else [[ |
||||
blah c; |
||||
]] |
||||
}; |
||||
|
||||
]] |
||||
``` |
||||
|
||||
will be translated by the Pump compiler to: |
||||
|
||||
``` |
||||
// Foo0 does blah for 0-ary predicates. |
||||
template <size_t N> |
||||
class Foo0 { |
||||
blah a; |
||||
}; |
||||
|
||||
// Foo1 does blah for 1-ary predicates. |
||||
template <size_t N, typename A1> |
||||
class Foo1 { |
||||
blah b; |
||||
}; |
||||
|
||||
// Foo2 does blah for 2-ary predicates. |
||||
template <size_t N, typename A1, typename A2> |
||||
class Foo2 { |
||||
blah b; |
||||
}; |
||||
|
||||
// Foo3 does blah for 3-ary predicates. |
||||
template <size_t N, typename A1, typename A2, typename A3> |
||||
class Foo3 { |
||||
blah c; |
||||
}; |
||||
``` |
||||
|
||||
In another example, |
||||
|
||||
``` |
||||
$range i 1..n |
||||
Func($for i + [[a$i]]); |
||||
$$ The text between i and [[ is the separator between iterations. |
||||
``` |
||||
|
||||
will generate one of the following lines (without the comments), depending on the value of `n`: |
||||
|
||||
``` |
||||
Func(); // If n is 0. |
||||
Func(a1); // If n is 1. |
||||
Func(a1 + a2); // If n is 2. |
||||
Func(a1 + a2 + a3); // If n is 3. |
||||
// And so on... |
||||
``` |
||||
|
||||
## Constructs ## |
||||
|
||||
We support the following meta programming constructs: |
||||
|
||||
| `$var id = exp` | Defines a named constant value. `$id` is valid util the end of the current meta lexical block. | |
||||
|:----------------|:-----------------------------------------------------------------------------------------------| |
||||
| `$range id exp..exp` | Sets the range of an iteration variable, which can be reused in multiple loops later. | |
||||
| `$for id sep [[ code ]]` | Iteration. The range of `id` must have been defined earlier. `$id` is valid in `code`. | |
||||
| `$($)` | Generates a single `$` character. | |
||||
| `$id` | Value of the named constant or iteration variable. | |
||||
| `$(exp)` | Value of the expression. | |
||||
| `$if exp [[ code ]] else_branch` | Conditional. | |
||||
| `[[ code ]]` | Meta lexical block. | |
||||
| `cpp_code` | Raw C++ code. | |
||||
| `$$ comment` | Meta comment. | |
||||
|
||||
**Note:** To give the user some freedom in formatting the Pump source |
||||
code, Pump ignores a new-line character if it's right after `$for foo` |
||||
or next to `[[` or `]]`. Without this rule you'll often be forced to write |
||||
very long lines to get the desired output. Therefore sometimes you may |
||||
need to insert an extra new-line in such places for a new-line to show |
||||
up in your output. |
||||
|
||||
## Grammar ## |
||||
|
||||
``` |
||||
code ::= atomic_code* |
||||
atomic_code ::= $var id = exp |
||||
| $var id = [[ code ]] |
||||
| $range id exp..exp |
||||
| $for id sep [[ code ]] |
||||
| $($) |
||||
| $id |
||||
| $(exp) |
||||
| $if exp [[ code ]] else_branch |
||||
| [[ code ]] |
||||
| cpp_code |
||||
sep ::= cpp_code | empty_string |
||||
else_branch ::= $else [[ code ]] |
||||
| $elif exp [[ code ]] else_branch |
||||
| empty_string |
||||
exp ::= simple_expression_in_Python_syntax |
||||
``` |
||||
|
||||
## Code ## |
||||
|
||||
You can find the source code of Pump in [scripts/pump.py](../scripts/pump.py). It is still |
||||
very unpolished and lacks automated tests, although it has been |
||||
successfully used many times. If you find a chance to use it in your |
||||
project, please let us know what you think! We also welcome help on |
||||
improving Pump. |
||||
|
||||
## Real Examples ## |
||||
|
||||
You can find real-world applications of Pump in [Google Test](http://www.google.com/codesearch?q=file%3A\.pump%24+package%3Ahttp%3A%2F%2Fgoogletest\.googlecode\.com) and [Google Mock](http://www.google.com/codesearch?q=file%3A\.pump%24+package%3Ahttp%3A%2F%2Fgooglemock\.googlecode\.com). The source file `foo.h.pump` generates `foo.h`. |
||||
|
||||
## Tips ## |
||||
|
||||
* If a meta variable is followed by a letter or digit, you can separate them using `[[]]`, which inserts an empty string. For example `Foo$j[[]]Helper` generate `Foo1Helper` when `j` is 1. |
||||
* To avoid extra-long Pump source lines, you can break a line anywhere you want by inserting `[[]]` followed by a new line. Since any new-line character next to `[[` or `]]` is ignored, the generated code won't contain this new line. |
@ -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. |
@ -1,93 +0,0 @@ |
||||
|
||||
|
||||
This guide will explain how to use the Google Testing Framework in your Xcode projects on Mac OS X. This tutorial begins by quickly explaining what to do for experienced users. After the quick start, the guide goes provides additional explanation about each step. |
||||
|
||||
# Quick Start # |
||||
|
||||
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. 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" |
||||
1. Add your unit test source code to the "Compile Sources" build phase of "UnitTests" |
||||
1. Edit the "UnitTests" executable and add an environment variable named "DYLD\_FRAMEWORK\_PATH" with a value equal to the path to the framework containing the gtest.framework relative to the compiled executable. |
||||
1. Build and Go |
||||
|
||||
The following sections further explain each of the steps listed above in depth, describing in more detail how to complete it including some variations. |
||||
|
||||
# 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: |
||||
|
||||
``` |
||||
svn checkout http://googletest.googlecode.com/svn/trunk/ googletest-read-only |
||||
``` |
||||
|
||||
Alternatively, if you are working with Subversion in your own code base, you can add Google Test as an external dependency to your own Subversion repository. By following this approach, everyone that checks out your svn repository will also receive a copy of Google Test (a specific version, if you wish) without having to check it out explicitly. This makes the set up of your project simpler and reduces the copied code in the repository. |
||||
|
||||
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`). |
||||
|
||||
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. |
||||
|
||||
``` |
||||
[Computer:svn] user$ svn propget svn:externals trunk |
||||
externals/src/googletest http://googletest.googlecode.com/svn/trunk |
||||
``` |
||||
|
||||
# Add the Framework to Your Project # |
||||
|
||||
The next step is to build and add the gtest.framework to your own project. This guide describes two common ways below. |
||||
|
||||
* **Option 1** --- The simplest way to add Google Test to your own project, is to open gtest.xcodeproj (found in the xcode/ directory of the Google Test trunk) and build the framework manually. Then, add the built framework into your project using the "Add->Existing Framework..." from the context menu or "Project->Add..." from the main menu. The gtest.framework is relocatable and contains the headers and object code that you'll need to make tests. This method requires rebuilding every time you upgrade Google Test in your project. |
||||
* **Option 2** --- If you are going to be living off the trunk of Google Test, incorporating its latest features into your unit tests (or are a Google Test developer yourself). You'll want to rebuild the framework every time the source updates. to do this, you'll need to add the gtest.xcodeproj file, not the framework itself, to your own Xcode project. Then, from the build products that are revealed by the project's disclosure triangle, you can find the gtest.framework, which can be added to your targets (discussed below). |
||||
|
||||
# Make a Test Target # |
||||
|
||||
To start writing tests, make a new "Shell Tool" target. This target template is available under BSD, Cocoa, or Carbon. Add your unit test source code to the "Compile Sources" build phase of the target. |
||||
|
||||
Next, you'll want to add gtest.framework in two different ways, depending upon which option you chose above. |
||||
|
||||
* **Option 1** --- During compilation, Xcode will need to know that you are linking against the gtest.framework. Add the gtest.framework to the "Link Binary with Libraries" build phase of your test target. This will include the Google Test headers in your header search path, and will tell the linker where to find the library. |
||||
* **Option 2** --- If your working out of the trunk, you'll also want to add gtest.framework to your "Link Binary with Libraries" build phase of your test target. In addition, you'll want to add the gtest.framework as a dependency to your unit test target. This way, Xcode will make sure that gtest.framework is up to date, every time your build your target. Finally, if you don't share build directories with Google Test, you'll have to copy the gtest.framework into your own build products directory using a "Run Script" build phase. |
||||
|
||||
# Set Up the Executable Run Environment # |
||||
|
||||
Since the unit test executable is a shell tool, it doesn't have a bundle with a `Contents/Frameworks` directory, in which to place gtest.framework. Instead, the dynamic linker must be told at runtime to search for the framework in another location. This can be accomplished by setting the "DYLD\_FRAMEWORK\_PATH" environment variable in the "Edit Active Executable ..." Arguments tab, under "Variables to be set in the environment:". The path for this value is the path (relative or absolute) of the directory containing the gtest.framework. |
||||
|
||||
If you haven't set up the DYLD\_FRAMEWORK\_PATH, correctly, you might get a message like this: |
||||
|
||||
``` |
||||
[Session started at 2008-08-15 06:23:57 -0600.] |
||||
dyld: Library not loaded: @loader_path/../Frameworks/gtest.framework/Versions/A/gtest |
||||
Referenced from: /Users/username/Documents/Sandbox/gtestSample/build/Debug/WidgetFrameworkTest |
||||
Reason: image not found |
||||
``` |
||||
|
||||
To correct this problem, got to the directory containing the executable named in "Referenced from:" value in the error message above. Then, with the terminal in this location, find the relative path to the directory containing the gtest.framework. That is the value you'll need to set as the DYLD\_FRAMEWORK\_PATH. |
||||
|
||||
# Build and Go # |
||||
|
||||
Now, when you click "Build and Go", the test will be executed. Dumping out something like this: |
||||
|
||||
``` |
||||
[Session started at 2008-08-06 06:36:13 -0600.] |
||||
[==========] Running 2 tests from 1 test case. |
||||
[----------] Global test environment set-up. |
||||
[----------] 2 tests from WidgetInitializerTest |
||||
[ RUN ] WidgetInitializerTest.TestConstructor |
||||
[ OK ] WidgetInitializerTest.TestConstructor |
||||
[ RUN ] WidgetInitializerTest.TestConversion |
||||
[ OK ] WidgetInitializerTest.TestConversion |
||||
[----------] Global test environment tear-down |
||||
[==========] 2 tests from 1 test case ran. |
||||
[ PASSED ] 2 tests. |
||||
|
||||
The Debugger has exited with status 0. |
||||
``` |
||||
|
||||
# Summary # |
||||
|
||||
Unit testing is a valuable way to ensure your data model stays valid even during rapid development or refactoring. The Google Testing Framework is a great unit testing framework for C and C++ which integrates well with an Xcode development environment. |
File diff suppressed because it is too large
Load Diff
@ -1,14 +0,0 @@ |
||||
This page lists all documentation wiki pages for Google Test **(the SVN trunk version)** |
||||
-- **if you use a released version of Google Test, please read the |
||||
documentation for that specific version instead.** |
||||
|
||||
* [Primer](V1_7_Primer.md) -- start here if you are new to Google Test. |
||||
* [Samples](V1_7_Samples.md) -- learn from examples. |
||||
* [AdvancedGuide](V1_7_AdvancedGuide.md) -- learn more about Google Test. |
||||
* [XcodeGuide](V1_7_XcodeGuide.md) -- how to use Google Test in Xcode on Mac. |
||||
* [Frequently-Asked Questions](V1_7_FAQ.md) -- check here before asking a question on the mailing list. |
||||
|
||||
To contribute code to Google Test, read: |
||||
|
||||
* [DevGuide](DevGuide.md) -- read this _before_ writing your first patch. |
||||
* [PumpManual](V1_7_PumpManual.md) -- how we generate some of Google Test's source files. |
File diff suppressed because it is too large
Load Diff
@ -1,502 +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_. |
||||
|
||||
# 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(`_expected_`, `_actual_`);`|`EXPECT_EQ(`_expected_`, `_actual_`);`| _expected_ `==` _actual_ | |
||||
|`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_ |
||||
. In `ASSERT_EQ*` and `EXPECT_EQ*` (and all other equality assertions |
||||
we'll introduce later), you should put the expression you want to test |
||||
in the position of _actual_, and put its expected value in _expected_, |
||||
as Google Test's failure messages are optimized for this convention. |
||||
|
||||
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. |
||||
|
||||
## 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(`_expected\_str_`, `_actual\_str_`);` | `EXPECT_STREQ(`_expected\_str_`, `_actual\_str_`);` | 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(`_expected\_str_`, `_actual\_str_`);`| `EXPECT_STRCASEEQ(`_expected\_str_`, `_actual\_str_`);` | 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](V1_7_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(test_case_name, test_name) { |
||||
... 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](V1_7_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 text 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](V1_7_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](V1_7_Samples.md), or continue with |
||||
[AdvancedGuide](V1_7_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. |
@ -1,177 +0,0 @@ |
||||
|
||||
|
||||
<b>P</b>ump is <b>U</b>seful for <b>M</b>eta <b>P</b>rogramming. |
||||
|
||||
# The Problem # |
||||
|
||||
Template and macro libraries often need to define many classes, |
||||
functions, or macros that vary only (or almost only) in the number of |
||||
arguments they take. It's a lot of repetitive, mechanical, and |
||||
error-prone work. |
||||
|
||||
Variadic templates and variadic macros can alleviate the problem. |
||||
However, while both are being considered by the C++ committee, neither |
||||
is in the standard yet or widely supported by compilers. Thus they |
||||
are often not a good choice, especially when your code needs to be |
||||
portable. And their capabilities are still limited. |
||||
|
||||
As a result, authors of such libraries often have to write scripts to |
||||
generate their implementation. However, our experience is that it's |
||||
tedious to write such scripts, which tend to reflect the structure of |
||||
the generated code poorly and are often hard to read and edit. For |
||||
example, a small change needed in the generated code may require some |
||||
non-intuitive, non-trivial changes in the script. This is especially |
||||
painful when experimenting with the code. |
||||
|
||||
# Our Solution # |
||||
|
||||
Pump (for Pump is Useful for Meta Programming, Pretty Useful for Meta |
||||
Programming, or Practical Utility for Meta Programming, whichever you |
||||
prefer) is a simple meta-programming tool for C++. The idea is that a |
||||
programmer writes a `foo.pump` file which contains C++ code plus meta |
||||
code that manipulates the C++ code. The meta code can handle |
||||
iterations over a range, nested iterations, local meta variable |
||||
definitions, simple arithmetic, and conditional expressions. You can |
||||
view it as a small Domain-Specific Language. The meta language is |
||||
designed to be non-intrusive (s.t. it won't confuse Emacs' C++ mode, |
||||
for example) and concise, making Pump code intuitive and easy to |
||||
maintain. |
||||
|
||||
## Highlights ## |
||||
|
||||
* The implementation is in a single Python script and thus ultra portable: no build or installation is needed and it works cross platforms. |
||||
* Pump tries to be smart with respect to [Google's style guide](http://code.google.com/p/google-styleguide/): it breaks long lines (easy to have when they are generated) at acceptable places to fit within 80 columns and indent the continuation lines correctly. |
||||
* The format is human-readable and more concise than XML. |
||||
* The format works relatively well with Emacs' C++ mode. |
||||
|
||||
## Examples ## |
||||
|
||||
The following Pump code (where meta keywords start with `$`, `[[` and `]]` are meta brackets, and `$$` starts a meta comment that ends with the line): |
||||
|
||||
``` |
||||
$var n = 3 $$ Defines a meta variable n. |
||||
$range i 0..n $$ Declares the range of meta iterator i (inclusive). |
||||
$for i [[ |
||||
$$ Meta loop. |
||||
// Foo$i does blah for $i-ary predicates. |
||||
$range j 1..i |
||||
template <size_t N $for j [[, typename A$j]]> |
||||
class Foo$i { |
||||
$if i == 0 [[ |
||||
blah a; |
||||
]] $elif i <= 2 [[ |
||||
blah b; |
||||
]] $else [[ |
||||
blah c; |
||||
]] |
||||
}; |
||||
|
||||
]] |
||||
``` |
||||
|
||||
will be translated by the Pump compiler to: |
||||
|
||||
``` |
||||
// Foo0 does blah for 0-ary predicates. |
||||
template <size_t N> |
||||
class Foo0 { |
||||
blah a; |
||||
}; |
||||
|
||||
// Foo1 does blah for 1-ary predicates. |
||||
template <size_t N, typename A1> |
||||
class Foo1 { |
||||
blah b; |
||||
}; |
||||
|
||||
// Foo2 does blah for 2-ary predicates. |
||||
template <size_t N, typename A1, typename A2> |
||||
class Foo2 { |
||||
blah b; |
||||
}; |
||||
|
||||
// Foo3 does blah for 3-ary predicates. |
||||
template <size_t N, typename A1, typename A2, typename A3> |
||||
class Foo3 { |
||||
blah c; |
||||
}; |
||||
``` |
||||
|
||||
In another example, |
||||
|
||||
``` |
||||
$range i 1..n |
||||
Func($for i + [[a$i]]); |
||||
$$ The text between i and [[ is the separator between iterations. |
||||
``` |
||||
|
||||
will generate one of the following lines (without the comments), depending on the value of `n`: |
||||
|
||||
``` |
||||
Func(); // If n is 0. |
||||
Func(a1); // If n is 1. |
||||
Func(a1 + a2); // If n is 2. |
||||
Func(a1 + a2 + a3); // If n is 3. |
||||
// And so on... |
||||
``` |
||||
|
||||
## Constructs ## |
||||
|
||||
We support the following meta programming constructs: |
||||
|
||||
| `$var id = exp` | Defines a named constant value. `$id` is valid util the end of the current meta lexical block. | |
||||
|:----------------|:-----------------------------------------------------------------------------------------------| |
||||
| `$range id exp..exp` | Sets the range of an iteration variable, which can be reused in multiple loops later. | |
||||
| `$for id sep [[ code ]]` | Iteration. The range of `id` must have been defined earlier. `$id` is valid in `code`. | |
||||
| `$($)` | Generates a single `$` character. | |
||||
| `$id` | Value of the named constant or iteration variable. | |
||||
| `$(exp)` | Value of the expression. | |
||||
| `$if exp [[ code ]] else_branch` | Conditional. | |
||||
| `[[ code ]]` | Meta lexical block. | |
||||
| `cpp_code` | Raw C++ code. | |
||||
| `$$ comment` | Meta comment. | |
||||
|
||||
**Note:** To give the user some freedom in formatting the Pump source |
||||
code, Pump ignores a new-line character if it's right after `$for foo` |
||||
or next to `[[` or `]]`. Without this rule you'll often be forced to write |
||||
very long lines to get the desired output. Therefore sometimes you may |
||||
need to insert an extra new-line in such places for a new-line to show |
||||
up in your output. |
||||
|
||||
## Grammar ## |
||||
|
||||
``` |
||||
code ::= atomic_code* |
||||
atomic_code ::= $var id = exp |
||||
| $var id = [[ code ]] |
||||
| $range id exp..exp |
||||
| $for id sep [[ code ]] |
||||
| $($) |
||||
| $id |
||||
| $(exp) |
||||
| $if exp [[ code ]] else_branch |
||||
| [[ code ]] |
||||
| cpp_code |
||||
sep ::= cpp_code | empty_string |
||||
else_branch ::= $else [[ code ]] |
||||
| $elif exp [[ code ]] else_branch |
||||
| empty_string |
||||
exp ::= simple_expression_in_Python_syntax |
||||
``` |
||||
|
||||
## Code ## |
||||
|
||||
You can find the source code of Pump in [scripts/pump.py](../scripts/pump.py). It is still |
||||
very unpolished and lacks automated tests, although it has been |
||||
successfully used many times. If you find a chance to use it in your |
||||
project, please let us know what you think! We also welcome help on |
||||
improving Pump. |
||||
|
||||
## Real Examples ## |
||||
|
||||
You can find real-world applications of Pump in [Google Test](http://www.google.com/codesearch?q=file%3A\.pump%24+package%3Ahttp%3A%2F%2Fgoogletest\.googlecode\.com) and [Google Mock](http://www.google.com/codesearch?q=file%3A\.pump%24+package%3Ahttp%3A%2F%2Fgooglemock\.googlecode\.com). The source file `foo.h.pump` generates `foo.h`. |
||||
|
||||
## Tips ## |
||||
|
||||
* If a meta variable is followed by a letter or digit, you can separate them using `[[]]`, which inserts an empty string. For example `Foo$j[[]]Helper` generate `Foo1Helper` when `j` is 1. |
||||
* To avoid extra-long Pump source lines, you can break a line anywhere you want by inserting `[[]]` followed by a new line. Since any new-line character next to `[[` or `]]` is ignored, the generated code won't contain this new line. |
@ -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. |
@ -1,93 +0,0 @@ |
||||
|
||||
|
||||
This guide will explain how to use the Google Testing Framework in your Xcode projects on Mac OS X. This tutorial begins by quickly explaining what to do for experienced users. After the quick start, the guide goes provides additional explanation about each step. |
||||
|
||||
# Quick Start # |
||||
|
||||
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. 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" |
||||
1. Add your unit test source code to the "Compile Sources" build phase of "UnitTests" |
||||
1. Edit the "UnitTests" executable and add an environment variable named "DYLD\_FRAMEWORK\_PATH" with a value equal to the path to the framework containing the gtest.framework relative to the compiled executable. |
||||
1. Build and Go |
||||
|
||||
The following sections further explain each of the steps listed above in depth, describing in more detail how to complete it including some variations. |
||||
|
||||
# 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: |
||||
|
||||
``` |
||||
svn checkout http://googletest.googlecode.com/svn/trunk/ googletest-read-only |
||||
``` |
||||
|
||||
Alternatively, if you are working with Subversion in your own code base, you can add Google Test as an external dependency to your own Subversion repository. By following this approach, everyone that checks out your svn repository will also receive a copy of Google Test (a specific version, if you wish) without having to check it out explicitly. This makes the set up of your project simpler and reduces the copied code in the repository. |
||||
|
||||
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`). |
||||
|
||||
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. |
||||
|
||||
``` |
||||
[Computer:svn] user$ svn propget svn:externals trunk |
||||
externals/src/googletest http://googletest.googlecode.com/svn/trunk |
||||
``` |
||||
|
||||
# Add the Framework to Your Project # |
||||
|
||||
The next step is to build and add the gtest.framework to your own project. This guide describes two common ways below. |
||||
|
||||
* **Option 1** --- The simplest way to add Google Test to your own project, is to open gtest.xcodeproj (found in the xcode/ directory of the Google Test trunk) and build the framework manually. Then, add the built framework into your project using the "Add->Existing Framework..." from the context menu or "Project->Add..." from the main menu. The gtest.framework is relocatable and contains the headers and object code that you'll need to make tests. This method requires rebuilding every time you upgrade Google Test in your project. |
||||
* **Option 2** --- If you are going to be living off the trunk of Google Test, incorporating its latest features into your unit tests (or are a Google Test developer yourself). You'll want to rebuild the framework every time the source updates. to do this, you'll need to add the gtest.xcodeproj file, not the framework itself, to your own Xcode project. Then, from the build products that are revealed by the project's disclosure triangle, you can find the gtest.framework, which can be added to your targets (discussed below). |
||||
|
||||
# Make a Test Target # |
||||
|
||||
To start writing tests, make a new "Shell Tool" target. This target template is available under BSD, Cocoa, or Carbon. Add your unit test source code to the "Compile Sources" build phase of the target. |
||||
|
||||
Next, you'll want to add gtest.framework in two different ways, depending upon which option you chose above. |
||||
|
||||
* **Option 1** --- During compilation, Xcode will need to know that you are linking against the gtest.framework. Add the gtest.framework to the "Link Binary with Libraries" build phase of your test target. This will include the Google Test headers in your header search path, and will tell the linker where to find the library. |
||||
* **Option 2** --- If your working out of the trunk, you'll also want to add gtest.framework to your "Link Binary with Libraries" build phase of your test target. In addition, you'll want to add the gtest.framework as a dependency to your unit test target. This way, Xcode will make sure that gtest.framework is up to date, every time your build your target. Finally, if you don't share build directories with Google Test, you'll have to copy the gtest.framework into your own build products directory using a "Run Script" build phase. |
||||
|
||||
# Set Up the Executable Run Environment # |
||||
|
||||
Since the unit test executable is a shell tool, it doesn't have a bundle with a `Contents/Frameworks` directory, in which to place gtest.framework. Instead, the dynamic linker must be told at runtime to search for the framework in another location. This can be accomplished by setting the "DYLD\_FRAMEWORK\_PATH" environment variable in the "Edit Active Executable ..." Arguments tab, under "Variables to be set in the environment:". The path for this value is the path (relative or absolute) of the directory containing the gtest.framework. |
||||
|
||||
If you haven't set up the DYLD\_FRAMEWORK\_PATH, correctly, you might get a message like this: |
||||
|
||||
``` |
||||
[Session started at 2008-08-15 06:23:57 -0600.] |
||||
dyld: Library not loaded: @loader_path/../Frameworks/gtest.framework/Versions/A/gtest |
||||
Referenced from: /Users/username/Documents/Sandbox/gtestSample/build/Debug/WidgetFrameworkTest |
||||
Reason: image not found |
||||
``` |
||||
|
||||
To correct this problem, got to the directory containing the executable named in "Referenced from:" value in the error message above. Then, with the terminal in this location, find the relative path to the directory containing the gtest.framework. That is the value you'll need to set as the DYLD\_FRAMEWORK\_PATH. |
||||
|
||||
# Build and Go # |
||||
|
||||
Now, when you click "Build and Go", the test will be executed. Dumping out something like this: |
||||
|
||||
``` |
||||
[Session started at 2008-08-06 06:36:13 -0600.] |
||||
[==========] Running 2 tests from 1 test case. |
||||
[----------] Global test environment set-up. |
||||
[----------] 2 tests from WidgetInitializerTest |
||||
[ RUN ] WidgetInitializerTest.TestConstructor |
||||
[ OK ] WidgetInitializerTest.TestConstructor |
||||
[ RUN ] WidgetInitializerTest.TestConversion |
||||
[ OK ] WidgetInitializerTest.TestConversion |
||||
[----------] Global test environment tear-down |
||||
[==========] 2 tests from 1 test case ran. |
||||
[ PASSED ] 2 tests. |
||||
|
||||
The Debugger has exited with status 0. |
||||
``` |
||||
|
||||
# Summary # |
||||
|
||||
Unit testing is a valuable way to ensure your data model stays valid even during rapid development or refactoring. The Google Testing Framework is a great unit testing framework for C and C++ which integrates well with an Xcode development environment. |
@ -0,0 +1,55 @@ |
||||
Microsoft Visual Studio Solution File, Format Version 11.00 |
||||
# Visual C++ Express 2010 |
||||
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "gtest-md", "gtest-md.vcxproj", "{C8F6C172-56F2-4E76-B5FA-C3B423B31BE8}" |
||||
EndProject |
||||
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "gtest_main-md", "gtest_main-md.vcxproj", "{3AF54C8A-10BF-4332-9147-F68ED9862033}" |
||||
EndProject |
||||
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "gtest_prod_test-md", "gtest_prod_test-md.vcxproj", "{24848551-EF4F-47E8-9A9D-EA4D49BC3ECB}" |
||||
EndProject |
||||
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "gtest_unittest-md", "gtest_unittest-md.vcxproj", "{4D9FDFB5-986A-4139-823C-F4EE0ED481A2}" |
||||
EndProject |
||||
Global |
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution |
||||
Debug|Win32 = Debug|Win32 |
||||
Debug|x64 = Debug|x64 |
||||
Release|Win32 = Release|Win32 |
||||
Release|x64 = Release|x64 |
||||
EndGlobalSection |
||||
GlobalSection(ProjectConfigurationPlatforms) = postSolution |
||||
{C8F6C172-56F2-4E76-B5FA-C3B423B31BE8}.Debug|Win32.ActiveCfg = Debug|Win32 |
||||
{C8F6C172-56F2-4E76-B5FA-C3B423B31BE8}.Debug|Win32.Build.0 = Debug|Win32 |
||||
{C8F6C172-56F2-4E76-B5FA-C3B423B31BE8}.Debug|x64.ActiveCfg = Debug|x64 |
||||
{C8F6C172-56F2-4E76-B5FA-C3B423B31BE8}.Debug|x64.Build.0 = Debug|x64 |
||||
{C8F6C172-56F2-4E76-B5FA-C3B423B31BE8}.Release|Win32.ActiveCfg = Release|Win32 |
||||
{C8F6C172-56F2-4E76-B5FA-C3B423B31BE8}.Release|Win32.Build.0 = Release|Win32 |
||||
{C8F6C172-56F2-4E76-B5FA-C3B423B31BE8}.Release|x64.ActiveCfg = Release|x64 |
||||
{C8F6C172-56F2-4E76-B5FA-C3B423B31BE8}.Release|x64.Build.0 = Release|x64 |
||||
{3AF54C8A-10BF-4332-9147-F68ED9862033}.Debug|Win32.ActiveCfg = Debug|Win32 |
||||
{3AF54C8A-10BF-4332-9147-F68ED9862033}.Debug|Win32.Build.0 = Debug|Win32 |
||||
{3AF54C8A-10BF-4332-9147-F68ED9862033}.Debug|x64.ActiveCfg = Debug|x64 |
||||
{3AF54C8A-10BF-4332-9147-F68ED9862033}.Debug|x64.Build.0 = Debug|x64 |
||||
{3AF54C8A-10BF-4332-9147-F68ED9862033}.Release|Win32.ActiveCfg = Release|Win32 |
||||
{3AF54C8A-10BF-4332-9147-F68ED9862033}.Release|Win32.Build.0 = Release|Win32 |
||||
{3AF54C8A-10BF-4332-9147-F68ED9862033}.Release|x64.ActiveCfg = Release|x64 |
||||
{3AF54C8A-10BF-4332-9147-F68ED9862033}.Release|x64.Build.0 = Release|x64 |
||||
{24848551-EF4F-47E8-9A9D-EA4D49BC3ECB}.Debug|Win32.ActiveCfg = Debug|Win32 |
||||
{24848551-EF4F-47E8-9A9D-EA4D49BC3ECB}.Debug|Win32.Build.0 = Debug|Win32 |
||||
{24848551-EF4F-47E8-9A9D-EA4D49BC3ECB}.Debug|x64.ActiveCfg = Debug|x64 |
||||
{24848551-EF4F-47E8-9A9D-EA4D49BC3ECB}.Debug|x64.Build.0 = Debug|x64 |
||||
{24848551-EF4F-47E8-9A9D-EA4D49BC3ECB}.Release|Win32.ActiveCfg = Release|Win32 |
||||
{24848551-EF4F-47E8-9A9D-EA4D49BC3ECB}.Release|Win32.Build.0 = Release|Win32 |
||||
{24848551-EF4F-47E8-9A9D-EA4D49BC3ECB}.Release|x64.ActiveCfg = Release|x64 |
||||
{24848551-EF4F-47E8-9A9D-EA4D49BC3ECB}.Release|x64.Build.0 = Release|x64 |
||||
{4D9FDFB5-986A-4139-823C-F4EE0ED481A2}.Debug|Win32.ActiveCfg = Debug|Win32 |
||||
{4D9FDFB5-986A-4139-823C-F4EE0ED481A2}.Debug|Win32.Build.0 = Debug|Win32 |
||||
{4D9FDFB5-986A-4139-823C-F4EE0ED481A2}.Debug|x64.ActiveCfg = Debug|x64 |
||||
{4D9FDFB5-986A-4139-823C-F4EE0ED481A2}.Debug|x64.Build.0 = Debug|x64 |
||||
{4D9FDFB5-986A-4139-823C-F4EE0ED481A2}.Release|Win32.ActiveCfg = Release|Win32 |
||||
{4D9FDFB5-986A-4139-823C-F4EE0ED481A2}.Release|Win32.Build.0 = Release|Win32 |
||||
{4D9FDFB5-986A-4139-823C-F4EE0ED481A2}.Release|x64.ActiveCfg = Release|x64 |
||||
{4D9FDFB5-986A-4139-823C-F4EE0ED481A2}.Release|x64.Build.0 = Release|x64 |
||||
EndGlobalSection |
||||
GlobalSection(SolutionProperties) = preSolution |
||||
HideSolutionNode = FALSE |
||||
EndGlobalSection |
||||
EndGlobal |
@ -0,0 +1,55 @@ |
||||
Microsoft Visual Studio Solution File, Format Version 11.00 |
||||
# Visual C++ Express 2010 |
||||
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "gtest", "gtest.vcxproj", "{C8F6C172-56F2-4E76-B5FA-C3B423B31BE7}" |
||||
EndProject |
||||
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "gtest_main", "gtest_main.vcxproj", "{3AF54C8A-10BF-4332-9147-F68ED9862032}" |
||||
EndProject |
||||
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "gtest_unittest", "gtest_unittest.vcxproj", "{4D9FDFB5-986A-4139-823C-F4EE0ED481A1}" |
||||
EndProject |
||||
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "gtest_prod_test", "gtest_prod_test.vcxproj", "{24848551-EF4F-47E8-9A9D-EA4D49BC3ECA}" |
||||
EndProject |
||||
Global |
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution |
||||
Debug|Win32 = Debug|Win32 |
||||
Debug|x64 = Debug|x64 |
||||
Release|Win32 = Release|Win32 |
||||
Release|x64 = Release|x64 |
||||
EndGlobalSection |
||||
GlobalSection(ProjectConfigurationPlatforms) = postSolution |
||||
{C8F6C172-56F2-4E76-B5FA-C3B423B31BE7}.Debug|Win32.ActiveCfg = Debug|Win32 |
||||
{C8F6C172-56F2-4E76-B5FA-C3B423B31BE7}.Debug|Win32.Build.0 = Debug|Win32 |
||||
{C8F6C172-56F2-4E76-B5FA-C3B423B31BE7}.Debug|x64.ActiveCfg = Debug|x64 |
||||
{C8F6C172-56F2-4E76-B5FA-C3B423B31BE7}.Debug|x64.Build.0 = Debug|x64 |
||||
{C8F6C172-56F2-4E76-B5FA-C3B423B31BE7}.Release|Win32.ActiveCfg = Release|Win32 |
||||
{C8F6C172-56F2-4E76-B5FA-C3B423B31BE7}.Release|Win32.Build.0 = Release|Win32 |
||||
{C8F6C172-56F2-4E76-B5FA-C3B423B31BE7}.Release|x64.ActiveCfg = Release|x64 |
||||
{C8F6C172-56F2-4E76-B5FA-C3B423B31BE7}.Release|x64.Build.0 = Release|x64 |
||||
{3AF54C8A-10BF-4332-9147-F68ED9862032}.Debug|Win32.ActiveCfg = Debug|Win32 |
||||
{3AF54C8A-10BF-4332-9147-F68ED9862032}.Debug|Win32.Build.0 = Debug|Win32 |
||||
{3AF54C8A-10BF-4332-9147-F68ED9862032}.Debug|x64.ActiveCfg = Debug|x64 |
||||
{3AF54C8A-10BF-4332-9147-F68ED9862032}.Debug|x64.Build.0 = Debug|x64 |
||||
{3AF54C8A-10BF-4332-9147-F68ED9862032}.Release|Win32.ActiveCfg = Release|Win32 |
||||
{3AF54C8A-10BF-4332-9147-F68ED9862032}.Release|Win32.Build.0 = Release|Win32 |
||||
{3AF54C8A-10BF-4332-9147-F68ED9862032}.Release|x64.ActiveCfg = Release|x64 |
||||
{3AF54C8A-10BF-4332-9147-F68ED9862032}.Release|x64.Build.0 = Release|x64 |
||||
{4D9FDFB5-986A-4139-823C-F4EE0ED481A1}.Debug|Win32.ActiveCfg = Debug|Win32 |
||||
{4D9FDFB5-986A-4139-823C-F4EE0ED481A1}.Debug|Win32.Build.0 = Debug|Win32 |
||||
{4D9FDFB5-986A-4139-823C-F4EE0ED481A1}.Debug|x64.ActiveCfg = Debug|x64 |
||||
{4D9FDFB5-986A-4139-823C-F4EE0ED481A1}.Debug|x64.Build.0 = Debug|x64 |
||||
{4D9FDFB5-986A-4139-823C-F4EE0ED481A1}.Release|Win32.ActiveCfg = Release|Win32 |
||||
{4D9FDFB5-986A-4139-823C-F4EE0ED481A1}.Release|Win32.Build.0 = Release|Win32 |
||||
{4D9FDFB5-986A-4139-823C-F4EE0ED481A1}.Release|x64.ActiveCfg = Release|x64 |
||||
{4D9FDFB5-986A-4139-823C-F4EE0ED481A1}.Release|x64.Build.0 = Release|x64 |
||||
{24848551-EF4F-47E8-9A9D-EA4D49BC3ECA}.Debug|Win32.ActiveCfg = Debug|Win32 |
||||
{24848551-EF4F-47E8-9A9D-EA4D49BC3ECA}.Debug|Win32.Build.0 = Debug|Win32 |
||||
{24848551-EF4F-47E8-9A9D-EA4D49BC3ECA}.Debug|x64.ActiveCfg = Debug|x64 |
||||
{24848551-EF4F-47E8-9A9D-EA4D49BC3ECA}.Debug|x64.Build.0 = Debug|x64 |
||||
{24848551-EF4F-47E8-9A9D-EA4D49BC3ECA}.Release|Win32.ActiveCfg = Release|Win32 |
||||
{24848551-EF4F-47E8-9A9D-EA4D49BC3ECA}.Release|Win32.Build.0 = Release|Win32 |
||||
{24848551-EF4F-47E8-9A9D-EA4D49BC3ECA}.Release|x64.ActiveCfg = Release|x64 |
||||
{24848551-EF4F-47E8-9A9D-EA4D49BC3ECA}.Release|x64.Build.0 = Release|x64 |
||||
EndGlobalSection |
||||
GlobalSection(SolutionProperties) = preSolution |
||||
HideSolutionNode = FALSE |
||||
EndGlobalSection |
||||
EndGlobal |
@ -1,45 +0,0 @@ |
||||
Microsoft Visual Studio Solution File, Format Version 8.00 |
||||
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "gtest-md", "gtest-md.vcproj", "{C8F6C172-56F2-4E76-B5FA-C3B423B31BE8}" |
||||
ProjectSection(ProjectDependencies) = postProject |
||||
EndProjectSection |
||||
EndProject |
||||
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "gtest_main-md", "gtest_main-md.vcproj", "{3AF54C8A-10BF-4332-9147-F68ED9862033}" |
||||
ProjectSection(ProjectDependencies) = postProject |
||||
EndProjectSection |
||||
EndProject |
||||
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "gtest_prod_test-md", "gtest_prod_test-md.vcproj", "{24848551-EF4F-47E8-9A9D-EA4D49BC3ECB}" |
||||
ProjectSection(ProjectDependencies) = postProject |
||||
EndProjectSection |
||||
EndProject |
||||
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "gtest_unittest-md", "gtest_unittest-md.vcproj", "{4D9FDFB5-986A-4139-823C-F4EE0ED481A2}" |
||||
ProjectSection(ProjectDependencies) = postProject |
||||
EndProjectSection |
||||
EndProject |
||||
Global |
||||
GlobalSection(SolutionConfiguration) = preSolution |
||||
Debug = Debug |
||||
Release = Release |
||||
EndGlobalSection |
||||
GlobalSection(ProjectConfiguration) = postSolution |
||||
{C8F6C172-56F2-4E76-B5FA-C3B423B31BE8}.Debug.ActiveCfg = Debug|Win32 |
||||
{C8F6C172-56F2-4E76-B5FA-C3B423B31BE8}.Debug.Build.0 = Debug|Win32 |
||||
{C8F6C172-56F2-4E76-B5FA-C3B423B31BE8}.Release.ActiveCfg = Release|Win32 |
||||
{C8F6C172-56F2-4E76-B5FA-C3B423B31BE8}.Release.Build.0 = Release|Win32 |
||||
{3AF54C8A-10BF-4332-9147-F68ED9862033}.Debug.ActiveCfg = Debug|Win32 |
||||
{3AF54C8A-10BF-4332-9147-F68ED9862033}.Debug.Build.0 = Debug|Win32 |
||||
{3AF54C8A-10BF-4332-9147-F68ED9862033}.Release.ActiveCfg = Release|Win32 |
||||
{3AF54C8A-10BF-4332-9147-F68ED9862033}.Release.Build.0 = Release|Win32 |
||||
{24848551-EF4F-47E8-9A9D-EA4D49BC3ECB}.Debug.ActiveCfg = Debug|Win32 |
||||
{24848551-EF4F-47E8-9A9D-EA4D49BC3ECB}.Debug.Build.0 = Debug|Win32 |
||||
{24848551-EF4F-47E8-9A9D-EA4D49BC3ECB}.Release.ActiveCfg = Release|Win32 |
||||
{24848551-EF4F-47E8-9A9D-EA4D49BC3ECB}.Release.Build.0 = Release|Win32 |
||||
{4D9FDFB5-986A-4139-823C-F4EE0ED481A2}.Debug.ActiveCfg = Debug|Win32 |
||||
{4D9FDFB5-986A-4139-823C-F4EE0ED481A2}.Debug.Build.0 = Debug|Win32 |
||||
{4D9FDFB5-986A-4139-823C-F4EE0ED481A2}.Release.ActiveCfg = Release|Win32 |
||||
{4D9FDFB5-986A-4139-823C-F4EE0ED481A2}.Release.Build.0 = Release|Win32 |
||||
EndGlobalSection |
||||
GlobalSection(ExtensibilityGlobals) = postSolution |
||||
EndGlobalSection |
||||
GlobalSection(ExtensibilityAddIns) = postSolution |
||||
EndGlobalSection |
||||
EndGlobal |
@ -1,126 +0,0 @@ |
||||
<?xml version="1.0" encoding="Windows-1252"?> |
||||
<VisualStudioProject |
||||
ProjectType="Visual C++" |
||||
Version="7.10" |
||||
Name="gtest-md" |
||||
ProjectGUID="{C8F6C172-56F2-4E76-B5FA-C3B423B31BE8}" |
||||
Keyword="Win32Proj"> |
||||
<Platforms> |
||||
<Platform |
||||
Name="Win32"/> |
||||
</Platforms> |
||||
<Configurations> |
||||
<Configuration |
||||
Name="Debug|Win32" |
||||
OutputDirectory="$(SolutionName)/$(ConfigurationName)" |
||||
IntermediateDirectory="$(OutDir)/$(ProjectName)" |
||||
ConfigurationType="4" |
||||
CharacterSet="2" |
||||
ReferencesPath=""> |
||||
<Tool |
||||
Name="VCCLCompilerTool" |
||||
Optimization="0" |
||||
PreprocessorDefinitions="WIN32;_DEBUG;_LIB" |
||||
MinimalRebuild="TRUE" |
||||
BasicRuntimeChecks="3" |
||||
RuntimeLibrary="3" |
||||
UsePrecompiledHeader="0" |
||||
WarningLevel="3" |
||||
Detect64BitPortabilityProblems="FALSE" |
||||
DebugInformationFormat="4"/> |
||||
<Tool |
||||
Name="VCCustomBuildTool"/> |
||||
<Tool |
||||
Name="VCLibrarianTool" |
||||
OutputFile="$(OutDir)/gtestd.lib"/> |
||||
<Tool |
||||
Name="VCMIDLTool"/> |
||||
<Tool |
||||
Name="VCPostBuildEventTool"/> |
||||
<Tool |
||||
Name="VCPreBuildEventTool"/> |
||||
<Tool |
||||
Name="VCPreLinkEventTool"/> |
||||
<Tool |
||||
Name="VCResourceCompilerTool"/> |
||||
<Tool |
||||
Name="VCWebServiceProxyGeneratorTool"/> |
||||
<Tool |
||||
Name="VCXMLDataGeneratorTool"/> |
||||
<Tool |
||||
Name="VCManagedWrapperGeneratorTool"/> |
||||
<Tool |
||||
Name="VCAuxiliaryManagedWrapperGeneratorTool"/> |
||||
</Configuration> |
||||
<Configuration |
||||
Name="Release|Win32" |
||||
OutputDirectory="$(SolutionName)/$(ConfigurationName)" |
||||
IntermediateDirectory="$(OutDir)/$(ProjectName)" |
||||
ConfigurationType="4" |
||||
CharacterSet="2" |
||||
ReferencesPath=""..\include";"..""> |
||||
<Tool |
||||
Name="VCCLCompilerTool" |
||||
PreprocessorDefinitions="WIN32;NDEBUG;_LIB" |
||||
RuntimeLibrary="2" |
||||
UsePrecompiledHeader="0" |
||||
WarningLevel="3" |
||||
Detect64BitPortabilityProblems="FALSE" |
||||
DebugInformationFormat="3"/> |
||||
<Tool |
||||
Name="VCCustomBuildTool"/> |
||||
<Tool |
||||
Name="VCLibrarianTool" |
||||
OutputFile="$(OutDir)/gtest.lib"/> |
||||
<Tool |
||||
Name="VCMIDLTool"/> |
||||
<Tool |
||||
Name="VCPostBuildEventTool"/> |
||||
<Tool |
||||
Name="VCPreBuildEventTool"/> |
||||
<Tool |
||||
Name="VCPreLinkEventTool"/> |
||||
<Tool |
||||
Name="VCResourceCompilerTool"/> |
||||
<Tool |
||||
Name="VCWebServiceProxyGeneratorTool"/> |
||||
<Tool |
||||
Name="VCXMLDataGeneratorTool"/> |
||||
<Tool |
||||
Name="VCManagedWrapperGeneratorTool"/> |
||||
<Tool |
||||
Name="VCAuxiliaryManagedWrapperGeneratorTool"/> |
||||
</Configuration> |
||||
</Configurations> |
||||
<References> |
||||
</References> |
||||
<Files> |
||||
<Filter |
||||
Name="Source Files" |
||||
Filter="cpp;c;cxx;def;odl;idl;hpj;bat;asm;asmx" |
||||
UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}"> |
||||
<File |
||||
RelativePath="..\src\gtest-all.cc"> |
||||
<FileConfiguration |
||||
Name="Debug|Win32"> |
||||
<Tool |
||||
Name="VCCLCompilerTool" |
||||
AdditionalIncludeDirectories=""..";"..\include""/> |
||||
</FileConfiguration> |
||||
<FileConfiguration |
||||
Name="Release|Win32"> |
||||
<Tool |
||||
Name="VCCLCompilerTool" |
||||
AdditionalIncludeDirectories=""..";"..\include""/> |
||||
</FileConfiguration> |
||||
</File> |
||||
</Filter> |
||||
<Filter |
||||
Name="Header Files" |
||||
Filter="h;hpp;hxx;hm;inl;inc;xsd" |
||||
UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}"> |
||||
</Filter> |
||||
</Files> |
||||
<Globals> |
||||
</Globals> |
||||
</VisualStudioProject> |
@ -1,45 +0,0 @@ |
||||
Microsoft Visual Studio Solution File, Format Version 8.00 |
||||
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "gtest", "gtest.vcproj", "{C8F6C172-56F2-4E76-B5FA-C3B423B31BE7}" |
||||
ProjectSection(ProjectDependencies) = postProject |
||||
EndProjectSection |
||||
EndProject |
||||
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "gtest_main", "gtest_main.vcproj", "{3AF54C8A-10BF-4332-9147-F68ED9862032}" |
||||
ProjectSection(ProjectDependencies) = postProject |
||||
EndProjectSection |
||||
EndProject |
||||
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "gtest_unittest", "gtest_unittest.vcproj", "{4D9FDFB5-986A-4139-823C-F4EE0ED481A1}" |
||||
ProjectSection(ProjectDependencies) = postProject |
||||
EndProjectSection |
||||
EndProject |
||||
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "gtest_prod_test", "gtest_prod_test.vcproj", "{24848551-EF4F-47E8-9A9D-EA4D49BC3ECA}" |
||||
ProjectSection(ProjectDependencies) = postProject |
||||
EndProjectSection |
||||
EndProject |
||||
Global |
||||
GlobalSection(SolutionConfiguration) = preSolution |
||||
Debug = Debug |
||||
Release = Release |
||||
EndGlobalSection |
||||
GlobalSection(ProjectConfiguration) = postSolution |
||||
{C8F6C172-56F2-4E76-B5FA-C3B423B31BE7}.Debug.ActiveCfg = Debug|Win32 |
||||
{C8F6C172-56F2-4E76-B5FA-C3B423B31BE7}.Debug.Build.0 = Debug|Win32 |
||||
{C8F6C172-56F2-4E76-B5FA-C3B423B31BE7}.Release.ActiveCfg = Release|Win32 |
||||
{C8F6C172-56F2-4E76-B5FA-C3B423B31BE7}.Release.Build.0 = Release|Win32 |
||||
{3AF54C8A-10BF-4332-9147-F68ED9862032}.Debug.ActiveCfg = Debug|Win32 |
||||
{3AF54C8A-10BF-4332-9147-F68ED9862032}.Debug.Build.0 = Debug|Win32 |
||||
{3AF54C8A-10BF-4332-9147-F68ED9862032}.Release.ActiveCfg = Release|Win32 |
||||
{3AF54C8A-10BF-4332-9147-F68ED9862032}.Release.Build.0 = Release|Win32 |
||||
{4D9FDFB5-986A-4139-823C-F4EE0ED481A1}.Debug.ActiveCfg = Debug|Win32 |
||||
{4D9FDFB5-986A-4139-823C-F4EE0ED481A1}.Debug.Build.0 = Debug|Win32 |
||||
{4D9FDFB5-986A-4139-823C-F4EE0ED481A1}.Release.ActiveCfg = Release|Win32 |
||||
{4D9FDFB5-986A-4139-823C-F4EE0ED481A1}.Release.Build.0 = Release|Win32 |
||||
{24848551-EF4F-47E8-9A9D-EA4D49BC3ECA}.Debug.ActiveCfg = Debug|Win32 |
||||
{24848551-EF4F-47E8-9A9D-EA4D49BC3ECA}.Debug.Build.0 = Debug|Win32 |
||||
{24848551-EF4F-47E8-9A9D-EA4D49BC3ECA}.Release.ActiveCfg = Release|Win32 |
||||
{24848551-EF4F-47E8-9A9D-EA4D49BC3ECA}.Release.Build.0 = Release|Win32 |
||||
EndGlobalSection |
||||
GlobalSection(ExtensibilityGlobals) = postSolution |
||||
EndGlobalSection |
||||
GlobalSection(ExtensibilityAddIns) = postSolution |
||||
EndGlobalSection |
||||
EndGlobal |
@ -1,126 +0,0 @@ |
||||
<?xml version="1.0" encoding="Windows-1252"?> |
||||
<VisualStudioProject |
||||
ProjectType="Visual C++" |
||||
Version="7.10" |
||||
Name="gtest" |
||||
ProjectGUID="{C8F6C172-56F2-4E76-B5FA-C3B423B31BE7}" |
||||
Keyword="Win32Proj"> |
||||
<Platforms> |
||||
<Platform |
||||
Name="Win32"/> |
||||
</Platforms> |
||||
<Configurations> |
||||
<Configuration |
||||
Name="Debug|Win32" |
||||
OutputDirectory="$(SolutionName)/$(ConfigurationName)" |
||||
IntermediateDirectory="$(OutDir)/$(ProjectName)" |
||||
ConfigurationType="4" |
||||
CharacterSet="2" |
||||
ReferencesPath=""> |
||||
<Tool |
||||
Name="VCCLCompilerTool" |
||||
Optimization="0" |
||||
PreprocessorDefinitions="WIN32;_DEBUG;_LIB" |
||||
MinimalRebuild="TRUE" |
||||
BasicRuntimeChecks="3" |
||||
RuntimeLibrary="5" |
||||
UsePrecompiledHeader="0" |
||||
WarningLevel="3" |
||||
Detect64BitPortabilityProblems="FALSE" |
||||
DebugInformationFormat="4"/> |
||||
<Tool |
||||
Name="VCCustomBuildTool"/> |
||||
<Tool |
||||
Name="VCLibrarianTool" |
||||
OutputFile="$(OutDir)/gtestd.lib"/> |
||||
<Tool |
||||
Name="VCMIDLTool"/> |
||||
<Tool |
||||
Name="VCPostBuildEventTool"/> |
||||
<Tool |
||||
Name="VCPreBuildEventTool"/> |
||||
<Tool |
||||
Name="VCPreLinkEventTool"/> |
||||
<Tool |
||||
Name="VCResourceCompilerTool"/> |
||||
<Tool |
||||
Name="VCWebServiceProxyGeneratorTool"/> |
||||
<Tool |
||||
Name="VCXMLDataGeneratorTool"/> |
||||
<Tool |
||||
Name="VCManagedWrapperGeneratorTool"/> |
||||
<Tool |
||||
Name="VCAuxiliaryManagedWrapperGeneratorTool"/> |
||||
</Configuration> |
||||
<Configuration |
||||
Name="Release|Win32" |
||||
OutputDirectory="$(SolutionName)/$(ConfigurationName)" |
||||
IntermediateDirectory="$(OutDir)/$(ProjectName)" |
||||
ConfigurationType="4" |
||||
CharacterSet="2" |
||||
ReferencesPath=""..\include";"..""> |
||||
<Tool |
||||
Name="VCCLCompilerTool" |
||||
PreprocessorDefinitions="WIN32;NDEBUG;_LIB" |
||||
RuntimeLibrary="4" |
||||
UsePrecompiledHeader="0" |
||||
WarningLevel="3" |
||||
Detect64BitPortabilityProblems="FALSE" |
||||
DebugInformationFormat="3"/> |
||||
<Tool |
||||
Name="VCCustomBuildTool"/> |
||||
<Tool |
||||
Name="VCLibrarianTool" |
||||
OutputFile="$(OutDir)/gtest.lib"/> |
||||
<Tool |
||||
Name="VCMIDLTool"/> |
||||
<Tool |
||||
Name="VCPostBuildEventTool"/> |
||||
<Tool |
||||
Name="VCPreBuildEventTool"/> |
||||
<Tool |
||||
Name="VCPreLinkEventTool"/> |
||||
<Tool |
||||
Name="VCResourceCompilerTool"/> |
||||
<Tool |
||||
Name="VCWebServiceProxyGeneratorTool"/> |
||||
<Tool |
||||
Name="VCXMLDataGeneratorTool"/> |
||||
<Tool |
||||
Name="VCManagedWrapperGeneratorTool"/> |
||||
<Tool |
||||
Name="VCAuxiliaryManagedWrapperGeneratorTool"/> |
||||
</Configuration> |
||||
</Configurations> |
||||
<References> |
||||
</References> |
||||
<Files> |
||||
<Filter |
||||
Name="Source Files" |
||||
Filter="cpp;c;cxx;def;odl;idl;hpj;bat;asm;asmx" |
||||
UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}"> |
||||
<File |
||||
RelativePath="..\src\gtest-all.cc"> |
||||
<FileConfiguration |
||||
Name="Debug|Win32"> |
||||
<Tool |
||||
Name="VCCLCompilerTool" |
||||
AdditionalIncludeDirectories=""..";"..\include""/> |
||||
</FileConfiguration> |
||||
<FileConfiguration |
||||
Name="Release|Win32"> |
||||
<Tool |
||||
Name="VCCLCompilerTool" |
||||
AdditionalIncludeDirectories=""..";"..\include""/> |
||||
</FileConfiguration> |
||||
</File> |
||||
</Filter> |
||||
<Filter |
||||
Name="Header Files" |
||||
Filter="h;hpp;hxx;hm;inl;inc;xsd" |
||||
UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}"> |
||||
</Filter> |
||||
</Files> |
||||
<Globals> |
||||
</Globals> |
||||
</VisualStudioProject> |
@ -1,129 +0,0 @@ |
||||
<?xml version="1.0" encoding="Windows-1252"?> |
||||
<VisualStudioProject |
||||
ProjectType="Visual C++" |
||||
Version="7.10" |
||||
Name="gtest_main-md" |
||||
ProjectGUID="{3AF54C8A-10BF-4332-9147-F68ED9862033}" |
||||
Keyword="Win32Proj"> |
||||
<Platforms> |
||||
<Platform |
||||
Name="Win32"/> |
||||
</Platforms> |
||||
<Configurations> |
||||
<Configuration |
||||
Name="Debug|Win32" |
||||
OutputDirectory="$(SolutionName)/$(ConfigurationName)" |
||||
IntermediateDirectory="$(OutDir)/$(ProjectName)" |
||||
ConfigurationType="4" |
||||
CharacterSet="2" |
||||
ReferencesPath=""> |
||||
<Tool |
||||
Name="VCCLCompilerTool" |
||||
Optimization="0" |
||||
PreprocessorDefinitions="WIN32;_DEBUG;_LIB" |
||||
MinimalRebuild="TRUE" |
||||
BasicRuntimeChecks="3" |
||||
RuntimeLibrary="3" |
||||
UsePrecompiledHeader="0" |
||||
WarningLevel="3" |
||||
Detect64BitPortabilityProblems="FALSE" |
||||
DebugInformationFormat="4"/> |
||||
<Tool |
||||
Name="VCCustomBuildTool"/> |
||||
<Tool |
||||
Name="VCLibrarianTool" |
||||
OutputFile="$(OutDir)/$(ProjectName)d.lib"/> |
||||
<Tool |
||||
Name="VCMIDLTool"/> |
||||
<Tool |
||||
Name="VCPostBuildEventTool"/> |
||||
<Tool |
||||
Name="VCPreBuildEventTool"/> |
||||
<Tool |
||||
Name="VCPreLinkEventTool"/> |
||||
<Tool |
||||
Name="VCResourceCompilerTool"/> |
||||
<Tool |
||||
Name="VCWebServiceProxyGeneratorTool"/> |
||||
<Tool |
||||
Name="VCXMLDataGeneratorTool"/> |
||||
<Tool |
||||
Name="VCManagedWrapperGeneratorTool"/> |
||||
<Tool |
||||
Name="VCAuxiliaryManagedWrapperGeneratorTool"/> |
||||
</Configuration> |
||||
<Configuration |
||||
Name="Release|Win32" |
||||
OutputDirectory="$(SolutionName)/$(ConfigurationName)" |
||||
IntermediateDirectory="$(OutDir)/$(ProjectName)" |
||||
ConfigurationType="4" |
||||
CharacterSet="2" |
||||
ReferencesPath=""..\include";"..""> |
||||
<Tool |
||||
Name="VCCLCompilerTool" |
||||
PreprocessorDefinitions="WIN32;NDEBUG;_LIB" |
||||
RuntimeLibrary="2" |
||||
UsePrecompiledHeader="0" |
||||
WarningLevel="3" |
||||
Detect64BitPortabilityProblems="FALSE" |
||||
DebugInformationFormat="3"/> |
||||
<Tool |
||||
Name="VCCustomBuildTool"/> |
||||
<Tool |
||||
Name="VCLibrarianTool" |
||||
OutputFile="$(OutDir)/$(ProjectName).lib"/> |
||||
<Tool |
||||
Name="VCMIDLTool"/> |
||||
<Tool |
||||
Name="VCPostBuildEventTool"/> |
||||
<Tool |
||||
Name="VCPreBuildEventTool"/> |
||||
<Tool |
||||
Name="VCPreLinkEventTool"/> |
||||
<Tool |
||||
Name="VCResourceCompilerTool"/> |
||||
<Tool |
||||
Name="VCWebServiceProxyGeneratorTool"/> |
||||
<Tool |
||||
Name="VCXMLDataGeneratorTool"/> |
||||
<Tool |
||||
Name="VCManagedWrapperGeneratorTool"/> |
||||
<Tool |
||||
Name="VCAuxiliaryManagedWrapperGeneratorTool"/> |
||||
</Configuration> |
||||
</Configurations> |
||||
<References> |
||||
<ProjectReference |
||||
ReferencedProjectIdentifier="{C8F6C172-56F2-4E76-B5FA-C3B423B31BE8}" |
||||
Name="gtest-md"/> |
||||
</References> |
||||
<Files> |
||||
<Filter |
||||
Name="Source Files" |
||||
Filter="cpp;c;cxx;def;odl;idl;hpj;bat;asm;asmx" |
||||
UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}"> |
||||
<File |
||||
RelativePath="..\src\gtest_main.cc"> |
||||
<FileConfiguration |
||||
Name="Debug|Win32"> |
||||
<Tool |
||||
Name="VCCLCompilerTool" |
||||
AdditionalIncludeDirectories=""..";"..\include""/> |
||||
</FileConfiguration> |
||||
<FileConfiguration |
||||
Name="Release|Win32"> |
||||
<Tool |
||||
Name="VCCLCompilerTool" |
||||
AdditionalIncludeDirectories=""..";"..\include""/> |
||||
</FileConfiguration> |
||||
</File> |
||||
</Filter> |
||||
<Filter |
||||
Name="Header Files" |
||||
Filter="h;hpp;hxx;hm;inl;inc;xsd" |
||||
UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}"> |
||||
</Filter> |
||||
</Files> |
||||
<Globals> |
||||
</Globals> |
||||
</VisualStudioProject> |
@ -1,129 +0,0 @@ |
||||
<?xml version="1.0" encoding="Windows-1252"?> |
||||
<VisualStudioProject |
||||
ProjectType="Visual C++" |
||||
Version="7.10" |
||||
Name="gtest_main" |
||||
ProjectGUID="{3AF54C8A-10BF-4332-9147-F68ED9862032}" |
||||
Keyword="Win32Proj"> |
||||
<Platforms> |
||||
<Platform |
||||
Name="Win32"/> |
||||
</Platforms> |
||||
<Configurations> |
||||
<Configuration |
||||
Name="Debug|Win32" |
||||
OutputDirectory="$(SolutionName)/$(ConfigurationName)" |
||||
IntermediateDirectory="$(OutDir)/$(ProjectName)" |
||||
ConfigurationType="4" |
||||
CharacterSet="2" |
||||
ReferencesPath=""> |
||||
<Tool |
||||
Name="VCCLCompilerTool" |
||||
Optimization="0" |
||||
PreprocessorDefinitions="WIN32;_DEBUG;_LIB" |
||||
MinimalRebuild="TRUE" |
||||
BasicRuntimeChecks="3" |
||||
RuntimeLibrary="5" |
||||
UsePrecompiledHeader="0" |
||||
WarningLevel="3" |
||||
Detect64BitPortabilityProblems="FALSE" |
||||
DebugInformationFormat="4"/> |
||||
<Tool |
||||
Name="VCCustomBuildTool"/> |
||||
<Tool |
||||
Name="VCLibrarianTool" |
||||
OutputFile="$(OutDir)/$(ProjectName)d.lib"/> |
||||
<Tool |
||||
Name="VCMIDLTool"/> |
||||
<Tool |
||||
Name="VCPostBuildEventTool"/> |
||||
<Tool |
||||
Name="VCPreBuildEventTool"/> |
||||
<Tool |
||||
Name="VCPreLinkEventTool"/> |
||||
<Tool |
||||
Name="VCResourceCompilerTool"/> |
||||
<Tool |
||||
Name="VCWebServiceProxyGeneratorTool"/> |
||||
<Tool |
||||
Name="VCXMLDataGeneratorTool"/> |
||||
<Tool |
||||
Name="VCManagedWrapperGeneratorTool"/> |
||||
<Tool |
||||
Name="VCAuxiliaryManagedWrapperGeneratorTool"/> |
||||
</Configuration> |
||||
<Configuration |
||||
Name="Release|Win32" |
||||
OutputDirectory="$(SolutionName)/$(ConfigurationName)" |
||||
IntermediateDirectory="$(OutDir)/$(ProjectName)" |
||||
ConfigurationType="4" |
||||
CharacterSet="2" |
||||
ReferencesPath=""..\include";"..""> |
||||
<Tool |
||||
Name="VCCLCompilerTool" |
||||
PreprocessorDefinitions="WIN32;NDEBUG;_LIB" |
||||
RuntimeLibrary="4" |
||||
UsePrecompiledHeader="0" |
||||
WarningLevel="3" |
||||
Detect64BitPortabilityProblems="FALSE" |
||||
DebugInformationFormat="3"/> |
||||
<Tool |
||||
Name="VCCustomBuildTool"/> |
||||
<Tool |
||||
Name="VCLibrarianTool" |
||||
OutputFile="$(OutDir)/$(ProjectName).lib"/> |
||||
<Tool |
||||
Name="VCMIDLTool"/> |
||||
<Tool |
||||
Name="VCPostBuildEventTool"/> |
||||
<Tool |
||||
Name="VCPreBuildEventTool"/> |
||||
<Tool |
||||
Name="VCPreLinkEventTool"/> |
||||
<Tool |
||||
Name="VCResourceCompilerTool"/> |
||||
<Tool |
||||
Name="VCWebServiceProxyGeneratorTool"/> |
||||
<Tool |
||||
Name="VCXMLDataGeneratorTool"/> |
||||
<Tool |
||||
Name="VCManagedWrapperGeneratorTool"/> |
||||
<Tool |
||||
Name="VCAuxiliaryManagedWrapperGeneratorTool"/> |
||||
</Configuration> |
||||
</Configurations> |
||||
<References> |
||||
<ProjectReference |
||||
ReferencedProjectIdentifier="{C8F6C172-56F2-4E76-B5FA-C3B423B31BE7}" |
||||
Name="gtest"/> |
||||
</References> |
||||
<Files> |
||||
<Filter |
||||
Name="Source Files" |
||||
Filter="cpp;c;cxx;def;odl;idl;hpj;bat;asm;asmx" |
||||
UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}"> |
||||
<File |
||||
RelativePath="..\src\gtest_main.cc"> |
||||
<FileConfiguration |
||||
Name="Debug|Win32"> |
||||
<Tool |
||||
Name="VCCLCompilerTool" |
||||
AdditionalIncludeDirectories=""..";"..\include""/> |
||||
</FileConfiguration> |
||||
<FileConfiguration |
||||
Name="Release|Win32"> |
||||
<Tool |
||||
Name="VCCLCompilerTool" |
||||
AdditionalIncludeDirectories=""..";"..\include""/> |
||||
</FileConfiguration> |
||||
</File> |
||||
</Filter> |
||||
<Filter |
||||
Name="Header Files" |
||||
Filter="h;hpp;hxx;hm;inl;inc;xsd" |
||||
UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}"> |
||||
</Filter> |
||||
</Files> |
||||
<Globals> |
||||
</Globals> |
||||
</VisualStudioProject> |
@ -1,164 +0,0 @@ |
||||
<?xml version="1.0" encoding="Windows-1252"?> |
||||
<VisualStudioProject |
||||
ProjectType="Visual C++" |
||||
Version="7.10" |
||||
Name="gtest_prod_test-md" |
||||
ProjectGUID="{24848551-EF4F-47E8-9A9D-EA4D49BC3ECB}" |
||||
Keyword="Win32Proj"> |
||||
<Platforms> |
||||
<Platform |
||||
Name="Win32"/> |
||||
</Platforms> |
||||
<Configurations> |
||||
<Configuration |
||||
Name="Debug|Win32" |
||||
OutputDirectory="$(SolutionName)/$(ConfigurationName)" |
||||
IntermediateDirectory="$(OutDir)/$(ProjectName)" |
||||
ConfigurationType="1" |
||||
CharacterSet="2"> |
||||
<Tool |
||||
Name="VCCLCompilerTool" |
||||
Optimization="0" |
||||
PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE" |
||||
MinimalRebuild="TRUE" |
||||
BasicRuntimeChecks="3" |
||||
RuntimeLibrary="3" |
||||
UsePrecompiledHeader="3" |
||||
WarningLevel="3" |
||||
Detect64BitPortabilityProblems="FALSE" |
||||
DebugInformationFormat="4"/> |
||||
<Tool |
||||
Name="VCCustomBuildTool"/> |
||||
<Tool |
||||
Name="VCLinkerTool" |
||||
OutputFile="$(OutDir)/gtest_prod_test.exe" |
||||
LinkIncremental="2" |
||||
GenerateDebugInformation="TRUE" |
||||
ProgramDatabaseFile="$(OutDir)/gtest_prod_test.pdb" |
||||
SubSystem="1" |
||||
TargetMachine="1"/> |
||||
<Tool |
||||
Name="VCMIDLTool"/> |
||||
<Tool |
||||
Name="VCPostBuildEventTool"/> |
||||
<Tool |
||||
Name="VCPreBuildEventTool"/> |
||||
<Tool |
||||
Name="VCPreLinkEventTool"/> |
||||
<Tool |
||||
Name="VCResourceCompilerTool"/> |
||||
<Tool |
||||
Name="VCWebServiceProxyGeneratorTool"/> |
||||
<Tool |
||||
Name="VCXMLDataGeneratorTool"/> |
||||
<Tool |
||||
Name="VCWebDeploymentTool"/> |
||||
<Tool |
||||
Name="VCManagedWrapperGeneratorTool"/> |
||||
<Tool |
||||
Name="VCAuxiliaryManagedWrapperGeneratorTool"/> |
||||
</Configuration> |
||||
<Configuration |
||||
Name="Release|Win32" |
||||
OutputDirectory="$(SolutionName)/$(ConfigurationName)" |
||||
IntermediateDirectory="$(OutDir)/$(ProjectName)" |
||||
ConfigurationType="1" |
||||
CharacterSet="2"> |
||||
<Tool |
||||
Name="VCCLCompilerTool" |
||||
PreprocessorDefinitions="WIN32;NDEBUG;_CONSOLE" |
||||
RuntimeLibrary="2" |
||||
UsePrecompiledHeader="3" |
||||
WarningLevel="3" |
||||
Detect64BitPortabilityProblems="FALSE" |
||||
DebugInformationFormat="3"/> |
||||
<Tool |
||||
Name="VCCustomBuildTool"/> |
||||
<Tool |
||||
Name="VCLinkerTool" |
||||
OutputFile="$(OutDir)/gtest_prod_test.exe" |
||||
LinkIncremental="1" |
||||
GenerateDebugInformation="TRUE" |
||||
SubSystem="1" |
||||
OptimizeReferences="2" |
||||
EnableCOMDATFolding="2" |
||||
TargetMachine="1"/> |
||||
<Tool |
||||
Name="VCMIDLTool"/> |
||||
<Tool |
||||
Name="VCPostBuildEventTool"/> |
||||
<Tool |
||||
Name="VCPreBuildEventTool"/> |
||||
<Tool |
||||
Name="VCPreLinkEventTool"/> |
||||
<Tool |
||||
Name="VCResourceCompilerTool"/> |
||||
<Tool |
||||
Name="VCWebServiceProxyGeneratorTool"/> |
||||
<Tool |
||||
Name="VCXMLDataGeneratorTool"/> |
||||
<Tool |
||||
Name="VCWebDeploymentTool"/> |
||||
<Tool |
||||
Name="VCManagedWrapperGeneratorTool"/> |
||||
<Tool |
||||
Name="VCAuxiliaryManagedWrapperGeneratorTool"/> |
||||
</Configuration> |
||||
</Configurations> |
||||
<References> |
||||
<ProjectReference |
||||
ReferencedProjectIdentifier="{3AF54C8A-10BF-4332-9147-F68ED9862033}" |
||||
Name="gtest_main-md"/> |
||||
</References> |
||||
<Files> |
||||
<Filter |
||||
Name="Source Files" |
||||
Filter="cpp;c;cxx;def;odl;idl;hpj;bat;asm;asmx" |
||||
UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}"> |
||||
<File |
||||
RelativePath="..\test\gtest_prod_test.cc"> |
||||
<FileConfiguration |
||||
Name="Debug|Win32"> |
||||
<Tool |
||||
Name="VCCLCompilerTool" |
||||
AdditionalIncludeDirectories=""..";"..\include"" |
||||
UsePrecompiledHeader="0"/> |
||||
</FileConfiguration> |
||||
<FileConfiguration |
||||
Name="Release|Win32"> |
||||
<Tool |
||||
Name="VCCLCompilerTool" |
||||
AdditionalIncludeDirectories=""..";"..\include"" |
||||
UsePrecompiledHeader="0"/> |
||||
</FileConfiguration> |
||||
</File> |
||||
<File |
||||
RelativePath="..\test\production.cc"> |
||||
<FileConfiguration |
||||
Name="Debug|Win32"> |
||||
<Tool |
||||
Name="VCCLCompilerTool" |
||||
AdditionalIncludeDirectories=""..";"..\include"" |
||||
UsePrecompiledHeader="0"/> |
||||
</FileConfiguration> |
||||
<FileConfiguration |
||||
Name="Release|Win32"> |
||||
<Tool |
||||
Name="VCCLCompilerTool" |
||||
AdditionalIncludeDirectories=""..";"..\include"" |
||||
UsePrecompiledHeader="0"/> |
||||
</FileConfiguration> |
||||
</File> |
||||
</Filter> |
||||
<Filter |
||||
Name="Header Files" |
||||
Filter="h;hpp;hxx;hm;inl;inc;xsd" |
||||
UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}"> |
||||
<File |
||||
RelativePath="..\test\production.h"> |
||||
</File> |
||||
</Filter> |
||||
</Files> |
||||
<Globals> |
||||
</Globals> |
||||
</VisualStudioProject> |
@ -1,164 +0,0 @@ |
||||
<?xml version="1.0" encoding="Windows-1252"?> |
||||
<VisualStudioProject |
||||
ProjectType="Visual C++" |
||||
Version="7.10" |
||||
Name="gtest_prod_test" |
||||
ProjectGUID="{24848551-EF4F-47E8-9A9D-EA4D49BC3ECA}" |
||||
Keyword="Win32Proj"> |
||||
<Platforms> |
||||
<Platform |
||||
Name="Win32"/> |
||||
</Platforms> |
||||
<Configurations> |
||||
<Configuration |
||||
Name="Debug|Win32" |
||||
OutputDirectory="$(SolutionName)/$(ConfigurationName)" |
||||
IntermediateDirectory="$(OutDir)/$(ProjectName)" |
||||
ConfigurationType="1" |
||||
CharacterSet="2"> |
||||
<Tool |
||||
Name="VCCLCompilerTool" |
||||
Optimization="0" |
||||
PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE" |
||||
MinimalRebuild="TRUE" |
||||
BasicRuntimeChecks="3" |
||||
RuntimeLibrary="5" |
||||
UsePrecompiledHeader="3" |
||||
WarningLevel="3" |
||||
Detect64BitPortabilityProblems="FALSE" |
||||
DebugInformationFormat="4"/> |
||||
<Tool |
||||
Name="VCCustomBuildTool"/> |
||||
<Tool |
||||
Name="VCLinkerTool" |
||||
OutputFile="$(OutDir)/gtest_prod_test.exe" |
||||
LinkIncremental="2" |
||||
GenerateDebugInformation="TRUE" |
||||
ProgramDatabaseFile="$(OutDir)/gtest_prod_test.pdb" |
||||
SubSystem="1" |
||||
TargetMachine="1"/> |
||||
<Tool |
||||
Name="VCMIDLTool"/> |
||||
<Tool |
||||
Name="VCPostBuildEventTool"/> |
||||
<Tool |
||||
Name="VCPreBuildEventTool"/> |
||||
<Tool |
||||
Name="VCPreLinkEventTool"/> |
||||
<Tool |
||||
Name="VCResourceCompilerTool"/> |
||||
<Tool |
||||
Name="VCWebServiceProxyGeneratorTool"/> |
||||
<Tool |
||||
Name="VCXMLDataGeneratorTool"/> |
||||
<Tool |
||||
Name="VCWebDeploymentTool"/> |
||||
<Tool |
||||
Name="VCManagedWrapperGeneratorTool"/> |
||||
<Tool |
||||
Name="VCAuxiliaryManagedWrapperGeneratorTool"/> |
||||
</Configuration> |
||||
<Configuration |
||||
Name="Release|Win32" |
||||
OutputDirectory="$(SolutionName)/$(ConfigurationName)" |
||||
IntermediateDirectory="$(OutDir)/$(ProjectName)" |
||||
ConfigurationType="1" |
||||
CharacterSet="2"> |
||||
<Tool |
||||
Name="VCCLCompilerTool" |
||||
PreprocessorDefinitions="WIN32;NDEBUG;_CONSOLE" |
||||
RuntimeLibrary="4" |
||||
UsePrecompiledHeader="3" |
||||
WarningLevel="3" |
||||
Detect64BitPortabilityProblems="FALSE" |
||||
DebugInformationFormat="3"/> |
||||
<Tool |
||||
Name="VCCustomBuildTool"/> |
||||
<Tool |
||||
Name="VCLinkerTool" |
||||
OutputFile="$(OutDir)/gtest_prod_test.exe" |
||||
LinkIncremental="1" |
||||
GenerateDebugInformation="TRUE" |
||||
SubSystem="1" |
||||
OptimizeReferences="2" |
||||
EnableCOMDATFolding="2" |
||||
TargetMachine="1"/> |
||||
<Tool |
||||
Name="VCMIDLTool"/> |
||||
<Tool |
||||
Name="VCPostBuildEventTool"/> |
||||
<Tool |
||||
Name="VCPreBuildEventTool"/> |
||||
<Tool |
||||
Name="VCPreLinkEventTool"/> |
||||
<Tool |
||||
Name="VCResourceCompilerTool"/> |
||||
<Tool |
||||
Name="VCWebServiceProxyGeneratorTool"/> |
||||
<Tool |
||||
Name="VCXMLDataGeneratorTool"/> |
||||
<Tool |
||||
Name="VCWebDeploymentTool"/> |
||||
<Tool |
||||
Name="VCManagedWrapperGeneratorTool"/> |
||||
<Tool |
||||
Name="VCAuxiliaryManagedWrapperGeneratorTool"/> |
||||
</Configuration> |
||||
</Configurations> |
||||
<References> |
||||
<ProjectReference |
||||
ReferencedProjectIdentifier="{3AF54C8A-10BF-4332-9147-F68ED9862032}" |
||||
Name="gtest_main"/> |
||||
</References> |
||||
<Files> |
||||
<Filter |
||||
Name="Source Files" |
||||
Filter="cpp;c;cxx;def;odl;idl;hpj;bat;asm;asmx" |
||||
UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}"> |
||||
<File |
||||
RelativePath="..\test\gtest_prod_test.cc"> |
||||
<FileConfiguration |
||||
Name="Debug|Win32"> |
||||
<Tool |
||||
Name="VCCLCompilerTool" |
||||
AdditionalIncludeDirectories=""..";"..\include"" |
||||
UsePrecompiledHeader="0"/> |
||||
</FileConfiguration> |
||||
<FileConfiguration |
||||
Name="Release|Win32"> |
||||
<Tool |
||||
Name="VCCLCompilerTool" |
||||
AdditionalIncludeDirectories=""..";"..\include"" |
||||
UsePrecompiledHeader="0"/> |
||||
</FileConfiguration> |
||||
</File> |
||||
<File |
||||
RelativePath="..\test\production.cc"> |
||||
<FileConfiguration |
||||
Name="Debug|Win32"> |
||||
<Tool |
||||
Name="VCCLCompilerTool" |
||||
AdditionalIncludeDirectories=""..";"..\include"" |
||||
UsePrecompiledHeader="0"/> |
||||
</FileConfiguration> |
||||
<FileConfiguration |
||||
Name="Release|Win32"> |
||||
<Tool |
||||
Name="VCCLCompilerTool" |
||||
AdditionalIncludeDirectories=""..";"..\include"" |
||||
UsePrecompiledHeader="0"/> |
||||
</FileConfiguration> |
||||
</File> |
||||
</Filter> |
||||
<Filter |
||||
Name="Header Files" |
||||
Filter="h;hpp;hxx;hm;inl;inc;xsd" |
||||
UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}"> |
||||
<File |
||||
RelativePath="..\test\production.h"> |
||||
</File> |
||||
</Filter> |
||||
</Files> |
||||
<Globals> |
||||
</Globals> |
||||
</VisualStudioProject> |
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in new issue