// Copyright 2007, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // Google Mock - a framework for writing C++ mock classes. // // This file implements the ON_CALL() and EXPECT_CALL() macros. // // A user can use the ON_CALL() macro to specify the default action of // a mock method. The syntax is: // // ON_CALL(mock_object, Method(argument-matchers)) // .With(multi-argument-matcher) // .WillByDefault(action); // // where the .With() clause is optional. // // A user can use the EXPECT_CALL() macro to specify an expectation on // a mock method. The syntax is: // // EXPECT_CALL(mock_object, Method(argument-matchers)) // .With(multi-argument-matchers) // .Times(cardinality) // .InSequence(sequences) // .After(expectations) // .WillOnce(action) // .WillRepeatedly(action) // .RetiresOnSaturation(); // // where all clauses are optional, and .InSequence()/.After()/ // .WillOnce() can appear any number of times. // IWYU pragma: private, include "gmock/gmock.h" // IWYU pragma: friend gmock/.* #ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_ #define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_ #include <cstdint> #include <functional> #include <map> #include <memory> #include <ostream> #include <set> #include <sstream> #include <string> #include <type_traits> #include <utility> #include <vector> #include "gmock/gmock-actions.h" #include "gmock/gmock-cardinalities.h" #include "gmock/gmock-matchers.h" #include "gmock/internal/gmock-internal-utils.h" #include "gmock/internal/gmock-port.h" #include "gtest/gtest.h" #if GTEST_HAS_EXCEPTIONS #include <stdexcept> // NOLINT #endif GTEST_DISABLE_MSC_WARNINGS_PUSH_(…) namespace testing { // An abstract handle of an expectation. class Expectation; // A set of expectation handles. class ExpectationSet; // Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION // and MUST NOT BE USED IN USER CODE!!! namespace internal { // Implements a mock function. template <typename F> class FunctionMocker; // Base class for expectations. class ExpectationBase; // Implements an expectation. template <typename F> class TypedExpectation; // Helper class for testing the Expectation class template. class ExpectationTester; // Helper classes for implementing NiceMock, StrictMock, and NaggyMock. template <typename MockClass> class NiceMockImpl; template <typename MockClass> class StrictMockImpl; template <typename MockClass> class NaggyMockImpl; // Protects the mock object registry (in class Mock), all function // mockers, and all expectations. // // The reason we don't use more fine-grained protection is: when a // mock function Foo() is called, it needs to consult its expectations // to see which one should be picked. If another thread is allowed to // call a mock function (either Foo() or a different one) at the same // time, it could affect the "retired" attributes of Foo()'s // expectations when InSequence() is used, and thus affect which // expectation gets picked. Therefore, we sequence all mock function // calls to ensure the integrity of the mock objects' states. GTEST_API_ GTEST_DECLARE_STATIC_MUTEX_(g_gmock_mutex); // Abstract base class of FunctionMocker. This is the // type-agnostic part of the function mocker interface. Its pure // virtual methods are implemented by FunctionMocker. class GTEST_API_ UntypedFunctionMockerBase { … }; // class UntypedFunctionMockerBase // Untyped base class for OnCallSpec<F>. class UntypedOnCallSpecBase { … }; // class UntypedOnCallSpecBase // This template class implements an ON_CALL spec. template <typename F> class OnCallSpec : public UntypedOnCallSpecBase { … }; // class OnCallSpec // Possible reactions on uninteresting calls. enum CallReaction { … }; } // namespace internal // Utilities for manipulating mock objects. class GTEST_API_ Mock { … }; // class Mock // An abstract handle of an expectation. Useful in the .After() // clause of EXPECT_CALL() for setting the (partial) order of // expectations. The syntax: // // Expectation e1 = EXPECT_CALL(...)...; // EXPECT_CALL(...).After(e1)...; // // sets two expectations where the latter can only be matched after // the former has been satisfied. // // Notes: // - This class is copyable and has value semantics. // - Constness is shallow: a const Expectation object itself cannot // be modified, but the mutable methods of the ExpectationBase // object it references can be called via expectation_base(). class GTEST_API_ Expectation { … }; // A set of expectation handles. Useful in the .After() clause of // EXPECT_CALL() for setting the (partial) order of expectations. The // syntax: // // ExpectationSet es; // es += EXPECT_CALL(...)...; // es += EXPECT_CALL(...)...; // EXPECT_CALL(...).After(es)...; // // sets three expectations where the last one can only be matched // after the first two have both been satisfied. // // This class is copyable and has value semantics. class ExpectationSet { … }; // Sequence objects are used by a user to specify the relative order // in which the expectations should match. They are copyable (we rely // on the compiler-defined copy constructor and assignment operator). class GTEST_API_ Sequence { … }; // class Sequence // An object of this type causes all EXPECT_CALL() statements // encountered in its scope to be put in an anonymous sequence. The // work is done in the constructor and destructor. You should only // create an InSequence object on the stack. // // The sole purpose for this class is to support easy definition of // sequential expectations, e.g. // // { // InSequence dummy; // The name of the object doesn't matter. // // // The following expectations must match in the order they appear. // EXPECT_CALL(a, Bar())...; // EXPECT_CALL(a, Baz())...; // ... // EXPECT_CALL(b, Xyz())...; // } // // You can create InSequence objects in multiple threads, as long as // they are used to affect different mock objects. The idea is that // each thread can create and set up its own mocks as if it's the only // thread. However, for clarity of your tests we recommend you to set // up mocks in the main thread unless you have a good reason not to do // so. class GTEST_API_ InSequence { … }; namespace internal { // Points to the implicit sequence introduced by a living InSequence // object (if any) in the current thread or NULL. GTEST_API_ extern ThreadLocal<Sequence*> g_gmock_implicit_sequence; // Base class for implementing expectations. // // There are two reasons for having a type-agnostic base class for // Expectation: // // 1. We need to store collections of expectations of different // types (e.g. all pre-requisites of a particular expectation, all // expectations in a sequence). Therefore these expectation objects // must share a common base class. // // 2. We can avoid binary code bloat by moving methods not depending // on the template argument of Expectation to the base class. // // This class is internal and mustn't be used by user code directly. class GTEST_API_ ExpectationBase { … }; // class ExpectationBase template <typename F> class TypedExpectation; // Implements an expectation for the given function type. TypedExpectation<R (Args...)>; // class TypedExpectation // A MockSpec object is used by ON_CALL() or EXPECT_CALL() for // specifying the default behavior of, or expectation on, a mock // function. // Note: class MockSpec really belongs to the ::testing namespace. // However if we define it in ::testing, MSVC will complain when // classes in ::testing::internal declare it as a friend class // template. To workaround this compiler bug, we define MockSpec in // ::testing::internal and import it into ::testing. // Logs a message including file and line number information. GTEST_API_ void LogWithLocation(testing::internal::LogSeverity severity, const char* file, int line, const std::string& message); template <typename F> class MockSpec { … }; // class MockSpec // Wrapper type for generically holding an ordinary value or lvalue reference. // If T is not a reference type, it must be copyable or movable. // ReferenceOrValueWrapper<T> is movable, and will also be copyable unless // T is a move-only value type (which means that it will always be copyable // if the current platform does not support move semantics). // // The primary template defines handling for values, but function header // comments describe the contract for the whole template (including // specializations). template <typename T> class ReferenceOrValueWrapper { … }; // Specialization for lvalue reference types. See primary template // for documentation. ReferenceOrValueWrapper<T &>; // Prints the held value as an action's result to os. template <typename T> void PrintAsActionResult(const T& result, std::ostream& os) { … } // Reports an uninteresting call (whose description is in msg) in the // manner specified by 'reaction'. GTEST_API_ void ReportUninterestingCall(CallReaction reaction, const std::string& msg); // A generic RAII type that runs a user-provided function in its destructor. class Cleanup final { … }; struct UntypedFunctionMockerBase::UninterestingCallCleanupHandler { … }; struct UntypedFunctionMockerBase::FailureCleanupHandler { … }; template <typename F> class FunctionMocker; FunctionMocker<R (Args...)>; // class FunctionMocker // Calculates the result of invoking this mock function with the given // arguments, prints it, and returns it. template <typename R, typename... Args> R FunctionMocker<R(Args...)>::InvokeWith(ArgumentTuple&& args) GTEST_LOCK_EXCLUDED_(g_gmock_mutex) { … } } // namespace internal namespace internal { template <typename F> class MockFunction; MockFunction<R (Args...)>; /* The SignatureOf<F> struct is a meta-function returning function signature corresponding to the provided F argument. It makes use of MockFunction easier by allowing it to accept more F arguments than just function signatures. Specializations provided here cover a signature type itself and any template that can be parameterized with a signature, including std::function and boost::function. */ template <typename F, typename = void> struct SignatureOf; SignatureOf<R (Args...)>; SignatureOf<C<F>, typename std::enable_if<std::is_function<F>::value>::type>; SignatureOfT; } // namespace internal // A MockFunction<F> type has one mock method whose type is // internal::SignatureOfT<F>. It is useful when you just want your // test code to emit some messages and have Google Mock verify the // right messages are sent (and perhaps at the right times). For // example, if you are exercising code: // // Foo(1); // Foo(2); // Foo(3); // // and want to verify that Foo(1) and Foo(3) both invoke // mock.Bar("a"), but Foo(2) doesn't invoke anything, you can write: // // TEST(FooTest, InvokesBarCorrectly) { // MyMock mock; // MockFunction<void(string check_point_name)> check; // { // InSequence s; // // EXPECT_CALL(mock, Bar("a")); // EXPECT_CALL(check, Call("1")); // EXPECT_CALL(check, Call("2")); // EXPECT_CALL(mock, Bar("a")); // } // Foo(1); // check.Call("1"); // Foo(2); // check.Call("2"); // Foo(3); // } // // The expectation spec says that the first Bar("a") must happen // before check point "1", the second Bar("a") must happen after check // point "2", and nothing should happen between the two check // points. The explicit check points make it easy to tell which // Bar("a") is called by which call to Foo(). // // MockFunction<F> can also be used to exercise code that accepts // std::function<internal::SignatureOfT<F>> callbacks. To do so, use // AsStdFunction() method to create std::function proxy forwarding to // original object's Call. Example: // // TEST(FooTest, RunsCallbackWithBarArgument) { // MockFunction<int(string)> callback; // EXPECT_CALL(callback, Call("bar")).WillOnce(Return(1)); // Foo(callback.AsStdFunction()); // } // // The internal::SignatureOfT<F> indirection allows to use other types // than just function signature type. This is typically useful when // providing a mock for a predefined std::function type. Example: // // using FilterPredicate = std::function<bool(string)>; // void MyFilterAlgorithm(FilterPredicate predicate); // // TEST(FooTest, FilterPredicateAlwaysAccepts) { // MockFunction<FilterPredicate> predicateMock; // EXPECT_CALL(predicateMock, Call(_)).WillRepeatedly(Return(true)); // MyFilterAlgorithm(predicateMock.AsStdFunction()); // } template <typename F> class MockFunction : public internal::MockFunction<internal::SignatureOfT<F>> { … }; // The style guide prohibits "using" statements in a namespace scope // inside a header file. However, the MockSpec class template is // meant to be defined in the ::testing namespace. The following line // is just a trick for working around a bug in MSVC 8.0, which cannot // handle it if we define MockSpec in ::testing. MockSpec; // Const(x) is a convenient function for obtaining a const reference // to x. This is useful for setting expectations on an overloaded // const mock method, e.g. // // class MockFoo : public FooInterface { // public: // MOCK_METHOD0(Bar, int()); // MOCK_CONST_METHOD0(Bar, int&()); // }; // // MockFoo foo; // // Expects a call to non-const MockFoo::Bar(). // EXPECT_CALL(foo, Bar()); // // Expects a call to const MockFoo::Bar(). // EXPECT_CALL(Const(foo), Bar()); template <typename T> inline const T& Const(const T& x) { … } // Constructs an Expectation object that references and co-owns exp. inline Expectation::Expectation(internal::ExpectationBase& exp) // NOLINT : … { … } } // namespace testing GTEST_DISABLE_MSC_WARNINGS_POP_(…) // 4251 // Implementation for ON_CALL and EXPECT_CALL macros. A separate macro is // required to avoid compile errors when the name of the method used in call is // a result of macro expansion. See CompilesWithMethodNameExpandedFromMacro // tests in internal/gmock-spec-builders_test.cc for more details. // // This macro supports statements both with and without parameter matchers. If // the parameter list is omitted, gMock will accept any parameters, which allows // tests to be written that don't need to encode the number of method // parameter. This technique may only be used for non-overloaded methods. // // // These are the same: // ON_CALL(mock, NoArgsMethod()).WillByDefault(...); // ON_CALL(mock, NoArgsMethod).WillByDefault(...); // // // As are these: // ON_CALL(mock, TwoArgsMethod(_, _)).WillByDefault(...); // ON_CALL(mock, TwoArgsMethod).WillByDefault(...); // // // Can also specify args if you want, of course: // ON_CALL(mock, TwoArgsMethod(_, 45)).WillByDefault(...); // // // Overloads work as long as you specify parameters: // ON_CALL(mock, OverloadedMethod(_)).WillByDefault(...); // ON_CALL(mock, OverloadedMethod(_, _)).WillByDefault(...); // // // Oops! Which overload did you want? // ON_CALL(mock, OverloadedMethod).WillByDefault(...); // => ERROR: call to member function 'gmock_OverloadedMethod' is ambiguous // // How this works: The mock class uses two overloads of the gmock_Method // expectation setter method plus an operator() overload on the MockSpec object. // In the matcher list form, the macro expands to: // // // This statement: // ON_CALL(mock, TwoArgsMethod(_, 45))... // // // ...expands to: // mock.gmock_TwoArgsMethod(_, 45)(WithoutMatchers(), nullptr)... // |-------------v---------------||------------v-------------| // invokes first overload swallowed by operator() // // // ...which is essentially: // mock.gmock_TwoArgsMethod(_, 45)... // // Whereas the form without a matcher list: // // // This statement: // ON_CALL(mock, TwoArgsMethod)... // // // ...expands to: // mock.gmock_TwoArgsMethod(WithoutMatchers(), nullptr)... // |-----------------------v--------------------------| // invokes second overload // // // ...which is essentially: // mock.gmock_TwoArgsMethod(_, _)... // // The WithoutMatchers() argument is used to disambiguate overloads and to // block the caller from accidentally invoking the second overload directly. The // second argument is an internal type derived from the method signature. The // failure to disambiguate two overloads of this method in the ON_CALL statement // is how we block callers from setting expectations on overloaded methods. #define GMOCK_ON_CALL_IMPL_(mock_expr, Setter, call) … #define ON_CALL(obj, call) … #define EXPECT_CALL(obj, call) … #endif // GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_