Commit e3f120b9 authored by Jesse Beder's avatar Jesse Beder
Browse files

Add gmock as dependency

parent f6a6f46b
// Copyright 2008, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Author: wan@google.com (Zhanyong Wan)
#include "gmock/gmock-generated-nice-strict.h"
#include <string>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "gtest/gtest-spi.h"
// This must not be defined inside the ::testing namespace, or it will
// clash with ::testing::Mock.
class Mock {
public:
Mock() {}
MOCK_METHOD0(DoThis, void());
private:
GTEST_DISALLOW_COPY_AND_ASSIGN_(Mock);
};
namespace testing {
namespace gmock_nice_strict_test {
using testing::internal::string;
using testing::GMOCK_FLAG(verbose);
using testing::HasSubstr;
using testing::NaggyMock;
using testing::NiceMock;
using testing::StrictMock;
#if GTEST_HAS_STREAM_REDIRECTION
using testing::internal::CaptureStdout;
using testing::internal::GetCapturedStdout;
#endif
// Defines some mock classes needed by the tests.
class Foo {
public:
virtual ~Foo() {}
virtual void DoThis() = 0;
virtual int DoThat(bool flag) = 0;
};
class MockFoo : public Foo {
public:
MockFoo() {}
void Delete() { delete this; }
MOCK_METHOD0(DoThis, void());
MOCK_METHOD1(DoThat, int(bool flag));
private:
GTEST_DISALLOW_COPY_AND_ASSIGN_(MockFoo);
};
class MockBar {
public:
explicit MockBar(const string& s) : str_(s) {}
MockBar(char a1, char a2, string a3, string a4, int a5, int a6,
const string& a7, const string& a8, bool a9, bool a10) {
str_ = string() + a1 + a2 + a3 + a4 + static_cast<char>(a5) +
static_cast<char>(a6) + a7 + a8 + (a9 ? 'T' : 'F') + (a10 ? 'T' : 'F');
}
virtual ~MockBar() {}
const string& str() const { return str_; }
MOCK_METHOD0(This, int());
MOCK_METHOD2(That, string(int, bool));
private:
string str_;
GTEST_DISALLOW_COPY_AND_ASSIGN_(MockBar);
};
#if GTEST_HAS_STREAM_REDIRECTION
// Tests that a raw mock generates warnings for uninteresting calls.
TEST(RawMockTest, WarningForUninterestingCall) {
const string saved_flag = GMOCK_FLAG(verbose);
GMOCK_FLAG(verbose) = "warning";
MockFoo raw_foo;
CaptureStdout();
raw_foo.DoThis();
raw_foo.DoThat(true);
EXPECT_THAT(GetCapturedStdout(),
HasSubstr("Uninteresting mock function call"));
GMOCK_FLAG(verbose) = saved_flag;
}
// Tests that a raw mock generates warnings for uninteresting calls
// that delete the mock object.
TEST(RawMockTest, WarningForUninterestingCallAfterDeath) {
const string saved_flag = GMOCK_FLAG(verbose);
GMOCK_FLAG(verbose) = "warning";
MockFoo* const raw_foo = new MockFoo;
ON_CALL(*raw_foo, DoThis())
.WillByDefault(Invoke(raw_foo, &MockFoo::Delete));
CaptureStdout();
raw_foo->DoThis();
EXPECT_THAT(GetCapturedStdout(),
HasSubstr("Uninteresting mock function call"));
GMOCK_FLAG(verbose) = saved_flag;
}
// Tests that a raw mock generates informational logs for
// uninteresting calls.
TEST(RawMockTest, InfoForUninterestingCall) {
MockFoo raw_foo;
const string saved_flag = GMOCK_FLAG(verbose);
GMOCK_FLAG(verbose) = "info";
CaptureStdout();
raw_foo.DoThis();
EXPECT_THAT(GetCapturedStdout(),
HasSubstr("Uninteresting mock function call"));
GMOCK_FLAG(verbose) = saved_flag;
}
// Tests that a nice mock generates no warning for uninteresting calls.
TEST(NiceMockTest, NoWarningForUninterestingCall) {
NiceMock<MockFoo> nice_foo;
CaptureStdout();
nice_foo.DoThis();
nice_foo.DoThat(true);
EXPECT_EQ("", GetCapturedStdout());
}
// Tests that a nice mock generates no warning for uninteresting calls
// that delete the mock object.
TEST(NiceMockTest, NoWarningForUninterestingCallAfterDeath) {
NiceMock<MockFoo>* const nice_foo = new NiceMock<MockFoo>;
ON_CALL(*nice_foo, DoThis())
.WillByDefault(Invoke(nice_foo, &MockFoo::Delete));
CaptureStdout();
nice_foo->DoThis();
EXPECT_EQ("", GetCapturedStdout());
}
// Tests that a nice mock generates informational logs for
// uninteresting calls.
TEST(NiceMockTest, InfoForUninterestingCall) {
NiceMock<MockFoo> nice_foo;
const string saved_flag = GMOCK_FLAG(verbose);
GMOCK_FLAG(verbose) = "info";
CaptureStdout();
nice_foo.DoThis();
EXPECT_THAT(GetCapturedStdout(),
HasSubstr("Uninteresting mock function call"));
GMOCK_FLAG(verbose) = saved_flag;
}
#endif // GTEST_HAS_STREAM_REDIRECTION
// Tests that a nice mock allows expected calls.
TEST(NiceMockTest, AllowsExpectedCall) {
NiceMock<MockFoo> nice_foo;
EXPECT_CALL(nice_foo, DoThis());
nice_foo.DoThis();
}
// Tests that an unexpected call on a nice mock fails.
TEST(NiceMockTest, UnexpectedCallFails) {
NiceMock<MockFoo> nice_foo;
EXPECT_CALL(nice_foo, DoThis()).Times(0);
EXPECT_NONFATAL_FAILURE(nice_foo.DoThis(), "called more times than expected");
}
// Tests that NiceMock works with a mock class that has a non-default
// constructor.
TEST(NiceMockTest, NonDefaultConstructor) {
NiceMock<MockBar> nice_bar("hi");
EXPECT_EQ("hi", nice_bar.str());
nice_bar.This();
nice_bar.That(5, true);
}
// Tests that NiceMock works with a mock class that has a 10-ary
// non-default constructor.
TEST(NiceMockTest, NonDefaultConstructor10) {
NiceMock<MockBar> nice_bar('a', 'b', "c", "d", 'e', 'f',
"g", "h", true, false);
EXPECT_EQ("abcdefghTF", nice_bar.str());
nice_bar.This();
nice_bar.That(5, true);
}
#if !GTEST_OS_SYMBIAN && !GTEST_OS_WINDOWS_MOBILE
// Tests that NiceMock<Mock> compiles where Mock is a user-defined
// class (as opposed to ::testing::Mock). We had to work around an
// MSVC 8.0 bug that caused the symbol Mock used in the definition of
// NiceMock to be looked up in the wrong context, and this test
// ensures that our fix works.
//
// We have to skip this test on Symbian and Windows Mobile, as it
// causes the program to crash there, for reasons unclear to us yet.
TEST(NiceMockTest, AcceptsClassNamedMock) {
NiceMock< ::Mock> nice;
EXPECT_CALL(nice, DoThis());
nice.DoThis();
}
#endif // !GTEST_OS_SYMBIAN && !GTEST_OS_WINDOWS_MOBILE
#if GTEST_HAS_STREAM_REDIRECTION
// Tests that a naggy mock generates warnings for uninteresting calls.
TEST(NaggyMockTest, WarningForUninterestingCall) {
const string saved_flag = GMOCK_FLAG(verbose);
GMOCK_FLAG(verbose) = "warning";
NaggyMock<MockFoo> naggy_foo;
CaptureStdout();
naggy_foo.DoThis();
naggy_foo.DoThat(true);
EXPECT_THAT(GetCapturedStdout(),
HasSubstr("Uninteresting mock function call"));
GMOCK_FLAG(verbose) = saved_flag;
}
// Tests that a naggy mock generates a warning for an uninteresting call
// that deletes the mock object.
TEST(NaggyMockTest, WarningForUninterestingCallAfterDeath) {
const string saved_flag = GMOCK_FLAG(verbose);
GMOCK_FLAG(verbose) = "warning";
NaggyMock<MockFoo>* const naggy_foo = new NaggyMock<MockFoo>;
ON_CALL(*naggy_foo, DoThis())
.WillByDefault(Invoke(naggy_foo, &MockFoo::Delete));
CaptureStdout();
naggy_foo->DoThis();
EXPECT_THAT(GetCapturedStdout(),
HasSubstr("Uninteresting mock function call"));
GMOCK_FLAG(verbose) = saved_flag;
}
#endif // GTEST_HAS_STREAM_REDIRECTION
// Tests that a naggy mock allows expected calls.
TEST(NaggyMockTest, AllowsExpectedCall) {
NaggyMock<MockFoo> naggy_foo;
EXPECT_CALL(naggy_foo, DoThis());
naggy_foo.DoThis();
}
// Tests that an unexpected call on a naggy mock fails.
TEST(NaggyMockTest, UnexpectedCallFails) {
NaggyMock<MockFoo> naggy_foo;
EXPECT_CALL(naggy_foo, DoThis()).Times(0);
EXPECT_NONFATAL_FAILURE(naggy_foo.DoThis(),
"called more times than expected");
}
// Tests that NaggyMock works with a mock class that has a non-default
// constructor.
TEST(NaggyMockTest, NonDefaultConstructor) {
NaggyMock<MockBar> naggy_bar("hi");
EXPECT_EQ("hi", naggy_bar.str());
naggy_bar.This();
naggy_bar.That(5, true);
}
// Tests that NaggyMock works with a mock class that has a 10-ary
// non-default constructor.
TEST(NaggyMockTest, NonDefaultConstructor10) {
NaggyMock<MockBar> naggy_bar('0', '1', "2", "3", '4', '5',
"6", "7", true, false);
EXPECT_EQ("01234567TF", naggy_bar.str());
naggy_bar.This();
naggy_bar.That(5, true);
}
#if !GTEST_OS_SYMBIAN && !GTEST_OS_WINDOWS_MOBILE
// Tests that NaggyMock<Mock> compiles where Mock is a user-defined
// class (as opposed to ::testing::Mock). We had to work around an
// MSVC 8.0 bug that caused the symbol Mock used in the definition of
// NaggyMock to be looked up in the wrong context, and this test
// ensures that our fix works.
//
// We have to skip this test on Symbian and Windows Mobile, as it
// causes the program to crash there, for reasons unclear to us yet.
TEST(NaggyMockTest, AcceptsClassNamedMock) {
NaggyMock< ::Mock> naggy;
EXPECT_CALL(naggy, DoThis());
naggy.DoThis();
}
#endif // !GTEST_OS_SYMBIAN && !GTEST_OS_WINDOWS_MOBILE
// Tests that a strict mock allows expected calls.
TEST(StrictMockTest, AllowsExpectedCall) {
StrictMock<MockFoo> strict_foo;
EXPECT_CALL(strict_foo, DoThis());
strict_foo.DoThis();
}
// Tests that an unexpected call on a strict mock fails.
TEST(StrictMockTest, UnexpectedCallFails) {
StrictMock<MockFoo> strict_foo;
EXPECT_CALL(strict_foo, DoThis()).Times(0);
EXPECT_NONFATAL_FAILURE(strict_foo.DoThis(),
"called more times than expected");
}
// Tests that an uninteresting call on a strict mock fails.
TEST(StrictMockTest, UninterestingCallFails) {
StrictMock<MockFoo> strict_foo;
EXPECT_NONFATAL_FAILURE(strict_foo.DoThis(),
"Uninteresting mock function call");
}
// Tests that an uninteresting call on a strict mock fails, even if
// the call deletes the mock object.
TEST(StrictMockTest, UninterestingCallFailsAfterDeath) {
StrictMock<MockFoo>* const strict_foo = new StrictMock<MockFoo>;
ON_CALL(*strict_foo, DoThis())
.WillByDefault(Invoke(strict_foo, &MockFoo::Delete));
EXPECT_NONFATAL_FAILURE(strict_foo->DoThis(),
"Uninteresting mock function call");
}
// Tests that StrictMock works with a mock class that has a
// non-default constructor.
TEST(StrictMockTest, NonDefaultConstructor) {
StrictMock<MockBar> strict_bar("hi");
EXPECT_EQ("hi", strict_bar.str());
EXPECT_NONFATAL_FAILURE(strict_bar.That(5, true),
"Uninteresting mock function call");
}
// Tests that StrictMock works with a mock class that has a 10-ary
// non-default constructor.
TEST(StrictMockTest, NonDefaultConstructor10) {
StrictMock<MockBar> strict_bar('a', 'b', "c", "d", 'e', 'f',
"g", "h", true, false);
EXPECT_EQ("abcdefghTF", strict_bar.str());
EXPECT_NONFATAL_FAILURE(strict_bar.That(5, true),
"Uninteresting mock function call");
}
#if !GTEST_OS_SYMBIAN && !GTEST_OS_WINDOWS_MOBILE
// Tests that StrictMock<Mock> compiles where Mock is a user-defined
// class (as opposed to ::testing::Mock). We had to work around an
// MSVC 8.0 bug that caused the symbol Mock used in the definition of
// StrictMock to be looked up in the wrong context, and this test
// ensures that our fix works.
//
// We have to skip this test on Symbian and Windows Mobile, as it
// causes the program to crash there, for reasons unclear to us yet.
TEST(StrictMockTest, AcceptsClassNamedMock) {
StrictMock< ::Mock> strict;
EXPECT_CALL(strict, DoThis());
strict.DoThis();
}
#endif // !GTEST_OS_SYMBIAN && !GTEST_OS_WINDOWS_MOBILE
} // namespace gmock_nice_strict_test
} // namespace testing
// Copyright 2008, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Author: vladl@google.com (Vlad Losev)
// Google Mock - a framework for writing C++ mock classes.
//
// This file tests the internal cross-platform support utilities.
#include "gmock/internal/gmock-port.h"
#include "gtest/gtest.h"
// NOTE: if this file is left without tests for some reason, put a dummy
// test here to make references to symbols in the gtest library and avoid
// 'undefined symbol' linker errors in gmock_main:
TEST(DummyTest, Dummy) {}
// 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.
//
// Author: wan@google.com (Zhanyong Wan)
// Google Mock - a framework for writing C++ mock classes.
//
// This file tests the spec builder syntax.
#include "gmock/gmock-spec-builders.h"
#include <ostream> // NOLINT
#include <sstream>
#include <string>
#include "gmock/gmock.h"
#include "gmock/internal/gmock-port.h"
#include "gtest/gtest.h"
#include "gtest/gtest-spi.h"
#include "gtest/internal/gtest-port.h"
namespace testing {
namespace internal {
// Helper class for testing the Expectation class template.
class ExpectationTester {
public:
// Sets the call count of the given expectation to the given number.
void SetCallCount(int n, ExpectationBase* exp) {
exp->call_count_ = n;
}
};
} // namespace internal
} // namespace testing
namespace {
using testing::_;
using testing::AnyNumber;
using testing::AtLeast;
using testing::AtMost;
using testing::Between;
using testing::Cardinality;
using testing::CardinalityInterface;
using testing::ContainsRegex;
using testing::Const;
using testing::DoAll;
using testing::DoDefault;
using testing::Eq;
using testing::Expectation;
using testing::ExpectationSet;
using testing::GMOCK_FLAG(verbose);
using testing::Gt;
using testing::InSequence;
using testing::Invoke;
using testing::InvokeWithoutArgs;
using testing::IsSubstring;
using testing::Lt;
using testing::Message;
using testing::Mock;
using testing::NaggyMock;
using testing::Ne;
using testing::Return;
using testing::Sequence;
using testing::SetArgPointee;
using testing::internal::ExpectationTester;
using testing::internal::FormatFileLocation;
using testing::internal::kErrorVerbosity;
using testing::internal::kInfoVerbosity;
using testing::internal::kWarningVerbosity;
using testing::internal::linked_ptr;
using testing::internal::string;
#if GTEST_HAS_STREAM_REDIRECTION
using testing::HasSubstr;
using testing::internal::CaptureStdout;
using testing::internal::GetCapturedStdout;
#endif
class Incomplete;
class MockIncomplete {
public:
// This line verifies that a mock method can take a by-reference
// argument of an incomplete type.
MOCK_METHOD1(ByRefFunc, void(const Incomplete& x));
};
// Tells Google Mock how to print a value of type Incomplete.
void PrintTo(const Incomplete& x, ::std::ostream* os);
TEST(MockMethodTest, CanInstantiateWithIncompleteArgType) {
// Even though this mock class contains a mock method that takes
// by-reference an argument whose type is incomplete, we can still
// use the mock, as long as Google Mock knows how to print the
// argument.
MockIncomplete incomplete;
EXPECT_CALL(incomplete, ByRefFunc(_))
.Times(AnyNumber());
}
// The definition of the printer for the argument type doesn't have to
// be visible where the mock is used.
void PrintTo(const Incomplete& /* x */, ::std::ostream* os) {
*os << "incomplete";
}
class Result {};
class MockA {
public:
MockA() {}
MOCK_METHOD1(DoA, void(int n)); // NOLINT
MOCK_METHOD1(ReturnResult, Result(int n)); // NOLINT
MOCK_METHOD2(Binary, bool(int x, int y)); // NOLINT
MOCK_METHOD2(ReturnInt, int(int x, int y)); // NOLINT
private:
GTEST_DISALLOW_COPY_AND_ASSIGN_(MockA);
};
class MockB {
public:
MockB() {}
MOCK_CONST_METHOD0(DoB, int()); // NOLINT
MOCK_METHOD1(DoB, int(int n)); // NOLINT
private:
GTEST_DISALLOW_COPY_AND_ASSIGN_(MockB);
};
class ReferenceHoldingMock {
public:
ReferenceHoldingMock() {}
MOCK_METHOD1(AcceptReference, void(linked_ptr<MockA>*));
private:
GTEST_DISALLOW_COPY_AND_ASSIGN_(ReferenceHoldingMock);
};
// Tests that EXPECT_CALL and ON_CALL compile in a presence of macro
// redefining a mock method name. This could happen, for example, when
// the tested code #includes Win32 API headers which define many APIs
// as macros, e.g. #define TextOut TextOutW.
#define Method MethodW
class CC {
public:
virtual ~CC() {}
virtual int Method() = 0;
};
class MockCC : public CC {
public:
MockCC() {}
MOCK_METHOD0(Method, int());
private:
GTEST_DISALLOW_COPY_AND_ASSIGN_(MockCC);
};
// Tests that a method with expanded name compiles.
TEST(OnCallSyntaxTest, CompilesWithMethodNameExpandedFromMacro) {
MockCC cc;
ON_CALL(cc, Method());
}
// Tests that the method with expanded name not only compiles but runs
// and returns a correct value, too.
TEST(OnCallSyntaxTest, WorksWithMethodNameExpandedFromMacro) {
MockCC cc;
ON_CALL(cc, Method()).WillByDefault(Return(42));
EXPECT_EQ(42, cc.Method());
}
// Tests that a method with expanded name compiles.
TEST(ExpectCallSyntaxTest, CompilesWithMethodNameExpandedFromMacro) {
MockCC cc;
EXPECT_CALL(cc, Method());
cc.Method();
}
// Tests that it works, too.
TEST(ExpectCallSyntaxTest, WorksWithMethodNameExpandedFromMacro) {
MockCC cc;
EXPECT_CALL(cc, Method()).WillOnce(Return(42));
EXPECT_EQ(42, cc.Method());
}
#undef Method // Done with macro redefinition tests.
// Tests that ON_CALL evaluates its arguments exactly once as promised
// by Google Mock.
TEST(OnCallSyntaxTest, EvaluatesFirstArgumentOnce) {
MockA a;
MockA* pa = &a;
ON_CALL(*pa++, DoA(_));
EXPECT_EQ(&a + 1, pa);
}
TEST(OnCallSyntaxTest, EvaluatesSecondArgumentOnce) {
MockA a;
int n = 0;
ON_CALL(a, DoA(n++));
EXPECT_EQ(1, n);
}
// Tests that the syntax of ON_CALL() is enforced at run time.
TEST(OnCallSyntaxTest, WithIsOptional) {
MockA a;
ON_CALL(a, DoA(5))
.WillByDefault(Return());
ON_CALL(a, DoA(_))
.With(_)
.WillByDefault(Return());
}
TEST(OnCallSyntaxTest, WithCanAppearAtMostOnce) {
MockA a;
EXPECT_NONFATAL_FAILURE({ // NOLINT
ON_CALL(a, ReturnResult(_))
.With(_)
.With(_)
.WillByDefault(Return(Result()));
}, ".With() cannot appear more than once in an ON_CALL()");
}
TEST(OnCallSyntaxTest, WillByDefaultIsMandatory) {
MockA a;
EXPECT_DEATH_IF_SUPPORTED({
ON_CALL(a, DoA(5));
a.DoA(5);
}, "");
}
TEST(OnCallSyntaxTest, WillByDefaultCanAppearAtMostOnce) {
MockA a;
EXPECT_NONFATAL_FAILURE({ // NOLINT
ON_CALL(a, DoA(5))
.WillByDefault(Return())
.WillByDefault(Return());
}, ".WillByDefault() must appear exactly once in an ON_CALL()");
}
// Tests that EXPECT_CALL evaluates its arguments exactly once as
// promised by Google Mock.
TEST(ExpectCallSyntaxTest, EvaluatesFirstArgumentOnce) {
MockA a;
MockA* pa = &a;
EXPECT_CALL(*pa++, DoA(_));
a.DoA(0);
EXPECT_EQ(&a + 1, pa);
}
TEST(ExpectCallSyntaxTest, EvaluatesSecondArgumentOnce) {
MockA a;
int n = 0;
EXPECT_CALL(a, DoA(n++));
a.DoA(0);
EXPECT_EQ(1, n);
}
// Tests that the syntax of EXPECT_CALL() is enforced at run time.
TEST(ExpectCallSyntaxTest, WithIsOptional) {
MockA a;
EXPECT_CALL(a, DoA(5))
.Times(0);
EXPECT_CALL(a, DoA(6))
.With(_)
.Times(0);
}
TEST(ExpectCallSyntaxTest, WithCanAppearAtMostOnce) {
MockA a;
EXPECT_NONFATAL_FAILURE({ // NOLINT
EXPECT_CALL(a, DoA(6))
.With(_)
.With(_);
}, ".With() cannot appear more than once in an EXPECT_CALL()");
a.DoA(6);
}
TEST(ExpectCallSyntaxTest, WithMustBeFirstClause) {
MockA a;
EXPECT_NONFATAL_FAILURE({ // NOLINT
EXPECT_CALL(a, DoA(1))
.Times(1)
.With(_);
}, ".With() must be the first clause in an EXPECT_CALL()");
a.DoA(1);
EXPECT_NONFATAL_FAILURE({ // NOLINT
EXPECT_CALL(a, DoA(2))
.WillOnce(Return())
.With(_);
}, ".With() must be the first clause in an EXPECT_CALL()");
a.DoA(2);
}
TEST(ExpectCallSyntaxTest, TimesCanBeInferred) {
MockA a;
EXPECT_CALL(a, DoA(1))
.WillOnce(Return());
EXPECT_CALL(a, DoA(2))
.WillOnce(Return())
.WillRepeatedly(Return());
a.DoA(1);
a.DoA(2);
a.DoA(2);
}
TEST(ExpectCallSyntaxTest, TimesCanAppearAtMostOnce) {
MockA a;
EXPECT_NONFATAL_FAILURE({ // NOLINT
EXPECT_CALL(a, DoA(1))
.Times(1)
.Times(2);
}, ".Times() cannot appear more than once in an EXPECT_CALL()");
a.DoA(1);
a.DoA(1);
}
TEST(ExpectCallSyntaxTest, TimesMustBeBeforeInSequence) {
MockA a;
Sequence s;
EXPECT_NONFATAL_FAILURE({ // NOLINT
EXPECT_CALL(a, DoA(1))
.InSequence(s)
.Times(1);
}, ".Times() cannot appear after ");
a.DoA(1);
}
TEST(ExpectCallSyntaxTest, InSequenceIsOptional) {
MockA a;
Sequence s;
EXPECT_CALL(a, DoA(1));
EXPECT_CALL(a, DoA(2))
.InSequence(s);
a.DoA(1);
a.DoA(2);
}
TEST(ExpectCallSyntaxTest, InSequenceCanAppearMultipleTimes) {
MockA a;
Sequence s1, s2;
EXPECT_CALL(a, DoA(1))
.InSequence(s1, s2)
.InSequence(s1);
a.DoA(1);
}
TEST(ExpectCallSyntaxTest, InSequenceMustBeBeforeAfter) {
MockA a;
Sequence s;
Expectation e = EXPECT_CALL(a, DoA(1))
.Times(AnyNumber());
EXPECT_NONFATAL_FAILURE({ // NOLINT
EXPECT_CALL(a, DoA(2))
.After(e)
.InSequence(s);
}, ".InSequence() cannot appear after ");
a.DoA(2);
}
TEST(ExpectCallSyntaxTest, InSequenceMustBeBeforeWillOnce) {
MockA a;
Sequence s;
EXPECT_NONFATAL_FAILURE({ // NOLINT
EXPECT_CALL(a, DoA(1))
.WillOnce(Return())
.InSequence(s);
}, ".InSequence() cannot appear after ");
a.DoA(1);
}
TEST(ExpectCallSyntaxTest, AfterMustBeBeforeWillOnce) {
MockA a;
Expectation e = EXPECT_CALL(a, DoA(1));
EXPECT_NONFATAL_FAILURE({
EXPECT_CALL(a, DoA(2))
.WillOnce(Return())
.After(e);
}, ".After() cannot appear after ");
a.DoA(1);
a.DoA(2);
}
TEST(ExpectCallSyntaxTest, WillIsOptional) {
MockA a;
EXPECT_CALL(a, DoA(1));
EXPECT_CALL(a, DoA(2))
.WillOnce(Return());
a.DoA(1);
a.DoA(2);
}
TEST(ExpectCallSyntaxTest, WillCanAppearMultipleTimes) {
MockA a;
EXPECT_CALL(a, DoA(1))
.Times(AnyNumber())
.WillOnce(Return())
.WillOnce(Return())
.WillOnce(Return());
}
TEST(ExpectCallSyntaxTest, WillMustBeBeforeWillRepeatedly) {
MockA a;
EXPECT_NONFATAL_FAILURE({ // NOLINT
EXPECT_CALL(a, DoA(1))
.WillRepeatedly(Return())
.WillOnce(Return());
}, ".WillOnce() cannot appear after ");
a.DoA(1);
}
TEST(ExpectCallSyntaxTest, WillRepeatedlyIsOptional) {
MockA a;
EXPECT_CALL(a, DoA(1))
.WillOnce(Return());
EXPECT_CALL(a, DoA(2))
.WillOnce(Return())
.WillRepeatedly(Return());
a.DoA(1);
a.DoA(2);
a.DoA(2);
}
TEST(ExpectCallSyntaxTest, WillRepeatedlyCannotAppearMultipleTimes) {
MockA a;
EXPECT_NONFATAL_FAILURE({ // NOLINT
EXPECT_CALL(a, DoA(1))
.WillRepeatedly(Return())
.WillRepeatedly(Return());
}, ".WillRepeatedly() cannot appear more than once in an "
"EXPECT_CALL()");
}
TEST(ExpectCallSyntaxTest, WillRepeatedlyMustBeBeforeRetiresOnSaturation) {
MockA a;
EXPECT_NONFATAL_FAILURE({ // NOLINT
EXPECT_CALL(a, DoA(1))
.RetiresOnSaturation()
.WillRepeatedly(Return());
}, ".WillRepeatedly() cannot appear after ");
}
TEST(ExpectCallSyntaxTest, RetiresOnSaturationIsOptional) {
MockA a;
EXPECT_CALL(a, DoA(1));
EXPECT_CALL(a, DoA(1))
.RetiresOnSaturation();
a.DoA(1);
a.DoA(1);
}
TEST(ExpectCallSyntaxTest, RetiresOnSaturationCannotAppearMultipleTimes) {
MockA a;
EXPECT_NONFATAL_FAILURE({ // NOLINT
EXPECT_CALL(a, DoA(1))
.RetiresOnSaturation()
.RetiresOnSaturation();
}, ".RetiresOnSaturation() cannot appear more than once");
a.DoA(1);
}
TEST(ExpectCallSyntaxTest, DefaultCardinalityIsOnce) {
{
MockA a;
EXPECT_CALL(a, DoA(1));
a.DoA(1);
}
EXPECT_NONFATAL_FAILURE({ // NOLINT
MockA a;
EXPECT_CALL(a, DoA(1));
}, "to be called once");
EXPECT_NONFATAL_FAILURE({ // NOLINT
MockA a;
EXPECT_CALL(a, DoA(1));
a.DoA(1);
a.DoA(1);
}, "to be called once");
}
#if GTEST_HAS_STREAM_REDIRECTION
// Tests that Google Mock doesn't print a warning when the number of
// WillOnce() is adequate.
TEST(ExpectCallSyntaxTest, DoesNotWarnOnAdequateActionCount) {
CaptureStdout();
{
MockB b;
// It's always fine to omit WillOnce() entirely.
EXPECT_CALL(b, DoB())
.Times(0);
EXPECT_CALL(b, DoB(1))
.Times(AtMost(1));
EXPECT_CALL(b, DoB(2))
.Times(1)
.WillRepeatedly(Return(1));
// It's fine for the number of WillOnce()s to equal the upper bound.
EXPECT_CALL(b, DoB(3))
.Times(Between(1, 2))
.WillOnce(Return(1))
.WillOnce(Return(2));
// It's fine for the number of WillOnce()s to be smaller than the
// upper bound when there is a WillRepeatedly().
EXPECT_CALL(b, DoB(4))
.Times(AtMost(3))
.WillOnce(Return(1))
.WillRepeatedly(Return(2));
// Satisfies the above expectations.
b.DoB(2);
b.DoB(3);
}
EXPECT_STREQ("", GetCapturedStdout().c_str());
}
// Tests that Google Mock warns on having too many actions in an
// expectation compared to its cardinality.
TEST(ExpectCallSyntaxTest, WarnsOnTooManyActions) {
CaptureStdout();
{
MockB b;
// Warns when the number of WillOnce()s is larger than the upper bound.
EXPECT_CALL(b, DoB())
.Times(0)
.WillOnce(Return(1)); // #1
EXPECT_CALL(b, DoB())
.Times(AtMost(1))
.WillOnce(Return(1))
.WillOnce(Return(2)); // #2
EXPECT_CALL(b, DoB(1))
.Times(1)
.WillOnce(Return(1))
.WillOnce(Return(2))
.RetiresOnSaturation(); // #3
// Warns when the number of WillOnce()s equals the upper bound and
// there is a WillRepeatedly().
EXPECT_CALL(b, DoB())
.Times(0)
.WillRepeatedly(Return(1)); // #4
EXPECT_CALL(b, DoB(2))
.Times(1)
.WillOnce(Return(1))
.WillRepeatedly(Return(2)); // #5
// Satisfies the above expectations.
b.DoB(1);
b.DoB(2);
}
const std::string output = GetCapturedStdout();
EXPECT_PRED_FORMAT2(
IsSubstring,
"Too many actions specified in EXPECT_CALL(b, DoB())...\n"
"Expected to be never called, but has 1 WillOnce().",
output); // #1
EXPECT_PRED_FORMAT2(
IsSubstring,
"Too many actions specified in EXPECT_CALL(b, DoB())...\n"
"Expected to be called at most once, "
"but has 2 WillOnce()s.",
output); // #2
EXPECT_PRED_FORMAT2(
IsSubstring,
"Too many actions specified in EXPECT_CALL(b, DoB(1))...\n"
"Expected to be called once, but has 2 WillOnce()s.",
output); // #3
EXPECT_PRED_FORMAT2(
IsSubstring,
"Too many actions specified in EXPECT_CALL(b, DoB())...\n"
"Expected to be never called, but has 0 WillOnce()s "
"and a WillRepeatedly().",
output); // #4
EXPECT_PRED_FORMAT2(
IsSubstring,
"Too many actions specified in EXPECT_CALL(b, DoB(2))...\n"
"Expected to be called once, but has 1 WillOnce() "
"and a WillRepeatedly().",
output); // #5
}
// Tests that Google Mock warns on having too few actions in an
// expectation compared to its cardinality.
TEST(ExpectCallSyntaxTest, WarnsOnTooFewActions) {
MockB b;
EXPECT_CALL(b, DoB())
.Times(Between(2, 3))
.WillOnce(Return(1));
CaptureStdout();
b.DoB();
const std::string output = GetCapturedStdout();
EXPECT_PRED_FORMAT2(
IsSubstring,
"Too few actions specified in EXPECT_CALL(b, DoB())...\n"
"Expected to be called between 2 and 3 times, "
"but has only 1 WillOnce().",
output);
b.DoB();
}
#endif // GTEST_HAS_STREAM_REDIRECTION
// Tests the semantics of ON_CALL().
// Tests that the built-in default action is taken when no ON_CALL()
// is specified.
TEST(OnCallTest, TakesBuiltInDefaultActionWhenNoOnCall) {
MockB b;
EXPECT_CALL(b, DoB());
EXPECT_EQ(0, b.DoB());
}
// Tests that the built-in default action is taken when no ON_CALL()
// matches the invocation.
TEST(OnCallTest, TakesBuiltInDefaultActionWhenNoOnCallMatches) {
MockB b;
ON_CALL(b, DoB(1))
.WillByDefault(Return(1));
EXPECT_CALL(b, DoB(_));
EXPECT_EQ(0, b.DoB(2));
}
// Tests that the last matching ON_CALL() action is taken.
TEST(OnCallTest, PicksLastMatchingOnCall) {
MockB b;
ON_CALL(b, DoB(_))
.WillByDefault(Return(3));
ON_CALL(b, DoB(2))
.WillByDefault(Return(2));
ON_CALL(b, DoB(1))
.WillByDefault(Return(1));
EXPECT_CALL(b, DoB(_));
EXPECT_EQ(2, b.DoB(2));
}
// Tests the semantics of EXPECT_CALL().
// Tests that any call is allowed when no EXPECT_CALL() is specified.
TEST(ExpectCallTest, AllowsAnyCallWhenNoSpec) {
MockB b;
EXPECT_CALL(b, DoB());
// There is no expectation on DoB(int).
b.DoB();
// DoB(int) can be called any number of times.
b.DoB(1);
b.DoB(2);
}
// Tests that the last matching EXPECT_CALL() fires.
TEST(ExpectCallTest, PicksLastMatchingExpectCall) {
MockB b;
EXPECT_CALL(b, DoB(_))
.WillRepeatedly(Return(2));
EXPECT_CALL(b, DoB(1))
.WillRepeatedly(Return(1));
EXPECT_EQ(1, b.DoB(1));
}
// Tests lower-bound violation.
TEST(ExpectCallTest, CatchesTooFewCalls) {
EXPECT_NONFATAL_FAILURE({ // NOLINT
MockB b;
EXPECT_CALL(b, DoB(5))
.Times(AtLeast(2));
b.DoB(5);
}, "Actual function call count doesn't match EXPECT_CALL(b, DoB(5))...\n"
" Expected: to be called at least twice\n"
" Actual: called once - unsatisfied and active");
}
// Tests that the cardinality can be inferred when no Times(...) is
// specified.
TEST(ExpectCallTest, InfersCardinalityWhenThereIsNoWillRepeatedly) {
{
MockB b;
EXPECT_CALL(b, DoB())
.WillOnce(Return(1))
.WillOnce(Return(2));
EXPECT_EQ(1, b.DoB());
EXPECT_EQ(2, b.DoB());
}
EXPECT_NONFATAL_FAILURE({ // NOLINT
MockB b;
EXPECT_CALL(b, DoB())
.WillOnce(Return(1))
.WillOnce(Return(2));
EXPECT_EQ(1, b.DoB());
}, "to be called twice");
{ // NOLINT
MockB b;
EXPECT_CALL(b, DoB())
.WillOnce(Return(1))
.WillOnce(Return(2));
EXPECT_EQ(1, b.DoB());
EXPECT_EQ(2, b.DoB());
EXPECT_NONFATAL_FAILURE(b.DoB(), "to be called twice");
}
}
TEST(ExpectCallTest, InfersCardinality1WhenThereIsWillRepeatedly) {
{
MockB b;
EXPECT_CALL(b, DoB())
.WillOnce(Return(1))
.WillRepeatedly(Return(2));
EXPECT_EQ(1, b.DoB());
}
{ // NOLINT
MockB b;
EXPECT_CALL(b, DoB())
.WillOnce(Return(1))
.WillRepeatedly(Return(2));
EXPECT_EQ(1, b.DoB());
EXPECT_EQ(2, b.DoB());
EXPECT_EQ(2, b.DoB());
}
EXPECT_NONFATAL_FAILURE({ // NOLINT
MockB b;
EXPECT_CALL(b, DoB())
.WillOnce(Return(1))
.WillRepeatedly(Return(2));
}, "to be called at least once");
}
// Tests that the n-th action is taken for the n-th matching
// invocation.
TEST(ExpectCallTest, NthMatchTakesNthAction) {
MockB b;
EXPECT_CALL(b, DoB())
.WillOnce(Return(1))
.WillOnce(Return(2))
.WillOnce(Return(3));
EXPECT_EQ(1, b.DoB());
EXPECT_EQ(2, b.DoB());
EXPECT_EQ(3, b.DoB());
}
// Tests that the WillRepeatedly() action is taken when the WillOnce(...)
// list is exhausted.
TEST(ExpectCallTest, TakesRepeatedActionWhenWillListIsExhausted) {
MockB b;
EXPECT_CALL(b, DoB())
.WillOnce(Return(1))
.WillRepeatedly(Return(2));
EXPECT_EQ(1, b.DoB());
EXPECT_EQ(2, b.DoB());
EXPECT_EQ(2, b.DoB());
}
#if GTEST_HAS_STREAM_REDIRECTION
// Tests that the default action is taken when the WillOnce(...) list is
// exhausted and there is no WillRepeatedly().
TEST(ExpectCallTest, TakesDefaultActionWhenWillListIsExhausted) {
MockB b;
EXPECT_CALL(b, DoB(_))
.Times(1);
EXPECT_CALL(b, DoB())
.Times(AnyNumber())
.WillOnce(Return(1))
.WillOnce(Return(2));
CaptureStdout();
EXPECT_EQ(0, b.DoB(1)); // Shouldn't generate a warning as the
// expectation has no action clause at all.
EXPECT_EQ(1, b.DoB());
EXPECT_EQ(2, b.DoB());
const std::string output1 = GetCapturedStdout();
EXPECT_STREQ("", output1.c_str());
CaptureStdout();
EXPECT_EQ(0, b.DoB());
EXPECT_EQ(0, b.DoB());
const std::string output2 = GetCapturedStdout();
EXPECT_THAT(output2.c_str(),
HasSubstr("Actions ran out in EXPECT_CALL(b, DoB())...\n"
"Called 3 times, but only 2 WillOnce()s are specified"
" - returning default value."));
EXPECT_THAT(output2.c_str(),
HasSubstr("Actions ran out in EXPECT_CALL(b, DoB())...\n"
"Called 4 times, but only 2 WillOnce()s are specified"
" - returning default value."));
}
TEST(FunctionMockerMessageTest, ReportsExpectCallLocationForExhausedActions) {
MockB b;
std::string expect_call_location = FormatFileLocation(__FILE__, __LINE__ + 1);
EXPECT_CALL(b, DoB()).Times(AnyNumber()).WillOnce(Return(1));
EXPECT_EQ(1, b.DoB());
CaptureStdout();
EXPECT_EQ(0, b.DoB());
const std::string output = GetCapturedStdout();
// The warning message should contain the call location.
EXPECT_PRED_FORMAT2(IsSubstring, expect_call_location, output);
}
TEST(FunctionMockerMessageTest,
ReportsDefaultActionLocationOfUninterestingCallsForNaggyMock) {
std::string on_call_location;
CaptureStdout();
{
NaggyMock<MockB> b;
on_call_location = FormatFileLocation(__FILE__, __LINE__ + 1);
ON_CALL(b, DoB(_)).WillByDefault(Return(0));
b.DoB(0);
}
EXPECT_PRED_FORMAT2(IsSubstring, on_call_location, GetCapturedStdout());
}
#endif // GTEST_HAS_STREAM_REDIRECTION
// Tests that an uninteresting call performs the default action.
TEST(UninterestingCallTest, DoesDefaultAction) {
// When there is an ON_CALL() statement, the action specified by it
// should be taken.
MockA a;
ON_CALL(a, Binary(_, _))
.WillByDefault(Return(true));
EXPECT_TRUE(a.Binary(1, 2));
// When there is no ON_CALL(), the default value for the return type
// should be returned.
MockB b;
EXPECT_EQ(0, b.DoB());
}
// Tests that an unexpected call performs the default action.
TEST(UnexpectedCallTest, DoesDefaultAction) {
// When there is an ON_CALL() statement, the action specified by it
// should be taken.
MockA a;
ON_CALL(a, Binary(_, _))
.WillByDefault(Return(true));
EXPECT_CALL(a, Binary(0, 0));
a.Binary(0, 0);
bool result = false;
EXPECT_NONFATAL_FAILURE(result = a.Binary(1, 2),
"Unexpected mock function call");
EXPECT_TRUE(result);
// When there is no ON_CALL(), the default value for the return type
// should be returned.
MockB b;
EXPECT_CALL(b, DoB(0))
.Times(0);
int n = -1;
EXPECT_NONFATAL_FAILURE(n = b.DoB(1),
"Unexpected mock function call");
EXPECT_EQ(0, n);
}
// Tests that when an unexpected void function generates the right
// failure message.
TEST(UnexpectedCallTest, GeneratesFailureForVoidFunction) {
// First, tests the message when there is only one EXPECT_CALL().
MockA a1;
EXPECT_CALL(a1, DoA(1));
a1.DoA(1);
// Ideally we should match the failure message against a regex, but
// EXPECT_NONFATAL_FAILURE doesn't support that, so we test for
// multiple sub-strings instead.
EXPECT_NONFATAL_FAILURE(
a1.DoA(9),
"Unexpected mock function call - returning directly.\n"
" Function call: DoA(9)\n"
"Google Mock tried the following 1 expectation, but it didn't match:");
EXPECT_NONFATAL_FAILURE(
a1.DoA(9),
" Expected arg #0: is equal to 1\n"
" Actual: 9\n"
" Expected: to be called once\n"
" Actual: called once - saturated and active");
// Next, tests the message when there are more than one EXPECT_CALL().
MockA a2;
EXPECT_CALL(a2, DoA(1));
EXPECT_CALL(a2, DoA(3));
a2.DoA(1);
EXPECT_NONFATAL_FAILURE(
a2.DoA(2),
"Unexpected mock function call - returning directly.\n"
" Function call: DoA(2)\n"
"Google Mock tried the following 2 expectations, but none matched:");
EXPECT_NONFATAL_FAILURE(
a2.DoA(2),
"tried expectation #0: EXPECT_CALL(a2, DoA(1))...\n"
" Expected arg #0: is equal to 1\n"
" Actual: 2\n"
" Expected: to be called once\n"
" Actual: called once - saturated and active");
EXPECT_NONFATAL_FAILURE(
a2.DoA(2),
"tried expectation #1: EXPECT_CALL(a2, DoA(3))...\n"
" Expected arg #0: is equal to 3\n"
" Actual: 2\n"
" Expected: to be called once\n"
" Actual: never called - unsatisfied and active");
a2.DoA(3);
}
// Tests that an unexpected non-void function generates the right
// failure message.
TEST(UnexpectedCallTest, GeneartesFailureForNonVoidFunction) {
MockB b1;
EXPECT_CALL(b1, DoB(1));
b1.DoB(1);
EXPECT_NONFATAL_FAILURE(
b1.DoB(2),
"Unexpected mock function call - returning default value.\n"
" Function call: DoB(2)\n"
" Returns: 0\n"
"Google Mock tried the following 1 expectation, but it didn't match:");
EXPECT_NONFATAL_FAILURE(
b1.DoB(2),
" Expected arg #0: is equal to 1\n"
" Actual: 2\n"
" Expected: to be called once\n"
" Actual: called once - saturated and active");
}
// Tests that Google Mock explains that an retired expectation doesn't
// match the call.
TEST(UnexpectedCallTest, RetiredExpectation) {
MockB b;
EXPECT_CALL(b, DoB(1))
.RetiresOnSaturation();
b.DoB(1);
EXPECT_NONFATAL_FAILURE(
b.DoB(1),
" Expected: the expectation is active\n"
" Actual: it is retired");
}
// Tests that Google Mock explains that an expectation that doesn't
// match the arguments doesn't match the call.
TEST(UnexpectedCallTest, UnmatchedArguments) {
MockB b;
EXPECT_CALL(b, DoB(1));
EXPECT_NONFATAL_FAILURE(
b.DoB(2),
" Expected arg #0: is equal to 1\n"
" Actual: 2\n");
b.DoB(1);
}
// Tests that Google Mock explains that an expectation with
// unsatisfied pre-requisites doesn't match the call.
TEST(UnexpectedCallTest, UnsatisifiedPrerequisites) {
Sequence s1, s2;
MockB b;
EXPECT_CALL(b, DoB(1))
.InSequence(s1);
EXPECT_CALL(b, DoB(2))
.Times(AnyNumber())
.InSequence(s1);
EXPECT_CALL(b, DoB(3))
.InSequence(s2);
EXPECT_CALL(b, DoB(4))
.InSequence(s1, s2);
::testing::TestPartResultArray failures;
{
::testing::ScopedFakeTestPartResultReporter reporter(&failures);
b.DoB(4);
// Now 'failures' contains the Google Test failures generated by
// the above statement.
}
// There should be one non-fatal failure.
ASSERT_EQ(1, failures.size());
const ::testing::TestPartResult& r = failures.GetTestPartResult(0);
EXPECT_EQ(::testing::TestPartResult::kNonFatalFailure, r.type());
// Verifies that the failure message contains the two unsatisfied
// pre-requisites but not the satisfied one.
#if GTEST_USES_PCRE
EXPECT_THAT(r.message(), ContainsRegex(
// PCRE has trouble using (.|\n) to match any character, but
// supports the (?s) prefix for using . to match any character.
"(?s)the following immediate pre-requisites are not satisfied:\n"
".*: pre-requisite #0\n"
".*: pre-requisite #1"));
#elif GTEST_USES_POSIX_RE
EXPECT_THAT(r.message(), ContainsRegex(
// POSIX RE doesn't understand the (?s) prefix, but has no trouble
// with (.|\n).
"the following immediate pre-requisites are not satisfied:\n"
"(.|\n)*: pre-requisite #0\n"
"(.|\n)*: pre-requisite #1"));
#else
// We can only use Google Test's own simple regex.
EXPECT_THAT(r.message(), ContainsRegex(
"the following immediate pre-requisites are not satisfied:"));
EXPECT_THAT(r.message(), ContainsRegex(": pre-requisite #0"));
EXPECT_THAT(r.message(), ContainsRegex(": pre-requisite #1"));
#endif // GTEST_USES_PCRE
b.DoB(1);
b.DoB(3);
b.DoB(4);
}
TEST(UndefinedReturnValueTest, ReturnValueIsMandatory) {
MockA a;
// TODO(wan@google.com): We should really verify the output message,
// but we cannot yet due to that EXPECT_DEATH only captures stderr
// while Google Mock logs to stdout.
#if GTEST_HAS_EXCEPTIONS
EXPECT_ANY_THROW(a.ReturnResult(1));
#else
EXPECT_DEATH_IF_SUPPORTED(a.ReturnResult(1), "");
#endif
}
// Tests that an excessive call (one whose arguments match the
// matchers but is called too many times) performs the default action.
TEST(ExcessiveCallTest, DoesDefaultAction) {
// When there is an ON_CALL() statement, the action specified by it
// should be taken.
MockA a;
ON_CALL(a, Binary(_, _))
.WillByDefault(Return(true));
EXPECT_CALL(a, Binary(0, 0));
a.Binary(0, 0);
bool result = false;
EXPECT_NONFATAL_FAILURE(result = a.Binary(0, 0),
"Mock function called more times than expected");
EXPECT_TRUE(result);
// When there is no ON_CALL(), the default value for the return type
// should be returned.
MockB b;
EXPECT_CALL(b, DoB(0))
.Times(0);
int n = -1;
EXPECT_NONFATAL_FAILURE(n = b.DoB(0),
"Mock function called more times than expected");
EXPECT_EQ(0, n);
}
// Tests that when a void function is called too many times,
// the failure message contains the argument values.
TEST(ExcessiveCallTest, GeneratesFailureForVoidFunction) {
MockA a;
EXPECT_CALL(a, DoA(_))
.Times(0);
EXPECT_NONFATAL_FAILURE(
a.DoA(9),
"Mock function called more times than expected - returning directly.\n"
" Function call: DoA(9)\n"
" Expected: to be never called\n"
" Actual: called once - over-saturated and active");
}
// Tests that when a non-void function is called too many times, the
// failure message contains the argument values and the return value.
TEST(ExcessiveCallTest, GeneratesFailureForNonVoidFunction) {
MockB b;
EXPECT_CALL(b, DoB(_));
b.DoB(1);
EXPECT_NONFATAL_FAILURE(
b.DoB(2),
"Mock function called more times than expected - "
"returning default value.\n"
" Function call: DoB(2)\n"
" Returns: 0\n"
" Expected: to be called once\n"
" Actual: called twice - over-saturated and active");
}
// Tests using sequences.
TEST(InSequenceTest, AllExpectationInScopeAreInSequence) {
MockA a;
{
InSequence dummy;
EXPECT_CALL(a, DoA(1));
EXPECT_CALL(a, DoA(2));
}
EXPECT_NONFATAL_FAILURE({ // NOLINT
a.DoA(2);
}, "Unexpected mock function call");
a.DoA(1);
a.DoA(2);
}
TEST(InSequenceTest, NestedInSequence) {
MockA a;
{
InSequence dummy;
EXPECT_CALL(a, DoA(1));
{
InSequence dummy2;
EXPECT_CALL(a, DoA(2));
EXPECT_CALL(a, DoA(3));
}
}
EXPECT_NONFATAL_FAILURE({ // NOLINT
a.DoA(1);
a.DoA(3);
}, "Unexpected mock function call");
a.DoA(2);
a.DoA(3);
}
TEST(InSequenceTest, ExpectationsOutOfScopeAreNotAffected) {
MockA a;
{
InSequence dummy;
EXPECT_CALL(a, DoA(1));
EXPECT_CALL(a, DoA(2));
}
EXPECT_CALL(a, DoA(3));
EXPECT_NONFATAL_FAILURE({ // NOLINT
a.DoA(2);
}, "Unexpected mock function call");
a.DoA(3);
a.DoA(1);
a.DoA(2);
}
// Tests that any order is allowed when no sequence is used.
TEST(SequenceTest, AnyOrderIsOkByDefault) {
{
MockA a;
MockB b;
EXPECT_CALL(a, DoA(1));
EXPECT_CALL(b, DoB())
.Times(AnyNumber());
a.DoA(1);
b.DoB();
}
{ // NOLINT
MockA a;
MockB b;
EXPECT_CALL(a, DoA(1));
EXPECT_CALL(b, DoB())
.Times(AnyNumber());
b.DoB();
a.DoA(1);
}
}
// Tests that the calls must be in strict order when a complete order
// is specified.
TEST(SequenceTest, CallsMustBeInStrictOrderWhenSaidSo1) {
MockA a;
ON_CALL(a, ReturnResult(_))
.WillByDefault(Return(Result()));
Sequence s;
EXPECT_CALL(a, ReturnResult(1))
.InSequence(s);
EXPECT_CALL(a, ReturnResult(2))
.InSequence(s);
EXPECT_CALL(a, ReturnResult(3))
.InSequence(s);
a.ReturnResult(1);
// May only be called after a.ReturnResult(2).
EXPECT_NONFATAL_FAILURE(a.ReturnResult(3), "Unexpected mock function call");
a.ReturnResult(2);
a.ReturnResult(3);
}
// Tests that the calls must be in strict order when a complete order
// is specified.
TEST(SequenceTest, CallsMustBeInStrictOrderWhenSaidSo2) {
MockA a;
ON_CALL(a, ReturnResult(_))
.WillByDefault(Return(Result()));
Sequence s;
EXPECT_CALL(a, ReturnResult(1))
.InSequence(s);
EXPECT_CALL(a, ReturnResult(2))
.InSequence(s);
// May only be called after a.ReturnResult(1).
EXPECT_NONFATAL_FAILURE(a.ReturnResult(2), "Unexpected mock function call");
a.ReturnResult(1);
a.ReturnResult(2);
}
// Tests specifying a DAG using multiple sequences.
class PartialOrderTest : public testing::Test {
protected:
PartialOrderTest() {
ON_CALL(a_, ReturnResult(_))
.WillByDefault(Return(Result()));
// Specifies this partial ordering:
//
// a.ReturnResult(1) ==>
// a.ReturnResult(2) * n ==> a.ReturnResult(3)
// b.DoB() * 2 ==>
Sequence x, y;
EXPECT_CALL(a_, ReturnResult(1))
.InSequence(x);
EXPECT_CALL(b_, DoB())
.Times(2)
.InSequence(y);
EXPECT_CALL(a_, ReturnResult(2))
.Times(AnyNumber())
.InSequence(x, y);
EXPECT_CALL(a_, ReturnResult(3))
.InSequence(x);
}
MockA a_;
MockB b_;
};
TEST_F(PartialOrderTest, CallsMustConformToSpecifiedDag1) {
a_.ReturnResult(1);
b_.DoB();
// May only be called after the second DoB().
EXPECT_NONFATAL_FAILURE(a_.ReturnResult(2), "Unexpected mock function call");
b_.DoB();
a_.ReturnResult(3);
}
TEST_F(PartialOrderTest, CallsMustConformToSpecifiedDag2) {
// May only be called after ReturnResult(1).
EXPECT_NONFATAL_FAILURE(a_.ReturnResult(2), "Unexpected mock function call");
a_.ReturnResult(1);
b_.DoB();
b_.DoB();
a_.ReturnResult(3);
}
TEST_F(PartialOrderTest, CallsMustConformToSpecifiedDag3) {
// May only be called last.
EXPECT_NONFATAL_FAILURE(a_.ReturnResult(3), "Unexpected mock function call");
a_.ReturnResult(1);
b_.DoB();
b_.DoB();
a_.ReturnResult(3);
}
TEST_F(PartialOrderTest, CallsMustConformToSpecifiedDag4) {
a_.ReturnResult(1);
b_.DoB();
b_.DoB();
a_.ReturnResult(3);
// May only be called before ReturnResult(3).
EXPECT_NONFATAL_FAILURE(a_.ReturnResult(2), "Unexpected mock function call");
}
TEST(SequenceTest, Retirement) {
MockA a;
Sequence s;
EXPECT_CALL(a, DoA(1))
.InSequence(s);
EXPECT_CALL(a, DoA(_))
.InSequence(s)
.RetiresOnSaturation();
EXPECT_CALL(a, DoA(1))
.InSequence(s);
a.DoA(1);
a.DoA(2);
a.DoA(1);
}
// Tests Expectation.
TEST(ExpectationTest, ConstrutorsWork) {
MockA a;
Expectation e1; // Default ctor.
// Ctor from various forms of EXPECT_CALL.
Expectation e2 = EXPECT_CALL(a, DoA(2));
Expectation e3 = EXPECT_CALL(a, DoA(3)).With(_);
{
Sequence s;
Expectation e4 = EXPECT_CALL(a, DoA(4)).Times(1);
Expectation e5 = EXPECT_CALL(a, DoA(5)).InSequence(s);
}
Expectation e6 = EXPECT_CALL(a, DoA(6)).After(e2);
Expectation e7 = EXPECT_CALL(a, DoA(7)).WillOnce(Return());
Expectation e8 = EXPECT_CALL(a, DoA(8)).WillRepeatedly(Return());
Expectation e9 = EXPECT_CALL(a, DoA(9)).RetiresOnSaturation();
Expectation e10 = e2; // Copy ctor.
EXPECT_THAT(e1, Ne(e2));
EXPECT_THAT(e2, Eq(e10));
a.DoA(2);
a.DoA(3);
a.DoA(4);
a.DoA(5);
a.DoA(6);
a.DoA(7);
a.DoA(8);
a.DoA(9);
}
TEST(ExpectationTest, AssignmentWorks) {
MockA a;
Expectation e1;
Expectation e2 = EXPECT_CALL(a, DoA(1));
EXPECT_THAT(e1, Ne(e2));
e1 = e2;
EXPECT_THAT(e1, Eq(e2));
a.DoA(1);
}
// Tests ExpectationSet.
TEST(ExpectationSetTest, MemberTypesAreCorrect) {
::testing::StaticAssertTypeEq<Expectation, ExpectationSet::value_type>();
}
TEST(ExpectationSetTest, ConstructorsWork) {
MockA a;
Expectation e1;
const Expectation e2;
ExpectationSet es1; // Default ctor.
ExpectationSet es2 = EXPECT_CALL(a, DoA(1)); // Ctor from EXPECT_CALL.
ExpectationSet es3 = e1; // Ctor from Expectation.
ExpectationSet es4(e1); // Ctor from Expectation; alternative syntax.
ExpectationSet es5 = e2; // Ctor from const Expectation.
ExpectationSet es6(e2); // Ctor from const Expectation; alternative syntax.
ExpectationSet es7 = es2; // Copy ctor.
EXPECT_EQ(0, es1.size());
EXPECT_EQ(1, es2.size());
EXPECT_EQ(1, es3.size());
EXPECT_EQ(1, es4.size());
EXPECT_EQ(1, es5.size());
EXPECT_EQ(1, es6.size());
EXPECT_EQ(1, es7.size());
EXPECT_THAT(es3, Ne(es2));
EXPECT_THAT(es4, Eq(es3));
EXPECT_THAT(es5, Eq(es4));
EXPECT_THAT(es6, Eq(es5));
EXPECT_THAT(es7, Eq(es2));
a.DoA(1);
}
TEST(ExpectationSetTest, AssignmentWorks) {
ExpectationSet es1;
ExpectationSet es2 = Expectation();
es1 = es2;
EXPECT_EQ(1, es1.size());
EXPECT_THAT(*(es1.begin()), Eq(Expectation()));
EXPECT_THAT(es1, Eq(es2));
}
TEST(ExpectationSetTest, InsertionWorks) {
ExpectationSet es1;
Expectation e1;
es1 += e1;
EXPECT_EQ(1, es1.size());
EXPECT_THAT(*(es1.begin()), Eq(e1));
MockA a;
Expectation e2 = EXPECT_CALL(a, DoA(1));
es1 += e2;
EXPECT_EQ(2, es1.size());
ExpectationSet::const_iterator it1 = es1.begin();
ExpectationSet::const_iterator it2 = it1;
++it2;
EXPECT_TRUE(*it1 == e1 || *it2 == e1); // e1 must be in the set.
EXPECT_TRUE(*it1 == e2 || *it2 == e2); // e2 must be in the set too.
a.DoA(1);
}
TEST(ExpectationSetTest, SizeWorks) {
ExpectationSet es;
EXPECT_EQ(0, es.size());
es += Expectation();
EXPECT_EQ(1, es.size());
MockA a;
es += EXPECT_CALL(a, DoA(1));
EXPECT_EQ(2, es.size());
a.DoA(1);
}
TEST(ExpectationSetTest, IsEnumerable) {
ExpectationSet es;
EXPECT_TRUE(es.begin() == es.end());
es += Expectation();
ExpectationSet::const_iterator it = es.begin();
EXPECT_TRUE(it != es.end());
EXPECT_THAT(*it, Eq(Expectation()));
++it;
EXPECT_TRUE(it== es.end());
}
// Tests the .After() clause.
TEST(AfterTest, SucceedsWhenPartialOrderIsSatisfied) {
MockA a;
ExpectationSet es;
es += EXPECT_CALL(a, DoA(1));
es += EXPECT_CALL(a, DoA(2));
EXPECT_CALL(a, DoA(3))
.After(es);
a.DoA(1);
a.DoA(2);
a.DoA(3);
}
TEST(AfterTest, SucceedsWhenTotalOrderIsSatisfied) {
MockA a;
MockB b;
// The following also verifies that const Expectation objects work
// too. Do not remove the const modifiers.
const Expectation e1 = EXPECT_CALL(a, DoA(1));
const Expectation e2 = EXPECT_CALL(b, DoB())
.Times(2)
.After(e1);
EXPECT_CALL(a, DoA(2)).After(e2);
a.DoA(1);
b.DoB();
b.DoB();
a.DoA(2);
}
// Calls must be in strict order when specified so using .After().
TEST(AfterTest, CallsMustBeInStrictOrderWhenSpecifiedSo1) {
MockA a;
MockB b;
// Define ordering:
// a.DoA(1) ==> b.DoB() ==> a.DoA(2)
Expectation e1 = EXPECT_CALL(a, DoA(1));
Expectation e2 = EXPECT_CALL(b, DoB())
.After(e1);
EXPECT_CALL(a, DoA(2))
.After(e2);
a.DoA(1);
// May only be called after DoB().
EXPECT_NONFATAL_FAILURE(a.DoA(2), "Unexpected mock function call");
b.DoB();
a.DoA(2);
}
// Calls must be in strict order when specified so using .After().
TEST(AfterTest, CallsMustBeInStrictOrderWhenSpecifiedSo2) {
MockA a;
MockB b;
// Define ordering:
// a.DoA(1) ==> b.DoB() * 2 ==> a.DoA(2)
Expectation e1 = EXPECT_CALL(a, DoA(1));
Expectation e2 = EXPECT_CALL(b, DoB())
.Times(2)
.After(e1);
EXPECT_CALL(a, DoA(2))
.After(e2);
a.DoA(1);
b.DoB();
// May only be called after the second DoB().
EXPECT_NONFATAL_FAILURE(a.DoA(2), "Unexpected mock function call");
b.DoB();
a.DoA(2);
}
// Calls must satisfy the partial order when specified so.
TEST(AfterTest, CallsMustSatisfyPartialOrderWhenSpecifiedSo) {
MockA a;
ON_CALL(a, ReturnResult(_))
.WillByDefault(Return(Result()));
// Define ordering:
// a.DoA(1) ==>
// a.DoA(2) ==> a.ReturnResult(3)
Expectation e = EXPECT_CALL(a, DoA(1));
const ExpectationSet es = EXPECT_CALL(a, DoA(2));
EXPECT_CALL(a, ReturnResult(3))
.After(e, es);
// May only be called last.
EXPECT_NONFATAL_FAILURE(a.ReturnResult(3), "Unexpected mock function call");
a.DoA(2);
a.DoA(1);
a.ReturnResult(3);
}
// Calls must satisfy the partial order when specified so.
TEST(AfterTest, CallsMustSatisfyPartialOrderWhenSpecifiedSo2) {
MockA a;
// Define ordering:
// a.DoA(1) ==>
// a.DoA(2) ==> a.DoA(3)
Expectation e = EXPECT_CALL(a, DoA(1));
const ExpectationSet es = EXPECT_CALL(a, DoA(2));
EXPECT_CALL(a, DoA(3))
.After(e, es);
a.DoA(2);
// May only be called last.
EXPECT_NONFATAL_FAILURE(a.DoA(3), "Unexpected mock function call");
a.DoA(1);
a.DoA(3);
}
// .After() can be combined with .InSequence().
TEST(AfterTest, CanBeUsedWithInSequence) {
MockA a;
Sequence s;
Expectation e = EXPECT_CALL(a, DoA(1));
EXPECT_CALL(a, DoA(2)).InSequence(s);
EXPECT_CALL(a, DoA(3))
.InSequence(s)
.After(e);
a.DoA(1);
// May only be after DoA(2).
EXPECT_NONFATAL_FAILURE(a.DoA(3), "Unexpected mock function call");
a.DoA(2);
a.DoA(3);
}
// .After() can be called multiple times.
TEST(AfterTest, CanBeCalledManyTimes) {
MockA a;
Expectation e1 = EXPECT_CALL(a, DoA(1));
Expectation e2 = EXPECT_CALL(a, DoA(2));
Expectation e3 = EXPECT_CALL(a, DoA(3));
EXPECT_CALL(a, DoA(4))
.After(e1)
.After(e2)
.After(e3);
a.DoA(3);
a.DoA(1);
a.DoA(2);
a.DoA(4);
}
// .After() accepts up to 5 arguments.
TEST(AfterTest, AcceptsUpToFiveArguments) {
MockA a;
Expectation e1 = EXPECT_CALL(a, DoA(1));
Expectation e2 = EXPECT_CALL(a, DoA(2));
Expectation e3 = EXPECT_CALL(a, DoA(3));
ExpectationSet es1 = EXPECT_CALL(a, DoA(4));
ExpectationSet es2 = EXPECT_CALL(a, DoA(5));
EXPECT_CALL(a, DoA(6))
.After(e1, e2, e3, es1, es2);
a.DoA(5);
a.DoA(2);
a.DoA(4);
a.DoA(1);
a.DoA(3);
a.DoA(6);
}
// .After() allows input to contain duplicated Expectations.
TEST(AfterTest, AcceptsDuplicatedInput) {
MockA a;
ON_CALL(a, ReturnResult(_))
.WillByDefault(Return(Result()));
// Define ordering:
// DoA(1) ==>
// DoA(2) ==> ReturnResult(3)
Expectation e1 = EXPECT_CALL(a, DoA(1));
Expectation e2 = EXPECT_CALL(a, DoA(2));
ExpectationSet es;
es += e1;
es += e2;
EXPECT_CALL(a, ReturnResult(3))
.After(e1, e2, es, e1);
a.DoA(1);
// May only be after DoA(2).
EXPECT_NONFATAL_FAILURE(a.ReturnResult(3), "Unexpected mock function call");
a.DoA(2);
a.ReturnResult(3);
}
// An Expectation added to an ExpectationSet after it has been used in
// an .After() has no effect.
TEST(AfterTest, ChangesToExpectationSetHaveNoEffectAfterwards) {
MockA a;
ExpectationSet es1 = EXPECT_CALL(a, DoA(1));
Expectation e2 = EXPECT_CALL(a, DoA(2));
EXPECT_CALL(a, DoA(3))
.After(es1);
es1 += e2;
a.DoA(1);
a.DoA(3);
a.DoA(2);
}
// Tests that Google Mock correctly handles calls to mock functions
// after a mock object owning one of their pre-requisites has died.
// Tests that calls that satisfy the original spec are successful.
TEST(DeletingMockEarlyTest, Success1) {
MockB* const b1 = new MockB;
MockA* const a = new MockA;
MockB* const b2 = new MockB;
{
InSequence dummy;
EXPECT_CALL(*b1, DoB(_))
.WillOnce(Return(1));
EXPECT_CALL(*a, Binary(_, _))
.Times(AnyNumber())
.WillRepeatedly(Return(true));
EXPECT_CALL(*b2, DoB(_))
.Times(AnyNumber())
.WillRepeatedly(Return(2));
}
EXPECT_EQ(1, b1->DoB(1));
delete b1;
// a's pre-requisite has died.
EXPECT_TRUE(a->Binary(0, 1));
delete b2;
// a's successor has died.
EXPECT_TRUE(a->Binary(1, 2));
delete a;
}
// Tests that calls that satisfy the original spec are successful.
TEST(DeletingMockEarlyTest, Success2) {
MockB* const b1 = new MockB;
MockA* const a = new MockA;
MockB* const b2 = new MockB;
{
InSequence dummy;
EXPECT_CALL(*b1, DoB(_))
.WillOnce(Return(1));
EXPECT_CALL(*a, Binary(_, _))
.Times(AnyNumber());
EXPECT_CALL(*b2, DoB(_))
.Times(AnyNumber())
.WillRepeatedly(Return(2));
}
delete a; // a is trivially satisfied.
EXPECT_EQ(1, b1->DoB(1));
EXPECT_EQ(2, b2->DoB(2));
delete b1;
delete b2;
}
// Tests that it's OK to delete a mock object itself in its action.
// Suppresses warning on unreferenced formal parameter in MSVC with
// -W4.
#ifdef _MSC_VER
# pragma warning(push)
# pragma warning(disable:4100)
#endif
ACTION_P(Delete, ptr) { delete ptr; }
#ifdef _MSC_VER
# pragma warning(pop)
#endif
TEST(DeletingMockEarlyTest, CanDeleteSelfInActionReturningVoid) {
MockA* const a = new MockA;
EXPECT_CALL(*a, DoA(_)).WillOnce(Delete(a));
a->DoA(42); // This will cause a to be deleted.
}
TEST(DeletingMockEarlyTest, CanDeleteSelfInActionReturningValue) {
MockA* const a = new MockA;
EXPECT_CALL(*a, ReturnResult(_))
.WillOnce(DoAll(Delete(a), Return(Result())));
a->ReturnResult(42); // This will cause a to be deleted.
}
// Tests that calls that violate the original spec yield failures.
TEST(DeletingMockEarlyTest, Failure1) {
MockB* const b1 = new MockB;
MockA* const a = new MockA;
MockB* const b2 = new MockB;
{
InSequence dummy;
EXPECT_CALL(*b1, DoB(_))
.WillOnce(Return(1));
EXPECT_CALL(*a, Binary(_, _))
.Times(AnyNumber());
EXPECT_CALL(*b2, DoB(_))
.Times(AnyNumber())
.WillRepeatedly(Return(2));
}
delete a; // a is trivially satisfied.
EXPECT_NONFATAL_FAILURE({
b2->DoB(2);
}, "Unexpected mock function call");
EXPECT_EQ(1, b1->DoB(1));
delete b1;
delete b2;
}
// Tests that calls that violate the original spec yield failures.
TEST(DeletingMockEarlyTest, Failure2) {
MockB* const b1 = new MockB;
MockA* const a = new MockA;
MockB* const b2 = new MockB;
{
InSequence dummy;
EXPECT_CALL(*b1, DoB(_));
EXPECT_CALL(*a, Binary(_, _))
.Times(AnyNumber());
EXPECT_CALL(*b2, DoB(_))
.Times(AnyNumber());
}
EXPECT_NONFATAL_FAILURE(delete b1,
"Actual: never called");
EXPECT_NONFATAL_FAILURE(a->Binary(0, 1),
"Unexpected mock function call");
EXPECT_NONFATAL_FAILURE(b2->DoB(1),
"Unexpected mock function call");
delete a;
delete b2;
}
class EvenNumberCardinality : public CardinalityInterface {
public:
// Returns true iff call_count calls will satisfy this cardinality.
virtual bool IsSatisfiedByCallCount(int call_count) const {
return call_count % 2 == 0;
}
// Returns true iff call_count calls will saturate this cardinality.
virtual bool IsSaturatedByCallCount(int /* call_count */) const {
return false;
}
// Describes self to an ostream.
virtual void DescribeTo(::std::ostream* os) const {
*os << "called even number of times";
}
};
Cardinality EvenNumber() {
return Cardinality(new EvenNumberCardinality);
}
TEST(ExpectationBaseTest,
AllPrerequisitesAreSatisfiedWorksForNonMonotonicCardinality) {
MockA* a = new MockA;
Sequence s;
EXPECT_CALL(*a, DoA(1))
.Times(EvenNumber())
.InSequence(s);
EXPECT_CALL(*a, DoA(2))
.Times(AnyNumber())
.InSequence(s);
EXPECT_CALL(*a, DoA(3))
.Times(AnyNumber());
a->DoA(3);
a->DoA(1);
EXPECT_NONFATAL_FAILURE(a->DoA(2), "Unexpected mock function call");
EXPECT_NONFATAL_FAILURE(delete a, "to be called even number of times");
}
// The following tests verify the message generated when a mock
// function is called.
struct Printable {
};
inline void operator<<(::std::ostream& os, const Printable&) {
os << "Printable";
}
struct Unprintable {
Unprintable() : value(0) {}
int value;
};
class MockC {
public:
MockC() {}
MOCK_METHOD6(VoidMethod, void(bool cond, int n, string s, void* p,
const Printable& x, Unprintable y));
MOCK_METHOD0(NonVoidMethod, int()); // NOLINT
private:
GTEST_DISALLOW_COPY_AND_ASSIGN_(MockC);
};
class VerboseFlagPreservingFixture : public testing::Test {
protected:
VerboseFlagPreservingFixture()
: saved_verbose_flag_(GMOCK_FLAG(verbose)) {}
~VerboseFlagPreservingFixture() { GMOCK_FLAG(verbose) = saved_verbose_flag_; }
private:
const string saved_verbose_flag_;
GTEST_DISALLOW_COPY_AND_ASSIGN_(VerboseFlagPreservingFixture);
};
#if GTEST_HAS_STREAM_REDIRECTION
// Tests that an uninteresting mock function call on a naggy mock
// generates a warning containing the stack trace.
TEST(FunctionCallMessageTest,
UninterestingCallOnNaggyMockGeneratesFyiWithStackTrace) {
NaggyMock<MockC> c;
CaptureStdout();
c.VoidMethod(false, 5, "Hi", NULL, Printable(), Unprintable());
const std::string output = GetCapturedStdout();
EXPECT_PRED_FORMAT2(IsSubstring, "GMOCK WARNING", output);
EXPECT_PRED_FORMAT2(IsSubstring, "Stack trace:", output);
# ifndef NDEBUG
// We check the stack trace content in dbg-mode only, as opt-mode
// may inline the call we are interested in seeing.
// Verifies that a void mock function's name appears in the stack
// trace.
EXPECT_PRED_FORMAT2(IsSubstring, "VoidMethod(", output);
// Verifies that a non-void mock function's name appears in the
// stack trace.
CaptureStdout();
c.NonVoidMethod();
const std::string output2 = GetCapturedStdout();
EXPECT_PRED_FORMAT2(IsSubstring, "NonVoidMethod(", output2);
# endif // NDEBUG
}
// Tests that an uninteresting mock function call on a naggy mock
// causes the function arguments and return value to be printed.
TEST(FunctionCallMessageTest,
UninterestingCallOnNaggyMockPrintsArgumentsAndReturnValue) {
// A non-void mock function.
NaggyMock<MockB> b;
CaptureStdout();
b.DoB();
const std::string output1 = GetCapturedStdout();
EXPECT_PRED_FORMAT2(
IsSubstring,
"Uninteresting mock function call - returning default value.\n"
" Function call: DoB()\n"
" Returns: 0\n", output1.c_str());
// Makes sure the return value is printed.
// A void mock function.
NaggyMock<MockC> c;
CaptureStdout();
c.VoidMethod(false, 5, "Hi", NULL, Printable(), Unprintable());
const std::string output2 = GetCapturedStdout();
EXPECT_THAT(output2.c_str(),
ContainsRegex(
"Uninteresting mock function call - returning directly\\.\n"
" Function call: VoidMethod"
"\\(false, 5, \"Hi\", NULL, @.+ "
"Printable, 4-byte object <00-00 00-00>\\)"));
// A void function has no return value to print.
}
// Tests how the --gmock_verbose flag affects Google Mock's output.
class GMockVerboseFlagTest : public VerboseFlagPreservingFixture {
public:
// Verifies that the given Google Mock output is correct. (When
// should_print is true, the output should match the given regex and
// contain the given function name in the stack trace. When it's
// false, the output should be empty.)
void VerifyOutput(const std::string& output, bool should_print,
const string& expected_substring,
const string& function_name) {
if (should_print) {
EXPECT_THAT(output.c_str(), HasSubstr(expected_substring));
# ifndef NDEBUG
// We check the stack trace content in dbg-mode only, as opt-mode
// may inline the call we are interested in seeing.
EXPECT_THAT(output.c_str(), HasSubstr(function_name));
# else
// Suppresses 'unused function parameter' warnings.
static_cast<void>(function_name);
# endif // NDEBUG
} else {
EXPECT_STREQ("", output.c_str());
}
}
// Tests how the flag affects expected calls.
void TestExpectedCall(bool should_print) {
MockA a;
EXPECT_CALL(a, DoA(5));
EXPECT_CALL(a, Binary(_, 1))
.WillOnce(Return(true));
// A void-returning function.
CaptureStdout();
a.DoA(5);
VerifyOutput(
GetCapturedStdout(),
should_print,
"Mock function call matches EXPECT_CALL(a, DoA(5))...\n"
" Function call: DoA(5)\n"
"Stack trace:\n",
"DoA");
// A non-void-returning function.
CaptureStdout();
a.Binary(2, 1);
VerifyOutput(
GetCapturedStdout(),
should_print,
"Mock function call matches EXPECT_CALL(a, Binary(_, 1))...\n"
" Function call: Binary(2, 1)\n"
" Returns: true\n"
"Stack trace:\n",
"Binary");
}
// Tests how the flag affects uninteresting calls on a naggy mock.
void TestUninterestingCallOnNaggyMock(bool should_print) {
NaggyMock<MockA> a;
// A void-returning function.
CaptureStdout();
a.DoA(5);
VerifyOutput(
GetCapturedStdout(),
should_print,
"\nGMOCK WARNING:\n"
"Uninteresting mock function call - returning directly.\n"
" Function call: DoA(5)\n"
"Stack trace:\n",
"DoA");
// A non-void-returning function.
CaptureStdout();
a.Binary(2, 1);
VerifyOutput(
GetCapturedStdout(),
should_print,
"\nGMOCK WARNING:\n"
"Uninteresting mock function call - returning default value.\n"
" Function call: Binary(2, 1)\n"
" Returns: false\n"
"Stack trace:\n",
"Binary");
}
};
// Tests that --gmock_verbose=info causes both expected and
// uninteresting calls to be reported.
TEST_F(GMockVerboseFlagTest, Info) {
GMOCK_FLAG(verbose) = kInfoVerbosity;
TestExpectedCall(true);
TestUninterestingCallOnNaggyMock(true);
}
// Tests that --gmock_verbose=warning causes uninteresting calls to be
// reported.
TEST_F(GMockVerboseFlagTest, Warning) {
GMOCK_FLAG(verbose) = kWarningVerbosity;
TestExpectedCall(false);
TestUninterestingCallOnNaggyMock(true);
}
// Tests that --gmock_verbose=warning causes neither expected nor
// uninteresting calls to be reported.
TEST_F(GMockVerboseFlagTest, Error) {
GMOCK_FLAG(verbose) = kErrorVerbosity;
TestExpectedCall(false);
TestUninterestingCallOnNaggyMock(false);
}
// Tests that --gmock_verbose=SOME_INVALID_VALUE has the same effect
// as --gmock_verbose=warning.
TEST_F(GMockVerboseFlagTest, InvalidFlagIsTreatedAsWarning) {
GMOCK_FLAG(verbose) = "invalid"; // Treated as "warning".
TestExpectedCall(false);
TestUninterestingCallOnNaggyMock(true);
}
#endif // GTEST_HAS_STREAM_REDIRECTION
// A helper class that generates a failure when printed. We use it to
// ensure that Google Mock doesn't print a value (even to an internal
// buffer) when it is not supposed to do so.
class PrintMeNot {};
void PrintTo(PrintMeNot /* dummy */, ::std::ostream* /* os */) {
ADD_FAILURE() << "Google Mock is printing a value that shouldn't be "
<< "printed even to an internal buffer.";
}
class LogTestHelper {
public:
LogTestHelper() {}
MOCK_METHOD1(Foo, PrintMeNot(PrintMeNot));
private:
GTEST_DISALLOW_COPY_AND_ASSIGN_(LogTestHelper);
};
class GMockLogTest : public VerboseFlagPreservingFixture {
protected:
LogTestHelper helper_;
};
TEST_F(GMockLogTest, DoesNotPrintGoodCallInternallyIfVerbosityIsWarning) {
GMOCK_FLAG(verbose) = kWarningVerbosity;
EXPECT_CALL(helper_, Foo(_))
.WillOnce(Return(PrintMeNot()));
helper_.Foo(PrintMeNot()); // This is an expected call.
}
TEST_F(GMockLogTest, DoesNotPrintGoodCallInternallyIfVerbosityIsError) {
GMOCK_FLAG(verbose) = kErrorVerbosity;
EXPECT_CALL(helper_, Foo(_))
.WillOnce(Return(PrintMeNot()));
helper_.Foo(PrintMeNot()); // This is an expected call.
}
TEST_F(GMockLogTest, DoesNotPrintWarningInternallyIfVerbosityIsError) {
GMOCK_FLAG(verbose) = kErrorVerbosity;
ON_CALL(helper_, Foo(_))
.WillByDefault(Return(PrintMeNot()));
helper_.Foo(PrintMeNot()); // This should generate a warning.
}
// Tests Mock::AllowLeak().
TEST(AllowLeakTest, AllowsLeakingUnusedMockObject) {
MockA* a = new MockA;
Mock::AllowLeak(a);
}
TEST(AllowLeakTest, CanBeCalledBeforeOnCall) {
MockA* a = new MockA;
Mock::AllowLeak(a);
ON_CALL(*a, DoA(_)).WillByDefault(Return());
a->DoA(0);
}
TEST(AllowLeakTest, CanBeCalledAfterOnCall) {
MockA* a = new MockA;
ON_CALL(*a, DoA(_)).WillByDefault(Return());
Mock::AllowLeak(a);
}
TEST(AllowLeakTest, CanBeCalledBeforeExpectCall) {
MockA* a = new MockA;
Mock::AllowLeak(a);
EXPECT_CALL(*a, DoA(_));
a->DoA(0);
}
TEST(AllowLeakTest, CanBeCalledAfterExpectCall) {
MockA* a = new MockA;
EXPECT_CALL(*a, DoA(_)).Times(AnyNumber());
Mock::AllowLeak(a);
}
TEST(AllowLeakTest, WorksWhenBothOnCallAndExpectCallArePresent) {
MockA* a = new MockA;
ON_CALL(*a, DoA(_)).WillByDefault(Return());
EXPECT_CALL(*a, DoA(_)).Times(AnyNumber());
Mock::AllowLeak(a);
}
// Tests that we can verify and clear a mock object's expectations
// when none of its methods has expectations.
TEST(VerifyAndClearExpectationsTest, NoMethodHasExpectations) {
MockB b;
ASSERT_TRUE(Mock::VerifyAndClearExpectations(&b));
// There should be no expectations on the methods now, so we can
// freely call them.
EXPECT_EQ(0, b.DoB());
EXPECT_EQ(0, b.DoB(1));
}
// Tests that we can verify and clear a mock object's expectations
// when some, but not all, of its methods have expectations *and* the
// verification succeeds.
TEST(VerifyAndClearExpectationsTest, SomeMethodsHaveExpectationsAndSucceed) {
MockB b;
EXPECT_CALL(b, DoB())
.WillOnce(Return(1));
b.DoB();
ASSERT_TRUE(Mock::VerifyAndClearExpectations(&b));
// There should be no expectations on the methods now, so we can
// freely call them.
EXPECT_EQ(0, b.DoB());
EXPECT_EQ(0, b.DoB(1));
}
// Tests that we can verify and clear a mock object's expectations
// when some, but not all, of its methods have expectations *and* the
// verification fails.
TEST(VerifyAndClearExpectationsTest, SomeMethodsHaveExpectationsAndFail) {
MockB b;
EXPECT_CALL(b, DoB())
.WillOnce(Return(1));
bool result = true;
EXPECT_NONFATAL_FAILURE(result = Mock::VerifyAndClearExpectations(&b),
"Actual: never called");
ASSERT_FALSE(result);
// There should be no expectations on the methods now, so we can
// freely call them.
EXPECT_EQ(0, b.DoB());
EXPECT_EQ(0, b.DoB(1));
}
// Tests that we can verify and clear a mock object's expectations
// when all of its methods have expectations.
TEST(VerifyAndClearExpectationsTest, AllMethodsHaveExpectations) {
MockB b;
EXPECT_CALL(b, DoB())
.WillOnce(Return(1));
EXPECT_CALL(b, DoB(_))
.WillOnce(Return(2));
b.DoB();
b.DoB(1);
ASSERT_TRUE(Mock::VerifyAndClearExpectations(&b));
// There should be no expectations on the methods now, so we can
// freely call them.
EXPECT_EQ(0, b.DoB());
EXPECT_EQ(0, b.DoB(1));
}
// Tests that we can verify and clear a mock object's expectations
// when a method has more than one expectation.
TEST(VerifyAndClearExpectationsTest, AMethodHasManyExpectations) {
MockB b;
EXPECT_CALL(b, DoB(0))
.WillOnce(Return(1));
EXPECT_CALL(b, DoB(_))
.WillOnce(Return(2));
b.DoB(1);
bool result = true;
EXPECT_NONFATAL_FAILURE(result = Mock::VerifyAndClearExpectations(&b),
"Actual: never called");
ASSERT_FALSE(result);
// There should be no expectations on the methods now, so we can
// freely call them.
EXPECT_EQ(0, b.DoB());
EXPECT_EQ(0, b.DoB(1));
}
// Tests that we can call VerifyAndClearExpectations() on the same
// mock object multiple times.
TEST(VerifyAndClearExpectationsTest, CanCallManyTimes) {
MockB b;
EXPECT_CALL(b, DoB());
b.DoB();
Mock::VerifyAndClearExpectations(&b);
EXPECT_CALL(b, DoB(_))
.WillOnce(Return(1));
b.DoB(1);
Mock::VerifyAndClearExpectations(&b);
Mock::VerifyAndClearExpectations(&b);
// There should be no expectations on the methods now, so we can
// freely call them.
EXPECT_EQ(0, b.DoB());
EXPECT_EQ(0, b.DoB(1));
}
// Tests that we can clear a mock object's default actions when none
// of its methods has default actions.
TEST(VerifyAndClearTest, NoMethodHasDefaultActions) {
MockB b;
// If this crashes or generates a failure, the test will catch it.
Mock::VerifyAndClear(&b);
EXPECT_EQ(0, b.DoB());
}
// Tests that we can clear a mock object's default actions when some,
// but not all of its methods have default actions.
TEST(VerifyAndClearTest, SomeMethodsHaveDefaultActions) {
MockB b;
ON_CALL(b, DoB())
.WillByDefault(Return(1));
Mock::VerifyAndClear(&b);
// Verifies that the default action of int DoB() was removed.
EXPECT_EQ(0, b.DoB());
}
// Tests that we can clear a mock object's default actions when all of
// its methods have default actions.
TEST(VerifyAndClearTest, AllMethodsHaveDefaultActions) {
MockB b;
ON_CALL(b, DoB())
.WillByDefault(Return(1));
ON_CALL(b, DoB(_))
.WillByDefault(Return(2));
Mock::VerifyAndClear(&b);
// Verifies that the default action of int DoB() was removed.
EXPECT_EQ(0, b.DoB());
// Verifies that the default action of int DoB(int) was removed.
EXPECT_EQ(0, b.DoB(0));
}
// Tests that we can clear a mock object's default actions when a
// method has more than one ON_CALL() set on it.
TEST(VerifyAndClearTest, AMethodHasManyDefaultActions) {
MockB b;
ON_CALL(b, DoB(0))
.WillByDefault(Return(1));
ON_CALL(b, DoB(_))
.WillByDefault(Return(2));
Mock::VerifyAndClear(&b);
// Verifies that the default actions (there are two) of int DoB(int)
// were removed.
EXPECT_EQ(0, b.DoB(0));
EXPECT_EQ(0, b.DoB(1));
}
// Tests that we can call VerifyAndClear() on a mock object multiple
// times.
TEST(VerifyAndClearTest, CanCallManyTimes) {
MockB b;
ON_CALL(b, DoB())
.WillByDefault(Return(1));
Mock::VerifyAndClear(&b);
Mock::VerifyAndClear(&b);
ON_CALL(b, DoB(_))
.WillByDefault(Return(1));
Mock::VerifyAndClear(&b);
EXPECT_EQ(0, b.DoB());
EXPECT_EQ(0, b.DoB(1));
}
// Tests that VerifyAndClear() works when the verification succeeds.
TEST(VerifyAndClearTest, Success) {
MockB b;
ON_CALL(b, DoB())
.WillByDefault(Return(1));
EXPECT_CALL(b, DoB(1))
.WillOnce(Return(2));
b.DoB();
b.DoB(1);
ASSERT_TRUE(Mock::VerifyAndClear(&b));
// There should be no expectations on the methods now, so we can
// freely call them.
EXPECT_EQ(0, b.DoB());
EXPECT_EQ(0, b.DoB(1));
}
// Tests that VerifyAndClear() works when the verification fails.
TEST(VerifyAndClearTest, Failure) {
MockB b;
ON_CALL(b, DoB(_))
.WillByDefault(Return(1));
EXPECT_CALL(b, DoB())
.WillOnce(Return(2));
b.DoB(1);
bool result = true;
EXPECT_NONFATAL_FAILURE(result = Mock::VerifyAndClear(&b),
"Actual: never called");
ASSERT_FALSE(result);
// There should be no expectations on the methods now, so we can
// freely call them.
EXPECT_EQ(0, b.DoB());
EXPECT_EQ(0, b.DoB(1));
}
// Tests that VerifyAndClear() works when the default actions and
// expectations are set on a const mock object.
TEST(VerifyAndClearTest, Const) {
MockB b;
ON_CALL(Const(b), DoB())
.WillByDefault(Return(1));
EXPECT_CALL(Const(b), DoB())
.WillOnce(DoDefault())
.WillOnce(Return(2));
b.DoB();
b.DoB();
ASSERT_TRUE(Mock::VerifyAndClear(&b));
// There should be no expectations on the methods now, so we can
// freely call them.
EXPECT_EQ(0, b.DoB());
EXPECT_EQ(0, b.DoB(1));
}
// Tests that we can set default actions and expectations on a mock
// object after VerifyAndClear() has been called on it.
TEST(VerifyAndClearTest, CanSetDefaultActionsAndExpectationsAfterwards) {
MockB b;
ON_CALL(b, DoB())
.WillByDefault(Return(1));
EXPECT_CALL(b, DoB(_))
.WillOnce(Return(2));
b.DoB(1);
Mock::VerifyAndClear(&b);
EXPECT_CALL(b, DoB())
.WillOnce(Return(3));
ON_CALL(b, DoB(_))
.WillByDefault(Return(4));
EXPECT_EQ(3, b.DoB());
EXPECT_EQ(4, b.DoB(1));
}
// Tests that calling VerifyAndClear() on one mock object does not
// affect other mock objects (either of the same type or not).
TEST(VerifyAndClearTest, DoesNotAffectOtherMockObjects) {
MockA a;
MockB b1;
MockB b2;
ON_CALL(a, Binary(_, _))
.WillByDefault(Return(true));
EXPECT_CALL(a, Binary(_, _))
.WillOnce(DoDefault())
.WillOnce(Return(false));
ON_CALL(b1, DoB())
.WillByDefault(Return(1));
EXPECT_CALL(b1, DoB(_))
.WillOnce(Return(2));
ON_CALL(b2, DoB())
.WillByDefault(Return(3));
EXPECT_CALL(b2, DoB(_));
b2.DoB(0);
Mock::VerifyAndClear(&b2);
// Verifies that the default actions and expectations of a and b1
// are still in effect.
EXPECT_TRUE(a.Binary(0, 0));
EXPECT_FALSE(a.Binary(0, 0));
EXPECT_EQ(1, b1.DoB());
EXPECT_EQ(2, b1.DoB(0));
}
TEST(VerifyAndClearTest,
DestroyingChainedMocksDoesNotDeadlockThroughExpectations) {
linked_ptr<MockA> a(new MockA);
ReferenceHoldingMock test_mock;
// EXPECT_CALL stores a reference to a inside test_mock.
EXPECT_CALL(test_mock, AcceptReference(_))
.WillRepeatedly(SetArgPointee<0>(a));
// Throw away the reference to the mock that we have in a. After this, the
// only reference to it is stored by test_mock.
a.reset();
// When test_mock goes out of scope, it destroys the last remaining reference
// to the mock object originally pointed to by a. This will cause the MockA
// destructor to be called from inside the ReferenceHoldingMock destructor.
// The state of all mocks is protected by a single global lock, but there
// should be no deadlock.
}
TEST(VerifyAndClearTest,
DestroyingChainedMocksDoesNotDeadlockThroughDefaultAction) {
linked_ptr<MockA> a(new MockA);
ReferenceHoldingMock test_mock;
// ON_CALL stores a reference to a inside test_mock.
ON_CALL(test_mock, AcceptReference(_))
.WillByDefault(SetArgPointee<0>(a));
// Throw away the reference to the mock that we have in a. After this, the
// only reference to it is stored by test_mock.
a.reset();
// When test_mock goes out of scope, it destroys the last remaining reference
// to the mock object originally pointed to by a. This will cause the MockA
// destructor to be called from inside the ReferenceHoldingMock destructor.
// The state of all mocks is protected by a single global lock, but there
// should be no deadlock.
}
// Tests that a mock function's action can call a mock function
// (either the same function or a different one) either as an explicit
// action or as a default action without causing a dead lock. It
// verifies that the action is not performed inside the critical
// section.
TEST(SynchronizationTest, CanCallMockMethodInAction) {
MockA a;
MockC c;
ON_CALL(a, DoA(_))
.WillByDefault(IgnoreResult(InvokeWithoutArgs(&c,
&MockC::NonVoidMethod)));
EXPECT_CALL(a, DoA(1));
EXPECT_CALL(a, DoA(1))
.WillOnce(Invoke(&a, &MockA::DoA))
.RetiresOnSaturation();
EXPECT_CALL(c, NonVoidMethod());
a.DoA(1);
// This will match the second EXPECT_CALL() and trigger another a.DoA(1),
// which will in turn match the first EXPECT_CALL() and trigger a call to
// c.NonVoidMethod() that was specified by the ON_CALL() since the first
// EXPECT_CALL() did not specify an action.
}
} // namespace
// Allows the user to define his own main and then invoke gmock_main
// from it. This might be necessary on some platforms which require
// specific setup and teardown.
#if GMOCK_RENAME_MAIN
int gmock_main(int argc, char **argv) {
#else
int main(int argc, char **argv) {
#endif // GMOCK_RENAME_MAIN
testing::InitGoogleMock(&argc, argv);
// Ensures that the tests pass no matter what value of
// --gmock_catch_leaked_mocks and --gmock_verbose the user specifies.
testing::GMOCK_FLAG(catch_leaked_mocks) = true;
testing::GMOCK_FLAG(verbose) = testing::internal::kWarningVerbosity;
return RUN_ALL_TESTS();
}
// Copyright 2009, 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: wan@google.com (Zhanyong Wan)
//
// Tests for Google C++ Mocking Framework (Google Mock)
//
// Sometimes it's desirable to build most of Google Mock's own tests
// by compiling a single file. This file serves this purpose.
#include "test/gmock-actions_test.cc"
#include "test/gmock-cardinalities_test.cc"
#include "test/gmock-generated-actions_test.cc"
#include "test/gmock-generated-function-mockers_test.cc"
#include "test/gmock-generated-internal-utils_test.cc"
#include "test/gmock-generated-matchers_test.cc"
#include "test/gmock-internal-utils_test.cc"
#include "test/gmock-matchers_test.cc"
#include "test/gmock-more-actions_test.cc"
#include "test/gmock-nice-strict_test.cc"
#include "test/gmock-port_test.cc"
#include "test/gmock-spec-builders_test.cc"
#include "test/gmock_test.cc"
// Copyright 2013, 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: wan@google.com (Zhanyong Wan)
// Tests Google Mock's functionality that depends on exceptions.
#include "gmock/gmock.h"
#include "gtest/gtest.h"
namespace {
using testing::HasSubstr;
using testing::internal::GoogleTestFailureException;
// A user-defined class.
class Something {};
class MockFoo {
public:
// A mock method that returns a user-defined type. Google Mock
// doesn't know what the default value for this type is.
MOCK_METHOD0(GetSomething, Something());
};
#if GTEST_HAS_EXCEPTIONS
TEST(DefaultValueTest, ThrowsRuntimeErrorWhenNoDefaultValue) {
MockFoo mock;
try {
// No expectation is set on this method, so Google Mock must
// return the default value. However, since Google Mock knows
// nothing about the return type, it doesn't know what to return,
// and has to throw (when exceptions are enabled) or abort
// (otherwise).
mock.GetSomething();
FAIL() << "GetSomething()'s return type has no default value, "
<< "so Google Mock should have thrown.";
} catch (const GoogleTestFailureException& /* unused */) {
FAIL() << "Google Test does not try to catch an exception of type "
<< "GoogleTestFailureException, which is used for reporting "
<< "a failure to other testing frameworks. Google Mock should "
<< "not throw a GoogleTestFailureException as it will kill the "
<< "entire test program instead of just the current TEST.";
} catch (const std::exception& ex) {
EXPECT_THAT(ex.what(), HasSubstr("has no default value"));
}
}
#endif
} // unnamed namespace
#!/usr/bin/env python
#
# Copyright 2009, 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.
"""Tests that leaked mock objects can be caught be Google Mock."""
__author__ = 'wan@google.com (Zhanyong Wan)'
import gmock_test_utils
PROGRAM_PATH = gmock_test_utils.GetTestExecutablePath('gmock_leak_test_')
TEST_WITH_EXPECT_CALL = [PROGRAM_PATH, '--gtest_filter=*ExpectCall*']
TEST_WITH_ON_CALL = [PROGRAM_PATH, '--gtest_filter=*OnCall*']
TEST_MULTIPLE_LEAKS = [PROGRAM_PATH, '--gtest_filter=*MultipleLeaked*']
environ = gmock_test_utils.environ
SetEnvVar = gmock_test_utils.SetEnvVar
# Tests in this file run a Google-Test-based test program and expect it
# to terminate prematurely. Therefore they are incompatible with
# the premature-exit-file protocol by design. Unset the
# premature-exit filepath to prevent Google Test from creating
# the file.
SetEnvVar(gmock_test_utils.PREMATURE_EXIT_FILE_ENV_VAR, None)
class GMockLeakTest(gmock_test_utils.TestCase):
def testCatchesLeakedMockByDefault(self):
self.assertNotEqual(
0,
gmock_test_utils.Subprocess(TEST_WITH_EXPECT_CALL,
env=environ).exit_code)
self.assertNotEqual(
0,
gmock_test_utils.Subprocess(TEST_WITH_ON_CALL,
env=environ).exit_code)
def testDoesNotCatchLeakedMockWhenDisabled(self):
self.assertEquals(
0,
gmock_test_utils.Subprocess(TEST_WITH_EXPECT_CALL +
['--gmock_catch_leaked_mocks=0'],
env=environ).exit_code)
self.assertEquals(
0,
gmock_test_utils.Subprocess(TEST_WITH_ON_CALL +
['--gmock_catch_leaked_mocks=0'],
env=environ).exit_code)
def testCatchesLeakedMockWhenEnabled(self):
self.assertNotEqual(
0,
gmock_test_utils.Subprocess(TEST_WITH_EXPECT_CALL +
['--gmock_catch_leaked_mocks'],
env=environ).exit_code)
self.assertNotEqual(
0,
gmock_test_utils.Subprocess(TEST_WITH_ON_CALL +
['--gmock_catch_leaked_mocks'],
env=environ).exit_code)
def testCatchesLeakedMockWhenEnabledWithExplictFlagValue(self):
self.assertNotEqual(
0,
gmock_test_utils.Subprocess(TEST_WITH_EXPECT_CALL +
['--gmock_catch_leaked_mocks=1'],
env=environ).exit_code)
def testCatchesMultipleLeakedMocks(self):
self.assertNotEqual(
0,
gmock_test_utils.Subprocess(TEST_MULTIPLE_LEAKS +
['--gmock_catch_leaked_mocks'],
env=environ).exit_code)
if __name__ == '__main__':
gmock_test_utils.Main()
// Copyright 2009, 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: wan@google.com (Zhanyong Wan)
// Google Mock - a framework for writing C++ mock classes.
//
// This program is for verifying that a leaked mock object can be
// caught by Google Mock's leak detector.
#include "gmock/gmock.h"
namespace {
using ::testing::Return;
class FooInterface {
public:
virtual ~FooInterface() {}
virtual void DoThis() = 0;
};
class MockFoo : public FooInterface {
public:
MockFoo() {}
MOCK_METHOD0(DoThis, void());
private:
GTEST_DISALLOW_COPY_AND_ASSIGN_(MockFoo);
};
TEST(LeakTest, LeakedMockWithExpectCallCausesFailureWhenLeakCheckingIsEnabled) {
MockFoo* foo = new MockFoo;
EXPECT_CALL(*foo, DoThis());
foo->DoThis();
// In order to test the leak detector, we deliberately leak foo.
// Makes sure Google Mock's leak detector can change the exit code
// to 1 even when the code is already exiting with 0.
exit(0);
}
TEST(LeakTest, LeakedMockWithOnCallCausesFailureWhenLeakCheckingIsEnabled) {
MockFoo* foo = new MockFoo;
ON_CALL(*foo, DoThis()).WillByDefault(Return());
// In order to test the leak detector, we deliberately leak foo.
// Makes sure Google Mock's leak detector can change the exit code
// to 1 even when the code is already exiting with 0.
exit(0);
}
TEST(LeakTest, CatchesMultipleLeakedMockObjects) {
MockFoo* foo1 = new MockFoo;
MockFoo* foo2 = new MockFoo;
ON_CALL(*foo1, DoThis()).WillByDefault(Return());
EXPECT_CALL(*foo2, DoThis());
foo2->DoThis();
// In order to test the leak detector, we deliberately leak foo1 and
// foo2.
// Makes sure Google Mock's leak detector can change the exit code
// to 1 even when the code is already exiting with 0.
exit(0);
}
} // namespace
// Copyright 2008, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Author: wan@google.com (Zhanyong Wan), vladl@google.com (Vlad Losev)
// Google Mock - a framework for writing C++ mock classes.
//
// This file is for verifying that various Google Mock constructs do not
// produce linker errors when instantiated in different translation units.
// Please see gmock_link_test.h for details.
#define LinkTest LinkTest2
#include "test/gmock_link_test.h"
// Copyright 2008, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Author: wan@google.com (Zhanyong Wan), vladl@google.com (Vlad Losev)
// Google Mock - a framework for writing C++ mock classes.
//
// This file is for verifying that various Google Mock constructs do not
// produce linker errors when instantiated in different translation units.
// Please see gmock_link_test.h for details.
#define LinkTest LinkTest1
#include "test/gmock_link_test.h"
// Copyright 2009, 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: vladl@google.com (Vlad Losev)
// Google Mock - a framework for writing C++ mock classes.
//
// This file tests that:
// a. A header file defining a mock class can be included in multiple
// translation units without causing a link error.
// b. Actions and matchers can be instantiated with identical template
// arguments in different translation units without causing link
// errors.
// The following constructs are currently tested:
// Actions:
// Return()
// Return(value)
// ReturnNull
// ReturnRef
// Assign
// SetArgPointee
// SetArrayArgument
// SetErrnoAndReturn
// Invoke(function)
// Invoke(object, method)
// InvokeWithoutArgs(function)
// InvokeWithoutArgs(object, method)
// InvokeArgument
// WithArg
// WithArgs
// WithoutArgs
// DoAll
// DoDefault
// IgnoreResult
// Throw
// ACTION()-generated
// ACTION_P()-generated
// ACTION_P2()-generated
// Matchers:
// _
// A
// An
// Eq
// Gt, Lt, Ge, Le, Ne
// NotNull
// Ref
// TypedEq
// DoubleEq
// FloatEq
// NanSensitiveDoubleEq
// NanSensitiveFloatEq
// ContainsRegex
// MatchesRegex
// EndsWith
// HasSubstr
// StartsWith
// StrCaseEq
// StrCaseNe
// StrEq
// StrNe
// ElementsAre
// ElementsAreArray
// ContainerEq
// Field
// Property
// ResultOf(function)
// Pointee
// Truly(predicate)
// AllOf
// AnyOf
// Not
// MatcherCast<T>
//
// Please note: this test does not verify the functioning of these
// constructs, only that the programs using them will link successfully.
//
// Implementation note:
// This test requires identical definitions of Interface and Mock to be
// included in different translation units. We achieve this by writing
// them in this header and #including it in gmock_link_test.cc and
// gmock_link2_test.cc. Because the symbols generated by the compiler for
// those constructs must be identical in both translation units,
// definitions of Interface and Mock tests MUST be kept in the SAME
// NON-ANONYMOUS namespace in this file. The test fixture class LinkTest
// is defined as LinkTest1 in gmock_link_test.cc and as LinkTest2 in
// gmock_link2_test.cc to avoid producing linker errors.
#ifndef GMOCK_TEST_GMOCK_LINK_TEST_H_
#define GMOCK_TEST_GMOCK_LINK_TEST_H_
#include "gmock/gmock.h"
#if !GTEST_OS_WINDOWS_MOBILE
# include <errno.h>
#endif
#include "gmock/internal/gmock-port.h"
#include "gtest/gtest.h"
#include <iostream>
#include <vector>
using testing::_;
using testing::A;
using testing::AllOf;
using testing::AnyOf;
using testing::Assign;
using testing::ContainerEq;
using testing::DoAll;
using testing::DoDefault;
using testing::DoubleEq;
using testing::ElementsAre;
using testing::ElementsAreArray;
using testing::EndsWith;
using testing::Eq;
using testing::Field;
using testing::FloatEq;
using testing::Ge;
using testing::Gt;
using testing::HasSubstr;
using testing::IgnoreResult;
using testing::Invoke;
using testing::InvokeArgument;
using testing::InvokeWithoutArgs;
using testing::IsNull;
using testing::Le;
using testing::Lt;
using testing::Matcher;
using testing::MatcherCast;
using testing::NanSensitiveDoubleEq;
using testing::NanSensitiveFloatEq;
using testing::Ne;
using testing::Not;
using testing::NotNull;
using testing::Pointee;
using testing::Property;
using testing::Ref;
using testing::ResultOf;
using testing::Return;
using testing::ReturnNull;
using testing::ReturnRef;
using testing::SetArgPointee;
using testing::SetArrayArgument;
using testing::StartsWith;
using testing::StrCaseEq;
using testing::StrCaseNe;
using testing::StrEq;
using testing::StrNe;
using testing::Truly;
using testing::TypedEq;
using testing::WithArg;
using testing::WithArgs;
using testing::WithoutArgs;
#if !GTEST_OS_WINDOWS_MOBILE
using testing::SetErrnoAndReturn;
#endif
#if GTEST_HAS_EXCEPTIONS
using testing::Throw;
#endif
using testing::ContainsRegex;
using testing::MatchesRegex;
class Interface {
public:
virtual ~Interface() {}
virtual void VoidFromString(char* str) = 0;
virtual char* StringFromString(char* str) = 0;
virtual int IntFromString(char* str) = 0;
virtual int& IntRefFromString(char* str) = 0;
virtual void VoidFromFunc(void(*func)(char* str)) = 0;
virtual void VoidFromIntRef(int& n) = 0; // NOLINT
virtual void VoidFromFloat(float n) = 0;
virtual void VoidFromDouble(double n) = 0;
virtual void VoidFromVector(const std::vector<int>& v) = 0;
};
class Mock: public Interface {
public:
Mock() {}
MOCK_METHOD1(VoidFromString, void(char* str));
MOCK_METHOD1(StringFromString, char*(char* str));
MOCK_METHOD1(IntFromString, int(char* str));
MOCK_METHOD1(IntRefFromString, int&(char* str));
MOCK_METHOD1(VoidFromFunc, void(void(*func)(char* str)));
MOCK_METHOD1(VoidFromIntRef, void(int& n)); // NOLINT
MOCK_METHOD1(VoidFromFloat, void(float n));
MOCK_METHOD1(VoidFromDouble, void(double n));
MOCK_METHOD1(VoidFromVector, void(const std::vector<int>& v));
private:
GTEST_DISALLOW_COPY_AND_ASSIGN_(Mock);
};
class InvokeHelper {
public:
static void StaticVoidFromVoid() {}
void VoidFromVoid() {}
static void StaticVoidFromString(char* /* str */) {}
void VoidFromString(char* /* str */) {}
static int StaticIntFromString(char* /* str */) { return 1; }
static bool StaticBoolFromString(const char* /* str */) { return true; }
};
class FieldHelper {
public:
explicit FieldHelper(int a_field) : field_(a_field) {}
int field() const { return field_; }
int field_; // NOLINT -- need external access to field_ to test
// the Field matcher.
};
// Tests the linkage of the ReturnVoid action.
TEST(LinkTest, TestReturnVoid) {
Mock mock;
EXPECT_CALL(mock, VoidFromString(_)).WillOnce(Return());
mock.VoidFromString(NULL);
}
// Tests the linkage of the Return action.
TEST(LinkTest, TestReturn) {
Mock mock;
char ch = 'x';
EXPECT_CALL(mock, StringFromString(_)).WillOnce(Return(&ch));
mock.StringFromString(NULL);
}
// Tests the linkage of the ReturnNull action.
TEST(LinkTest, TestReturnNull) {
Mock mock;
EXPECT_CALL(mock, VoidFromString(_)).WillOnce(Return());
mock.VoidFromString(NULL);
}
// Tests the linkage of the ReturnRef action.
TEST(LinkTest, TestReturnRef) {
Mock mock;
int n = 42;
EXPECT_CALL(mock, IntRefFromString(_)).WillOnce(ReturnRef(n));
mock.IntRefFromString(NULL);
}
// Tests the linkage of the Assign action.
TEST(LinkTest, TestAssign) {
Mock mock;
char ch = 'x';
EXPECT_CALL(mock, VoidFromString(_)).WillOnce(Assign(&ch, 'y'));
mock.VoidFromString(NULL);
}
// Tests the linkage of the SetArgPointee action.
TEST(LinkTest, TestSetArgPointee) {
Mock mock;
char ch = 'x';
EXPECT_CALL(mock, VoidFromString(_)).WillOnce(SetArgPointee<0>('y'));
mock.VoidFromString(&ch);
}
// Tests the linkage of the SetArrayArgument action.
TEST(LinkTest, TestSetArrayArgument) {
Mock mock;
char ch = 'x';
char ch2 = 'y';
EXPECT_CALL(mock, VoidFromString(_)).WillOnce(SetArrayArgument<0>(&ch2,
&ch2 + 1));
mock.VoidFromString(&ch);
}
#if !GTEST_OS_WINDOWS_MOBILE
// Tests the linkage of the SetErrnoAndReturn action.
TEST(LinkTest, TestSetErrnoAndReturn) {
Mock mock;
int saved_errno = errno;
EXPECT_CALL(mock, IntFromString(_)).WillOnce(SetErrnoAndReturn(1, -1));
mock.IntFromString(NULL);
errno = saved_errno;
}
#endif // !GTEST_OS_WINDOWS_MOBILE
// Tests the linkage of the Invoke(function) and Invoke(object, method) actions.
TEST(LinkTest, TestInvoke) {
Mock mock;
InvokeHelper test_invoke_helper;
EXPECT_CALL(mock, VoidFromString(_))
.WillOnce(Invoke(&InvokeHelper::StaticVoidFromString))
.WillOnce(Invoke(&test_invoke_helper, &InvokeHelper::VoidFromString));
mock.VoidFromString(NULL);
mock.VoidFromString(NULL);
}
// Tests the linkage of the InvokeWithoutArgs action.
TEST(LinkTest, TestInvokeWithoutArgs) {
Mock mock;
InvokeHelper test_invoke_helper;
EXPECT_CALL(mock, VoidFromString(_))
.WillOnce(InvokeWithoutArgs(&InvokeHelper::StaticVoidFromVoid))
.WillOnce(InvokeWithoutArgs(&test_invoke_helper,
&InvokeHelper::VoidFromVoid));
mock.VoidFromString(NULL);
mock.VoidFromString(NULL);
}
// Tests the linkage of the InvokeArgument action.
TEST(LinkTest, TestInvokeArgument) {
Mock mock;
char ch = 'x';
EXPECT_CALL(mock, VoidFromFunc(_)).WillOnce(InvokeArgument<0>(&ch));
mock.VoidFromFunc(InvokeHelper::StaticVoidFromString);
}
// Tests the linkage of the WithArg action.
TEST(LinkTest, TestWithArg) {
Mock mock;
EXPECT_CALL(mock, VoidFromString(_))
.WillOnce(WithArg<0>(Invoke(&InvokeHelper::StaticVoidFromString)));
mock.VoidFromString(NULL);
}
// Tests the linkage of the WithArgs action.
TEST(LinkTest, TestWithArgs) {
Mock mock;
EXPECT_CALL(mock, VoidFromString(_))
.WillOnce(WithArgs<0>(Invoke(&InvokeHelper::StaticVoidFromString)));
mock.VoidFromString(NULL);
}
// Tests the linkage of the WithoutArgs action.
TEST(LinkTest, TestWithoutArgs) {
Mock mock;
EXPECT_CALL(mock, VoidFromString(_)).WillOnce(WithoutArgs(Return()));
mock.VoidFromString(NULL);
}
// Tests the linkage of the DoAll action.
TEST(LinkTest, TestDoAll) {
Mock mock;
char ch = 'x';
EXPECT_CALL(mock, VoidFromString(_))
.WillOnce(DoAll(SetArgPointee<0>('y'), Return()));
mock.VoidFromString(&ch);
}
// Tests the linkage of the DoDefault action.
TEST(LinkTest, TestDoDefault) {
Mock mock;
char ch = 'x';
ON_CALL(mock, VoidFromString(_)).WillByDefault(Return());
EXPECT_CALL(mock, VoidFromString(_)).WillOnce(DoDefault());
mock.VoidFromString(&ch);
}
// Tests the linkage of the IgnoreResult action.
TEST(LinkTest, TestIgnoreResult) {
Mock mock;
EXPECT_CALL(mock, VoidFromString(_)).WillOnce(IgnoreResult(Return(42)));
mock.VoidFromString(NULL);
}
#if GTEST_HAS_EXCEPTIONS
// Tests the linkage of the Throw action.
TEST(LinkTest, TestThrow) {
Mock mock;
EXPECT_CALL(mock, VoidFromString(_)).WillOnce(Throw(42));
EXPECT_THROW(mock.VoidFromString(NULL), int);
}
#endif // GTEST_HAS_EXCEPTIONS
// The ACTION*() macros trigger warning C4100 (unreferenced formal
// parameter) in MSVC with -W4. Unfortunately they cannot be fixed in
// the macro definition, as the warnings are generated when the macro
// is expanded and macro expansion cannot contain #pragma. Therefore
// we suppress them here.
#ifdef _MSC_VER
# pragma warning(push)
# pragma warning(disable:4100)
#endif
// Tests the linkage of actions created using ACTION macro.
namespace {
ACTION(Return1) { return 1; }
}
TEST(LinkTest, TestActionMacro) {
Mock mock;
EXPECT_CALL(mock, IntFromString(_)).WillOnce(Return1());
mock.IntFromString(NULL);
}
// Tests the linkage of actions created using ACTION_P macro.
namespace {
ACTION_P(ReturnArgument, ret_value) { return ret_value; }
}
TEST(LinkTest, TestActionPMacro) {
Mock mock;
EXPECT_CALL(mock, IntFromString(_)).WillOnce(ReturnArgument(42));
mock.IntFromString(NULL);
}
// Tests the linkage of actions created using ACTION_P2 macro.
namespace {
ACTION_P2(ReturnEqualsEitherOf, first, second) {
return arg0 == first || arg0 == second;
}
}
#ifdef _MSC_VER
# pragma warning(pop)
#endif
TEST(LinkTest, TestActionP2Macro) {
Mock mock;
char ch = 'x';
EXPECT_CALL(mock, IntFromString(_))
.WillOnce(ReturnEqualsEitherOf("one", "two"));
mock.IntFromString(&ch);
}
// Tests the linkage of the "_" matcher.
TEST(LinkTest, TestMatcherAnything) {
Mock mock;
ON_CALL(mock, VoidFromString(_)).WillByDefault(Return());
}
// Tests the linkage of the A matcher.
TEST(LinkTest, TestMatcherA) {
Mock mock;
ON_CALL(mock, VoidFromString(A<char*>())).WillByDefault(Return());
}
// Tests the linkage of the Eq and the "bare value" matcher.
TEST(LinkTest, TestMatchersEq) {
Mock mock;
const char* p = "x";
ON_CALL(mock, VoidFromString(Eq(p))).WillByDefault(Return());
ON_CALL(mock, VoidFromString(const_cast<char*>("y")))
.WillByDefault(Return());
}
// Tests the linkage of the Lt, Gt, Le, Ge, and Ne matchers.
TEST(LinkTest, TestMatchersRelations) {
Mock mock;
ON_CALL(mock, VoidFromFloat(Lt(1.0f))).WillByDefault(Return());
ON_CALL(mock, VoidFromFloat(Gt(1.0f))).WillByDefault(Return());
ON_CALL(mock, VoidFromFloat(Le(1.0f))).WillByDefault(Return());
ON_CALL(mock, VoidFromFloat(Ge(1.0f))).WillByDefault(Return());
ON_CALL(mock, VoidFromFloat(Ne(1.0f))).WillByDefault(Return());
}
// Tests the linkage of the NotNull matcher.
TEST(LinkTest, TestMatcherNotNull) {
Mock mock;
ON_CALL(mock, VoidFromString(NotNull())).WillByDefault(Return());
}
// Tests the linkage of the IsNull matcher.
TEST(LinkTest, TestMatcherIsNull) {
Mock mock;
ON_CALL(mock, VoidFromString(IsNull())).WillByDefault(Return());
}
// Tests the linkage of the Ref matcher.
TEST(LinkTest, TestMatcherRef) {
Mock mock;
int a = 0;
ON_CALL(mock, VoidFromIntRef(Ref(a))).WillByDefault(Return());
}
// Tests the linkage of the TypedEq matcher.
TEST(LinkTest, TestMatcherTypedEq) {
Mock mock;
long a = 0;
ON_CALL(mock, VoidFromIntRef(TypedEq<int&>(a))).WillByDefault(Return());
}
// Tests the linkage of the FloatEq, DoubleEq, NanSensitiveFloatEq and
// NanSensitiveDoubleEq matchers.
TEST(LinkTest, TestMatchersFloatingPoint) {
Mock mock;
float a = 0;
ON_CALL(mock, VoidFromFloat(FloatEq(a))).WillByDefault(Return());
ON_CALL(mock, VoidFromDouble(DoubleEq(a))).WillByDefault(Return());
ON_CALL(mock, VoidFromFloat(NanSensitiveFloatEq(a))).WillByDefault(Return());
ON_CALL(mock, VoidFromDouble(NanSensitiveDoubleEq(a)))
.WillByDefault(Return());
}
// Tests the linkage of the ContainsRegex matcher.
TEST(LinkTest, TestMatcherContainsRegex) {
Mock mock;
ON_CALL(mock, VoidFromString(ContainsRegex(".*"))).WillByDefault(Return());
}
// Tests the linkage of the MatchesRegex matcher.
TEST(LinkTest, TestMatcherMatchesRegex) {
Mock mock;
ON_CALL(mock, VoidFromString(MatchesRegex(".*"))).WillByDefault(Return());
}
// Tests the linkage of the StartsWith, EndsWith, and HasSubstr matchers.
TEST(LinkTest, TestMatchersSubstrings) {
Mock mock;
ON_CALL(mock, VoidFromString(StartsWith("a"))).WillByDefault(Return());
ON_CALL(mock, VoidFromString(EndsWith("c"))).WillByDefault(Return());
ON_CALL(mock, VoidFromString(HasSubstr("b"))).WillByDefault(Return());
}
// Tests the linkage of the StrEq, StrNe, StrCaseEq, and StrCaseNe matchers.
TEST(LinkTest, TestMatchersStringEquality) {
Mock mock;
ON_CALL(mock, VoidFromString(StrEq("a"))).WillByDefault(Return());
ON_CALL(mock, VoidFromString(StrNe("a"))).WillByDefault(Return());
ON_CALL(mock, VoidFromString(StrCaseEq("a"))).WillByDefault(Return());
ON_CALL(mock, VoidFromString(StrCaseNe("a"))).WillByDefault(Return());
}
// Tests the linkage of the ElementsAre matcher.
TEST(LinkTest, TestMatcherElementsAre) {
Mock mock;
ON_CALL(mock, VoidFromVector(ElementsAre('a', _))).WillByDefault(Return());
}
// Tests the linkage of the ElementsAreArray matcher.
TEST(LinkTest, TestMatcherElementsAreArray) {
Mock mock;
char arr[] = { 'a', 'b' };
ON_CALL(mock, VoidFromVector(ElementsAreArray(arr))).WillByDefault(Return());
}
// Tests the linkage of the ContainerEq matcher.
TEST(LinkTest, TestMatcherContainerEq) {
Mock mock;
std::vector<int> v;
ON_CALL(mock, VoidFromVector(ContainerEq(v))).WillByDefault(Return());
}
// Tests the linkage of the Field matcher.
TEST(LinkTest, TestMatcherField) {
FieldHelper helper(0);
Matcher<const FieldHelper&> m = Field(&FieldHelper::field_, Eq(0));
EXPECT_TRUE(m.Matches(helper));
Matcher<const FieldHelper*> m2 = Field(&FieldHelper::field_, Eq(0));
EXPECT_TRUE(m2.Matches(&helper));
}
// Tests the linkage of the Property matcher.
TEST(LinkTest, TestMatcherProperty) {
FieldHelper helper(0);
Matcher<const FieldHelper&> m = Property(&FieldHelper::field, Eq(0));
EXPECT_TRUE(m.Matches(helper));
Matcher<const FieldHelper*> m2 = Property(&FieldHelper::field, Eq(0));
EXPECT_TRUE(m2.Matches(&helper));
}
// Tests the linkage of the ResultOf matcher.
TEST(LinkTest, TestMatcherResultOf) {
Matcher<char*> m = ResultOf(&InvokeHelper::StaticIntFromString, Eq(1));
EXPECT_TRUE(m.Matches(NULL));
}
// Tests the linkage of the ResultOf matcher.
TEST(LinkTest, TestMatcherPointee) {
int n = 1;
Matcher<int*> m = Pointee(Eq(1));
EXPECT_TRUE(m.Matches(&n));
}
// Tests the linkage of the Truly matcher.
TEST(LinkTest, TestMatcherTruly) {
Matcher<const char*> m = Truly(&InvokeHelper::StaticBoolFromString);
EXPECT_TRUE(m.Matches(NULL));
}
// Tests the linkage of the AllOf matcher.
TEST(LinkTest, TestMatcherAllOf) {
Matcher<int> m = AllOf(_, Eq(1));
EXPECT_TRUE(m.Matches(1));
}
// Tests the linkage of the AnyOf matcher.
TEST(LinkTest, TestMatcherAnyOf) {
Matcher<int> m = AnyOf(_, Eq(1));
EXPECT_TRUE(m.Matches(1));
}
// Tests the linkage of the Not matcher.
TEST(LinkTest, TestMatcherNot) {
Matcher<int> m = Not(_);
EXPECT_FALSE(m.Matches(1));
}
// Tests the linkage of the MatcherCast<T>() function.
TEST(LinkTest, TestMatcherCast) {
Matcher<const char*> m = MatcherCast<const char*>(_);
EXPECT_TRUE(m.Matches(NULL));
}
#endif // GMOCK_TEST_GMOCK_LINK_TEST_H_
#!/usr/bin/env python
#
# Copyright 2008, Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Tests the text output of Google C++ Mocking Framework.
SYNOPSIS
gmock_output_test.py --build_dir=BUILD/DIR --gengolden
# where BUILD/DIR contains the built gmock_output_test_ file.
gmock_output_test.py --gengolden
gmock_output_test.py
"""
__author__ = 'wan@google.com (Zhanyong Wan)'
import os
import re
import sys
import gmock_test_utils
# The flag for generating the golden file
GENGOLDEN_FLAG = '--gengolden'
PROGRAM_PATH = gmock_test_utils.GetTestExecutablePath('gmock_output_test_')
COMMAND = [PROGRAM_PATH, '--gtest_stack_trace_depth=0', '--gtest_print_time=0']
GOLDEN_NAME = 'gmock_output_test_golden.txt'
GOLDEN_PATH = os.path.join(gmock_test_utils.GetSourceDir(), GOLDEN_NAME)
def ToUnixLineEnding(s):
"""Changes all Windows/Mac line endings in s to UNIX line endings."""
return s.replace('\r\n', '\n').replace('\r', '\n')
def RemoveReportHeaderAndFooter(output):
"""Removes Google Test result report's header and footer from the output."""
output = re.sub(r'.*gtest_main.*\n', '', output)
output = re.sub(r'\[.*\d+ tests.*\n', '', output)
output = re.sub(r'\[.* test environment .*\n', '', output)
output = re.sub(r'\[=+\] \d+ tests .* ran.*', '', output)
output = re.sub(r'.* FAILED TESTS\n', '', output)
return output
def RemoveLocations(output):
"""Removes all file location info from a Google Test program's output.
Args:
output: the output of a Google Test program.
Returns:
output with all file location info (in the form of
'DIRECTORY/FILE_NAME:LINE_NUMBER: 'or
'DIRECTORY\\FILE_NAME(LINE_NUMBER): ') replaced by
'FILE:#: '.
"""
return re.sub(r'.*[/\\](.+)(\:\d+|\(\d+\))\:', 'FILE:#:', output)
def NormalizeErrorMarker(output):
"""Normalizes the error marker, which is different on Windows vs on Linux."""
return re.sub(r' error: ', ' Failure\n', output)
def RemoveMemoryAddresses(output):
"""Removes memory addresses from the test output."""
return re.sub(r'@\w+', '@0x#', output)
def RemoveTestNamesOfLeakedMocks(output):
"""Removes the test names of leaked mock objects from the test output."""
return re.sub(r'\(used in test .+\) ', '', output)
def GetLeakyTests(output):
"""Returns a list of test names that leak mock objects."""
# findall() returns a list of all matches of the regex in output.
# For example, if '(used in test FooTest.Bar)' is in output, the
# list will contain 'FooTest.Bar'.
return re.findall(r'\(used in test (.+)\)', output)
def GetNormalizedOutputAndLeakyTests(output):
"""Normalizes the output of gmock_output_test_.
Args:
output: The test output.
Returns:
A tuple (the normalized test output, the list of test names that have
leaked mocks).
"""
output = ToUnixLineEnding(output)
output = RemoveReportHeaderAndFooter(output)
output = NormalizeErrorMarker(output)
output = RemoveLocations(output)
output = RemoveMemoryAddresses(output)
return (RemoveTestNamesOfLeakedMocks(output), GetLeakyTests(output))
def GetShellCommandOutput(cmd):
"""Runs a command in a sub-process, and returns its STDOUT in a string."""
return gmock_test_utils.Subprocess(cmd, capture_stderr=False).output
def GetNormalizedCommandOutputAndLeakyTests(cmd):
"""Runs a command and returns its normalized output and a list of leaky tests.
Args:
cmd: the shell command.
"""
# Disables exception pop-ups on Windows.
os.environ['GTEST_CATCH_EXCEPTIONS'] = '1'
return GetNormalizedOutputAndLeakyTests(GetShellCommandOutput(cmd))
class GMockOutputTest(gmock_test_utils.TestCase):
def testOutput(self):
(output, leaky_tests) = GetNormalizedCommandOutputAndLeakyTests(COMMAND)
golden_file = open(GOLDEN_PATH, 'rb')
golden = golden_file.read()
golden_file.close()
# The normalized output should match the golden file.
self.assertEquals(golden, output)
# The raw output should contain 2 leaked mock object errors for
# test GMockOutputTest.CatchesLeakedMocks.
self.assertEquals(['GMockOutputTest.CatchesLeakedMocks',
'GMockOutputTest.CatchesLeakedMocks'],
leaky_tests)
if __name__ == '__main__':
if sys.argv[1:] == [GENGOLDEN_FLAG]:
(output, _) = GetNormalizedCommandOutputAndLeakyTests(COMMAND)
golden_file = open(GOLDEN_PATH, 'wb')
golden_file.write(output)
golden_file.close()
else:
gmock_test_utils.Main()
// Copyright 2008, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Author: wan@google.com (Zhanyong Wan)
// Tests Google Mock's output in various scenarios. This ensures that
// Google Mock's messages are readable and useful.
#include "gmock/gmock.h"
#include <stdio.h>
#include <string>
#include "gtest/gtest.h"
using testing::_;
using testing::AnyNumber;
using testing::Ge;
using testing::InSequence;
using testing::NaggyMock;
using testing::Ref;
using testing::Return;
using testing::Sequence;
class MockFoo {
public:
MockFoo() {}
MOCK_METHOD3(Bar, char(const std::string& s, int i, double x));
MOCK_METHOD2(Bar2, bool(int x, int y));
MOCK_METHOD2(Bar3, void(int x, int y));
private:
GTEST_DISALLOW_COPY_AND_ASSIGN_(MockFoo);
};
class GMockOutputTest : public testing::Test {
protected:
NaggyMock<MockFoo> foo_;
};
TEST_F(GMockOutputTest, ExpectedCall) {
testing::GMOCK_FLAG(verbose) = "info";
EXPECT_CALL(foo_, Bar2(0, _));
foo_.Bar2(0, 0); // Expected call
testing::GMOCK_FLAG(verbose) = "warning";
}
TEST_F(GMockOutputTest, ExpectedCallToVoidFunction) {
testing::GMOCK_FLAG(verbose) = "info";
EXPECT_CALL(foo_, Bar3(0, _));
foo_.Bar3(0, 0); // Expected call
testing::GMOCK_FLAG(verbose) = "warning";
}
TEST_F(GMockOutputTest, ExplicitActionsRunOut) {
EXPECT_CALL(foo_, Bar2(_, _))
.Times(2)
.WillOnce(Return(false));
foo_.Bar2(2, 2);
foo_.Bar2(1, 1); // Explicit actions in EXPECT_CALL run out.
}
TEST_F(GMockOutputTest, UnexpectedCall) {
EXPECT_CALL(foo_, Bar2(0, _));
foo_.Bar2(1, 0); // Unexpected call
foo_.Bar2(0, 0); // Expected call
}
TEST_F(GMockOutputTest, UnexpectedCallToVoidFunction) {
EXPECT_CALL(foo_, Bar3(0, _));
foo_.Bar3(1, 0); // Unexpected call
foo_.Bar3(0, 0); // Expected call
}
TEST_F(GMockOutputTest, ExcessiveCall) {
EXPECT_CALL(foo_, Bar2(0, _));
foo_.Bar2(0, 0); // Expected call
foo_.Bar2(0, 1); // Excessive call
}
TEST_F(GMockOutputTest, ExcessiveCallToVoidFunction) {
EXPECT_CALL(foo_, Bar3(0, _));
foo_.Bar3(0, 0); // Expected call
foo_.Bar3(0, 1); // Excessive call
}
TEST_F(GMockOutputTest, UninterestingCall) {
foo_.Bar2(0, 1); // Uninteresting call
}
TEST_F(GMockOutputTest, UninterestingCallToVoidFunction) {
foo_.Bar3(0, 1); // Uninteresting call
}
TEST_F(GMockOutputTest, RetiredExpectation) {
EXPECT_CALL(foo_, Bar2(_, _))
.RetiresOnSaturation();
EXPECT_CALL(foo_, Bar2(0, 0));
foo_.Bar2(1, 1);
foo_.Bar2(1, 1); // Matches a retired expectation
foo_.Bar2(0, 0);
}
TEST_F(GMockOutputTest, UnsatisfiedPrerequisite) {
{
InSequence s;
EXPECT_CALL(foo_, Bar(_, 0, _));
EXPECT_CALL(foo_, Bar2(0, 0));
EXPECT_CALL(foo_, Bar2(1, _));
}
foo_.Bar2(1, 0); // Has one immediate unsatisfied pre-requisite
foo_.Bar("Hi", 0, 0);
foo_.Bar2(0, 0);
foo_.Bar2(1, 0);
}
TEST_F(GMockOutputTest, UnsatisfiedPrerequisites) {
Sequence s1, s2;
EXPECT_CALL(foo_, Bar(_, 0, _))
.InSequence(s1);
EXPECT_CALL(foo_, Bar2(0, 0))
.InSequence(s2);
EXPECT_CALL(foo_, Bar2(1, _))
.InSequence(s1, s2);
foo_.Bar2(1, 0); // Has two immediate unsatisfied pre-requisites
foo_.Bar("Hi", 0, 0);
foo_.Bar2(0, 0);
foo_.Bar2(1, 0);
}
TEST_F(GMockOutputTest, UnsatisfiedWith) {
EXPECT_CALL(foo_, Bar2(_, _)).With(Ge());
}
TEST_F(GMockOutputTest, UnsatisfiedExpectation) {
EXPECT_CALL(foo_, Bar(_, _, _));
EXPECT_CALL(foo_, Bar2(0, _))
.Times(2);
foo_.Bar2(0, 1);
}
TEST_F(GMockOutputTest, MismatchArguments) {
const std::string s = "Hi";
EXPECT_CALL(foo_, Bar(Ref(s), _, Ge(0)));
foo_.Bar("Ho", 0, -0.1); // Mismatch arguments
foo_.Bar(s, 0, 0);
}
TEST_F(GMockOutputTest, MismatchWith) {
EXPECT_CALL(foo_, Bar2(Ge(2), Ge(1)))
.With(Ge());
foo_.Bar2(2, 3); // Mismatch With()
foo_.Bar2(2, 1);
}
TEST_F(GMockOutputTest, MismatchArgumentsAndWith) {
EXPECT_CALL(foo_, Bar2(Ge(2), Ge(1)))
.With(Ge());
foo_.Bar2(1, 3); // Mismatch arguments and mismatch With()
foo_.Bar2(2, 1);
}
TEST_F(GMockOutputTest, UnexpectedCallWithDefaultAction) {
ON_CALL(foo_, Bar2(_, _))
.WillByDefault(Return(true)); // Default action #1
ON_CALL(foo_, Bar2(1, _))
.WillByDefault(Return(false)); // Default action #2
EXPECT_CALL(foo_, Bar2(2, 2));
foo_.Bar2(1, 0); // Unexpected call, takes default action #2.
foo_.Bar2(0, 0); // Unexpected call, takes default action #1.
foo_.Bar2(2, 2); // Expected call.
}
TEST_F(GMockOutputTest, ExcessiveCallWithDefaultAction) {
ON_CALL(foo_, Bar2(_, _))
.WillByDefault(Return(true)); // Default action #1
ON_CALL(foo_, Bar2(1, _))
.WillByDefault(Return(false)); // Default action #2
EXPECT_CALL(foo_, Bar2(2, 2));
EXPECT_CALL(foo_, Bar2(1, 1));
foo_.Bar2(2, 2); // Expected call.
foo_.Bar2(2, 2); // Excessive call, takes default action #1.
foo_.Bar2(1, 1); // Expected call.
foo_.Bar2(1, 1); // Excessive call, takes default action #2.
}
TEST_F(GMockOutputTest, UninterestingCallWithDefaultAction) {
ON_CALL(foo_, Bar2(_, _))
.WillByDefault(Return(true)); // Default action #1
ON_CALL(foo_, Bar2(1, _))
.WillByDefault(Return(false)); // Default action #2
foo_.Bar2(2, 2); // Uninteresting call, takes default action #1.
foo_.Bar2(1, 1); // Uninteresting call, takes default action #2.
}
TEST_F(GMockOutputTest, ExplicitActionsRunOutWithDefaultAction) {
ON_CALL(foo_, Bar2(_, _))
.WillByDefault(Return(true)); // Default action #1
EXPECT_CALL(foo_, Bar2(_, _))
.Times(2)
.WillOnce(Return(false));
foo_.Bar2(2, 2);
foo_.Bar2(1, 1); // Explicit actions in EXPECT_CALL run out.
}
TEST_F(GMockOutputTest, CatchesLeakedMocks) {
MockFoo* foo1 = new MockFoo;
MockFoo* foo2 = new MockFoo;
// Invokes ON_CALL on foo1.
ON_CALL(*foo1, Bar(_, _, _)).WillByDefault(Return('a'));
// Invokes EXPECT_CALL on foo2.
EXPECT_CALL(*foo2, Bar2(_, _));
EXPECT_CALL(*foo2, Bar2(1, _));
EXPECT_CALL(*foo2, Bar3(_, _)).Times(AnyNumber());
foo2->Bar2(2, 1);
foo2->Bar2(1, 1);
// Both foo1 and foo2 are deliberately leaked.
}
void TestCatchesLeakedMocksInAdHocTests() {
MockFoo* foo = new MockFoo;
// Invokes EXPECT_CALL on foo.
EXPECT_CALL(*foo, Bar2(_, _));
foo->Bar2(2, 1);
// foo is deliberately leaked.
}
int main(int argc, char **argv) {
testing::InitGoogleMock(&argc, argv);
// Ensures that the tests pass no matter what value of
// --gmock_catch_leaked_mocks and --gmock_verbose the user specifies.
testing::GMOCK_FLAG(catch_leaked_mocks) = true;
testing::GMOCK_FLAG(verbose) = "warning";
TestCatchesLeakedMocksInAdHocTests();
return RUN_ALL_TESTS();
}
[ RUN ] GMockOutputTest.ExpectedCall
FILE:#: EXPECT_CALL(foo_, Bar2(0, _)) invoked
Stack trace:
FILE:#: Mock function call matches EXPECT_CALL(foo_, Bar2(0, _))...
Function call: Bar2(0, 0)
Returns: false
Stack trace:
[ OK ] GMockOutputTest.ExpectedCall
[ RUN ] GMockOutputTest.ExpectedCallToVoidFunction
FILE:#: EXPECT_CALL(foo_, Bar3(0, _)) invoked
Stack trace:
FILE:#: Mock function call matches EXPECT_CALL(foo_, Bar3(0, _))...
Function call: Bar3(0, 0)
Stack trace:
[ OK ] GMockOutputTest.ExpectedCallToVoidFunction
[ RUN ] GMockOutputTest.ExplicitActionsRunOut
GMOCK WARNING:
FILE:#: Too few actions specified in EXPECT_CALL(foo_, Bar2(_, _))...
Expected to be called twice, but has only 1 WillOnce().
GMOCK WARNING:
FILE:#: Actions ran out in EXPECT_CALL(foo_, Bar2(_, _))...
Called 2 times, but only 1 WillOnce() is specified - returning default value.
Stack trace:
[ OK ] GMockOutputTest.ExplicitActionsRunOut
[ RUN ] GMockOutputTest.UnexpectedCall
unknown file: Failure
Unexpected mock function call - returning default value.
Function call: Bar2(1, 0)
Returns: false
Google Mock tried the following 1 expectation, but it didn't match:
FILE:#: EXPECT_CALL(foo_, Bar2(0, _))...
Expected arg #0: is equal to 0
Actual: 1
Expected: to be called once
Actual: never called - unsatisfied and active
[ FAILED ] GMockOutputTest.UnexpectedCall
[ RUN ] GMockOutputTest.UnexpectedCallToVoidFunction
unknown file: Failure
Unexpected mock function call - returning directly.
Function call: Bar3(1, 0)
Google Mock tried the following 1 expectation, but it didn't match:
FILE:#: EXPECT_CALL(foo_, Bar3(0, _))...
Expected arg #0: is equal to 0
Actual: 1
Expected: to be called once
Actual: never called - unsatisfied and active
[ FAILED ] GMockOutputTest.UnexpectedCallToVoidFunction
[ RUN ] GMockOutputTest.ExcessiveCall
FILE:#: Failure
Mock function called more times than expected - returning default value.
Function call: Bar2(0, 1)
Returns: false
Expected: to be called once
Actual: called twice - over-saturated and active
[ FAILED ] GMockOutputTest.ExcessiveCall
[ RUN ] GMockOutputTest.ExcessiveCallToVoidFunction
FILE:#: Failure
Mock function called more times than expected - returning directly.
Function call: Bar3(0, 1)
Expected: to be called once
Actual: called twice - over-saturated and active
[ FAILED ] GMockOutputTest.ExcessiveCallToVoidFunction
[ RUN ] GMockOutputTest.UninterestingCall
GMOCK WARNING:
Uninteresting mock function call - returning default value.
Function call: Bar2(0, 1)
Returns: false
Stack trace:
[ OK ] GMockOutputTest.UninterestingCall
[ RUN ] GMockOutputTest.UninterestingCallToVoidFunction
GMOCK WARNING:
Uninteresting mock function call - returning directly.
Function call: Bar3(0, 1)
Stack trace:
[ OK ] GMockOutputTest.UninterestingCallToVoidFunction
[ RUN ] GMockOutputTest.RetiredExpectation
unknown file: Failure
Unexpected mock function call - returning default value.
Function call: Bar2(1, 1)
Returns: false
Google Mock tried the following 2 expectations, but none matched:
FILE:#: tried expectation #0: EXPECT_CALL(foo_, Bar2(_, _))...
Expected: the expectation is active
Actual: it is retired
Expected: to be called once
Actual: called once - saturated and retired
FILE:#: tried expectation #1: EXPECT_CALL(foo_, Bar2(0, 0))...
Expected arg #0: is equal to 0
Actual: 1
Expected arg #1: is equal to 0
Actual: 1
Expected: to be called once
Actual: never called - unsatisfied and active
[ FAILED ] GMockOutputTest.RetiredExpectation
[ RUN ] GMockOutputTest.UnsatisfiedPrerequisite
unknown file: Failure
Unexpected mock function call - returning default value.
Function call: Bar2(1, 0)
Returns: false
Google Mock tried the following 2 expectations, but none matched:
FILE:#: tried expectation #0: EXPECT_CALL(foo_, Bar2(0, 0))...
Expected arg #0: is equal to 0
Actual: 1
Expected: to be called once
Actual: never called - unsatisfied and active
FILE:#: tried expectation #1: EXPECT_CALL(foo_, Bar2(1, _))...
Expected: all pre-requisites are satisfied
Actual: the following immediate pre-requisites are not satisfied:
FILE:#: pre-requisite #0
(end of pre-requisites)
Expected: to be called once
Actual: never called - unsatisfied and active
[ FAILED ] GMockOutputTest.UnsatisfiedPrerequisite
[ RUN ] GMockOutputTest.UnsatisfiedPrerequisites
unknown file: Failure
Unexpected mock function call - returning default value.
Function call: Bar2(1, 0)
Returns: false
Google Mock tried the following 2 expectations, but none matched:
FILE:#: tried expectation #0: EXPECT_CALL(foo_, Bar2(0, 0))...
Expected arg #0: is equal to 0
Actual: 1
Expected: to be called once
Actual: never called - unsatisfied and active
FILE:#: tried expectation #1: EXPECT_CALL(foo_, Bar2(1, _))...
Expected: all pre-requisites are satisfied
Actual: the following immediate pre-requisites are not satisfied:
FILE:#: pre-requisite #0
FILE:#: pre-requisite #1
(end of pre-requisites)
Expected: to be called once
Actual: never called - unsatisfied and active
[ FAILED ] GMockOutputTest.UnsatisfiedPrerequisites
[ RUN ] GMockOutputTest.UnsatisfiedWith
FILE:#: Failure
Actual function call count doesn't match EXPECT_CALL(foo_, Bar2(_, _))...
Expected args: are a pair where the first >= the second
Expected: to be called once
Actual: never called - unsatisfied and active
[ FAILED ] GMockOutputTest.UnsatisfiedWith
[ RUN ] GMockOutputTest.UnsatisfiedExpectation
FILE:#: Failure
Actual function call count doesn't match EXPECT_CALL(foo_, Bar2(0, _))...
Expected: to be called twice
Actual: called once - unsatisfied and active
FILE:#: Failure
Actual function call count doesn't match EXPECT_CALL(foo_, Bar(_, _, _))...
Expected: to be called once
Actual: never called - unsatisfied and active
[ FAILED ] GMockOutputTest.UnsatisfiedExpectation
[ RUN ] GMockOutputTest.MismatchArguments
unknown file: Failure
Unexpected mock function call - returning default value.
Function call: Bar(@0x# "Ho", 0, -0.1)
Returns: '\0'
Google Mock tried the following 1 expectation, but it didn't match:
FILE:#: EXPECT_CALL(foo_, Bar(Ref(s), _, Ge(0)))...
Expected arg #0: references the variable @0x# "Hi"
Actual: "Ho", which is located @0x#
Expected arg #2: is >= 0
Actual: -0.1
Expected: to be called once
Actual: never called - unsatisfied and active
[ FAILED ] GMockOutputTest.MismatchArguments
[ RUN ] GMockOutputTest.MismatchWith
unknown file: Failure
Unexpected mock function call - returning default value.
Function call: Bar2(2, 3)
Returns: false
Google Mock tried the following 1 expectation, but it didn't match:
FILE:#: EXPECT_CALL(foo_, Bar2(Ge(2), Ge(1)))...
Expected args: are a pair where the first >= the second
Actual: don't match
Expected: to be called once
Actual: never called - unsatisfied and active
[ FAILED ] GMockOutputTest.MismatchWith
[ RUN ] GMockOutputTest.MismatchArgumentsAndWith
unknown file: Failure
Unexpected mock function call - returning default value.
Function call: Bar2(1, 3)
Returns: false
Google Mock tried the following 1 expectation, but it didn't match:
FILE:#: EXPECT_CALL(foo_, Bar2(Ge(2), Ge(1)))...
Expected arg #0: is >= 2
Actual: 1
Expected args: are a pair where the first >= the second
Actual: don't match
Expected: to be called once
Actual: never called - unsatisfied and active
[ FAILED ] GMockOutputTest.MismatchArgumentsAndWith
[ RUN ] GMockOutputTest.UnexpectedCallWithDefaultAction
unknown file: Failure
Unexpected mock function call - taking default action specified at:
FILE:#:
Function call: Bar2(1, 0)
Returns: false
Google Mock tried the following 1 expectation, but it didn't match:
FILE:#: EXPECT_CALL(foo_, Bar2(2, 2))...
Expected arg #0: is equal to 2
Actual: 1
Expected arg #1: is equal to 2
Actual: 0
Expected: to be called once
Actual: never called - unsatisfied and active
unknown file: Failure
Unexpected mock function call - taking default action specified at:
FILE:#:
Function call: Bar2(0, 0)
Returns: true
Google Mock tried the following 1 expectation, but it didn't match:
FILE:#: EXPECT_CALL(foo_, Bar2(2, 2))...
Expected arg #0: is equal to 2
Actual: 0
Expected arg #1: is equal to 2
Actual: 0
Expected: to be called once
Actual: never called - unsatisfied and active
[ FAILED ] GMockOutputTest.UnexpectedCallWithDefaultAction
[ RUN ] GMockOutputTest.ExcessiveCallWithDefaultAction
FILE:#: Failure
Mock function called more times than expected - taking default action specified at:
FILE:#:
Function call: Bar2(2, 2)
Returns: true
Expected: to be called once
Actual: called twice - over-saturated and active
FILE:#: Failure
Mock function called more times than expected - taking default action specified at:
FILE:#:
Function call: Bar2(1, 1)
Returns: false
Expected: to be called once
Actual: called twice - over-saturated and active
[ FAILED ] GMockOutputTest.ExcessiveCallWithDefaultAction
[ RUN ] GMockOutputTest.UninterestingCallWithDefaultAction
GMOCK WARNING:
Uninteresting mock function call - taking default action specified at:
FILE:#:
Function call: Bar2(2, 2)
Returns: true
Stack trace:
GMOCK WARNING:
Uninteresting mock function call - taking default action specified at:
FILE:#:
Function call: Bar2(1, 1)
Returns: false
Stack trace:
[ OK ] GMockOutputTest.UninterestingCallWithDefaultAction
[ RUN ] GMockOutputTest.ExplicitActionsRunOutWithDefaultAction
GMOCK WARNING:
FILE:#: Too few actions specified in EXPECT_CALL(foo_, Bar2(_, _))...
Expected to be called twice, but has only 1 WillOnce().
GMOCK WARNING:
FILE:#: Actions ran out in EXPECT_CALL(foo_, Bar2(_, _))...
Called 2 times, but only 1 WillOnce() is specified - taking default action specified at:
FILE:#:
Stack trace:
[ OK ] GMockOutputTest.ExplicitActionsRunOutWithDefaultAction
[ RUN ] GMockOutputTest.CatchesLeakedMocks
[ OK ] GMockOutputTest.CatchesLeakedMocks
[ FAILED ] GMockOutputTest.UnexpectedCall
[ FAILED ] GMockOutputTest.UnexpectedCallToVoidFunction
[ FAILED ] GMockOutputTest.ExcessiveCall
[ FAILED ] GMockOutputTest.ExcessiveCallToVoidFunction
[ FAILED ] GMockOutputTest.RetiredExpectation
[ FAILED ] GMockOutputTest.UnsatisfiedPrerequisite
[ FAILED ] GMockOutputTest.UnsatisfiedPrerequisites
[ FAILED ] GMockOutputTest.UnsatisfiedWith
[ FAILED ] GMockOutputTest.UnsatisfiedExpectation
[ FAILED ] GMockOutputTest.MismatchArguments
[ FAILED ] GMockOutputTest.MismatchWith
[ FAILED ] GMockOutputTest.MismatchArgumentsAndWith
[ FAILED ] GMockOutputTest.UnexpectedCallWithDefaultAction
[ FAILED ] GMockOutputTest.ExcessiveCallWithDefaultAction
FILE:#: ERROR: this mock object should be deleted but never is. Its address is @0x#.
FILE:#: ERROR: this mock object should be deleted but never is. Its address is @0x#.
FILE:#: ERROR: this mock object should be deleted but never is. Its address is @0x#.
ERROR: 3 leaked mock objects found at program exit.
// 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.
//
// Author: wan@google.com (Zhanyong Wan)
// Tests that Google Mock constructs can be used in a large number of
// threads concurrently.
#include "gmock/gmock.h"
#include "gtest/gtest.h"
namespace testing {
namespace {
// From <gtest/internal/gtest-port.h>.
using ::testing::internal::ThreadWithParam;
// The maximum number of test threads (not including helper threads)
// to create.
const int kMaxTestThreads = 50;
// How many times to repeat a task in a test thread.
const int kRepeat = 50;
class MockFoo {
public:
MOCK_METHOD1(Bar, int(int n)); // NOLINT
MOCK_METHOD2(Baz, char(const char* s1, const internal::string& s2)); // NOLINT
};
// Helper for waiting for the given thread to finish and then deleting it.
template <typename T>
void JoinAndDelete(ThreadWithParam<T>* t) {
t->Join();
delete t;
}
using internal::linked_ptr;
// Helper classes for testing using linked_ptr concurrently.
class Base {
public:
explicit Base(int a_x) : x_(a_x) {}
virtual ~Base() {}
int x() const { return x_; }
private:
int x_;
};
class Derived1 : public Base {
public:
Derived1(int a_x, int a_y) : Base(a_x), y_(a_y) {}
int y() const { return y_; }
private:
int y_;
};
class Derived2 : public Base {
public:
Derived2(int a_x, int a_z) : Base(a_x), z_(a_z) {}
int z() const { return z_; }
private:
int z_;
};
linked_ptr<Derived1> pointer1(new Derived1(1, 2));
linked_ptr<Derived2> pointer2(new Derived2(3, 4));
struct Dummy {};
// Tests that we can copy from a linked_ptr and read it concurrently.
void TestConcurrentCopyAndReadLinkedPtr(Dummy /* dummy */) {
// Reads pointer1 and pointer2 while they are being copied from in
// another thread.
EXPECT_EQ(1, pointer1->x());
EXPECT_EQ(2, pointer1->y());
EXPECT_EQ(3, pointer2->x());
EXPECT_EQ(4, pointer2->z());
// Copies from pointer1.
linked_ptr<Derived1> p1(pointer1);
EXPECT_EQ(1, p1->x());
EXPECT_EQ(2, p1->y());
// Assigns from pointer2 where the LHS was empty.
linked_ptr<Base> p2;
p2 = pointer1;
EXPECT_EQ(1, p2->x());
// Assigns from pointer2 where the LHS was not empty.
p2 = pointer2;
EXPECT_EQ(3, p2->x());
}
const linked_ptr<Derived1> p0(new Derived1(1, 2));
// Tests that we can concurrently modify two linked_ptrs that point to
// the same object.
void TestConcurrentWriteToEqualLinkedPtr(Dummy /* dummy */) {
// p1 and p2 point to the same, shared thing. One thread resets p1.
// Another thread assigns to p2. This will cause the same
// underlying "ring" to be updated concurrently.
linked_ptr<Derived1> p1(p0);
linked_ptr<Derived1> p2(p0);
EXPECT_EQ(1, p1->x());
EXPECT_EQ(2, p1->y());
EXPECT_EQ(1, p2->x());
EXPECT_EQ(2, p2->y());
p1.reset();
p2 = p0;
EXPECT_EQ(1, p2->x());
EXPECT_EQ(2, p2->y());
}
// Tests that different mock objects can be used in their respective
// threads. This should generate no Google Test failure.
void TestConcurrentMockObjects(Dummy /* dummy */) {
// Creates a mock and does some typical operations on it.
MockFoo foo;
ON_CALL(foo, Bar(_))
.WillByDefault(Return(1));
ON_CALL(foo, Baz(_, _))
.WillByDefault(Return('b'));
ON_CALL(foo, Baz(_, "you"))
.WillByDefault(Return('a'));
EXPECT_CALL(foo, Bar(0))
.Times(AtMost(3));
EXPECT_CALL(foo, Baz(_, _));
EXPECT_CALL(foo, Baz("hi", "you"))
.WillOnce(Return('z'))
.WillRepeatedly(DoDefault());
EXPECT_EQ(1, foo.Bar(0));
EXPECT_EQ(1, foo.Bar(0));
EXPECT_EQ('z', foo.Baz("hi", "you"));
EXPECT_EQ('a', foo.Baz("hi", "you"));
EXPECT_EQ('b', foo.Baz("hi", "me"));
}
// Tests invoking methods of the same mock object in multiple threads.
struct Helper1Param {
MockFoo* mock_foo;
int* count;
};
void Helper1(Helper1Param param) {
for (int i = 0; i < kRepeat; i++) {
const char ch = param.mock_foo->Baz("a", "b");
if (ch == 'a') {
// It was an expected call.
(*param.count)++;
} else {
// It was an excessive call.
EXPECT_EQ('\0', ch);
}
// An unexpected call.
EXPECT_EQ('\0', param.mock_foo->Baz("x", "y")) << "Expected failure.";
// An uninteresting call.
EXPECT_EQ(1, param.mock_foo->Bar(5));
}
}
// This should generate 3*kRepeat + 1 failures in total.
void TestConcurrentCallsOnSameObject(Dummy /* dummy */) {
MockFoo foo;
ON_CALL(foo, Bar(_))
.WillByDefault(Return(1));
EXPECT_CALL(foo, Baz(_, "b"))
.Times(kRepeat)
.WillRepeatedly(Return('a'));
EXPECT_CALL(foo, Baz(_, "c")); // Expected to be unsatisfied.
// This chunk of code should generate kRepeat failures about
// excessive calls, and 2*kRepeat failures about unexpected calls.
int count1 = 0;
const Helper1Param param = { &foo, &count1 };
ThreadWithParam<Helper1Param>* const t =
new ThreadWithParam<Helper1Param>(Helper1, param, NULL);
int count2 = 0;
const Helper1Param param2 = { &foo, &count2 };
Helper1(param2);
JoinAndDelete(t);
EXPECT_EQ(kRepeat, count1 + count2);
// foo's destructor should generate one failure about unsatisfied
// expectation.
}
// Tests using the same mock object in multiple threads when the
// expectations are partially ordered.
void Helper2(MockFoo* foo) {
for (int i = 0; i < kRepeat; i++) {
foo->Bar(2);
foo->Bar(3);
}
}
// This should generate no Google Test failures.
void TestPartiallyOrderedExpectationsWithThreads(Dummy /* dummy */) {
MockFoo foo;
Sequence s1, s2;
{
InSequence dummy;
EXPECT_CALL(foo, Bar(0));
EXPECT_CALL(foo, Bar(1))
.InSequence(s1, s2);
}
EXPECT_CALL(foo, Bar(2))
.Times(2*kRepeat)
.InSequence(s1)
.RetiresOnSaturation();
EXPECT_CALL(foo, Bar(3))
.Times(2*kRepeat)
.InSequence(s2);
{
InSequence dummy;
EXPECT_CALL(foo, Bar(2))
.InSequence(s1, s2);
EXPECT_CALL(foo, Bar(4));
}
foo.Bar(0);
foo.Bar(1);
ThreadWithParam<MockFoo*>* const t =
new ThreadWithParam<MockFoo*>(Helper2, &foo, NULL);
Helper2(&foo);
JoinAndDelete(t);
foo.Bar(2);
foo.Bar(4);
}
// Tests using Google Mock constructs in many threads concurrently.
TEST(StressTest, CanUseGMockWithThreads) {
void (*test_routines[])(Dummy dummy) = {
&TestConcurrentCopyAndReadLinkedPtr,
&TestConcurrentWriteToEqualLinkedPtr,
&TestConcurrentMockObjects,
&TestConcurrentCallsOnSameObject,
&TestPartiallyOrderedExpectationsWithThreads,
};
const int kRoutines = sizeof(test_routines)/sizeof(test_routines[0]);
const int kCopiesOfEachRoutine = kMaxTestThreads / kRoutines;
const int kTestThreads = kCopiesOfEachRoutine * kRoutines;
ThreadWithParam<Dummy>* threads[kTestThreads] = {};
for (int i = 0; i < kTestThreads; i++) {
// Creates a thread to run the test function.
threads[i] =
new ThreadWithParam<Dummy>(test_routines[i % kRoutines], Dummy(), NULL);
GTEST_LOG_(INFO) << "Thread #" << i << " running . . .";
}
// At this point, we have many threads running.
for (int i = 0; i < kTestThreads; i++) {
JoinAndDelete(threads[i]);
}
// Ensures that the correct number of failures have been reported.
const TestInfo* const info = UnitTest::GetInstance()->current_test_info();
const TestResult& result = *info->result();
const int kExpectedFailures = (3*kRepeat + 1)*kCopiesOfEachRoutine;
GTEST_CHECK_(kExpectedFailures == result.total_part_count())
<< "Expected " << kExpectedFailures << " failures, but got "
<< result.total_part_count();
}
} // namespace
} // namespace testing
int main(int argc, char **argv) {
testing::InitGoogleMock(&argc, argv);
const int exit_code = RUN_ALL_TESTS(); // Expected to fail.
GTEST_CHECK_(exit_code != 0) << "RUN_ALL_TESTS() did not fail as expected";
printf("\nPASS\n");
return 0;
}
// Copyright 2008, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Author: wan@google.com (Zhanyong Wan)
// Google Mock - a framework for writing C++ mock classes.
//
// This file tests code in gmock.cc.
#include "gmock/gmock.h"
#include <string>
#include "gtest/gtest.h"
using testing::GMOCK_FLAG(verbose);
using testing::InitGoogleMock;
using testing::internal::g_init_gtest_count;
// Verifies that calling InitGoogleMock() on argv results in new_argv,
// and the gmock_verbose flag's value is set to expected_gmock_verbose.
template <typename Char, int M, int N>
void TestInitGoogleMock(const Char* (&argv)[M], const Char* (&new_argv)[N],
const ::std::string& expected_gmock_verbose) {
const ::std::string old_verbose = GMOCK_FLAG(verbose);
int argc = M;
InitGoogleMock(&argc, const_cast<Char**>(argv));
ASSERT_EQ(N, argc) << "The new argv has wrong number of elements.";
for (int i = 0; i < N; i++) {
EXPECT_STREQ(new_argv[i], argv[i]);
}
EXPECT_EQ(expected_gmock_verbose, GMOCK_FLAG(verbose).c_str());
GMOCK_FLAG(verbose) = old_verbose; // Restores the gmock_verbose flag.
}
TEST(InitGoogleMockTest, ParsesInvalidCommandLine) {
const char* argv[] = {
NULL
};
const char* new_argv[] = {
NULL
};
TestInitGoogleMock(argv, new_argv, GMOCK_FLAG(verbose));
}
TEST(InitGoogleMockTest, ParsesEmptyCommandLine) {
const char* argv[] = {
"foo.exe",
NULL
};
const char* new_argv[] = {
"foo.exe",
NULL
};
TestInitGoogleMock(argv, new_argv, GMOCK_FLAG(verbose));
}
TEST(InitGoogleMockTest, ParsesSingleFlag) {
const char* argv[] = {
"foo.exe",
"--gmock_verbose=info",
NULL
};
const char* new_argv[] = {
"foo.exe",
NULL
};
TestInitGoogleMock(argv, new_argv, "info");
}
TEST(InitGoogleMockTest, ParsesUnrecognizedFlag) {
const char* argv[] = {
"foo.exe",
"--non_gmock_flag=blah",
NULL
};
const char* new_argv[] = {
"foo.exe",
"--non_gmock_flag=blah",
NULL
};
TestInitGoogleMock(argv, new_argv, GMOCK_FLAG(verbose));
}
TEST(InitGoogleMockTest, ParsesGoogleMockFlagAndUnrecognizedFlag) {
const char* argv[] = {
"foo.exe",
"--non_gmock_flag=blah",
"--gmock_verbose=error",
NULL
};
const char* new_argv[] = {
"foo.exe",
"--non_gmock_flag=blah",
NULL
};
TestInitGoogleMock(argv, new_argv, "error");
}
TEST(InitGoogleMockTest, CallsInitGoogleTest) {
const int old_init_gtest_count = g_init_gtest_count;
const char* argv[] = {
"foo.exe",
"--non_gmock_flag=blah",
"--gmock_verbose=error",
NULL
};
const char* new_argv[] = {
"foo.exe",
"--non_gmock_flag=blah",
NULL
};
TestInitGoogleMock(argv, new_argv, "error");
EXPECT_EQ(old_init_gtest_count + 1, g_init_gtest_count);
}
TEST(WideInitGoogleMockTest, ParsesInvalidCommandLine) {
const wchar_t* argv[] = {
NULL
};
const wchar_t* new_argv[] = {
NULL
};
TestInitGoogleMock(argv, new_argv, GMOCK_FLAG(verbose));
}
TEST(WideInitGoogleMockTest, ParsesEmptyCommandLine) {
const wchar_t* argv[] = {
L"foo.exe",
NULL
};
const wchar_t* new_argv[] = {
L"foo.exe",
NULL
};
TestInitGoogleMock(argv, new_argv, GMOCK_FLAG(verbose));
}
TEST(WideInitGoogleMockTest, ParsesSingleFlag) {
const wchar_t* argv[] = {
L"foo.exe",
L"--gmock_verbose=info",
NULL
};
const wchar_t* new_argv[] = {
L"foo.exe",
NULL
};
TestInitGoogleMock(argv, new_argv, "info");
}
TEST(WideInitGoogleMockTest, ParsesUnrecognizedFlag) {
const wchar_t* argv[] = {
L"foo.exe",
L"--non_gmock_flag=blah",
NULL
};
const wchar_t* new_argv[] = {
L"foo.exe",
L"--non_gmock_flag=blah",
NULL
};
TestInitGoogleMock(argv, new_argv, GMOCK_FLAG(verbose));
}
TEST(WideInitGoogleMockTest, ParsesGoogleMockFlagAndUnrecognizedFlag) {
const wchar_t* argv[] = {
L"foo.exe",
L"--non_gmock_flag=blah",
L"--gmock_verbose=error",
NULL
};
const wchar_t* new_argv[] = {
L"foo.exe",
L"--non_gmock_flag=blah",
NULL
};
TestInitGoogleMock(argv, new_argv, "error");
}
TEST(WideInitGoogleMockTest, CallsInitGoogleTest) {
const int old_init_gtest_count = g_init_gtest_count;
const wchar_t* argv[] = {
L"foo.exe",
L"--non_gmock_flag=blah",
L"--gmock_verbose=error",
NULL
};
const wchar_t* new_argv[] = {
L"foo.exe",
L"--non_gmock_flag=blah",
NULL
};
TestInitGoogleMock(argv, new_argv, "error");
EXPECT_EQ(old_init_gtest_count + 1, g_init_gtest_count);
}
// Makes sure Google Mock flags can be accessed in code.
TEST(FlagTest, IsAccessibleInCode) {
bool dummy = testing::GMOCK_FLAG(catch_leaked_mocks) &&
testing::GMOCK_FLAG(verbose) == "";
(void)dummy; // Avoids the "unused local variable" warning.
}
#!/usr/bin/env python
#
# Copyright 2006, 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.
"""Unit test utilities for Google C++ Mocking Framework."""
__author__ = 'wan@google.com (Zhanyong Wan)'
import os
import sys
# Determines path to gtest_test_utils and imports it.
SCRIPT_DIR = os.path.dirname(__file__) or '.'
# isdir resolves symbolic links.
gtest_tests_util_dir = os.path.join(SCRIPT_DIR, '../gtest/test')
if os.path.isdir(gtest_tests_util_dir):
GTEST_TESTS_UTIL_DIR = gtest_tests_util_dir
else:
GTEST_TESTS_UTIL_DIR = os.path.join(SCRIPT_DIR, '../../gtest/test')
sys.path.append(GTEST_TESTS_UTIL_DIR)
import gtest_test_utils # pylint: disable-msg=C6204
def GetSourceDir():
"""Returns the absolute path of the directory where the .py files are."""
return gtest_test_utils.GetSourceDir()
def GetTestExecutablePath(executable_name):
"""Returns the absolute path of the test binary given its name.
The function will print a message and abort the program if the resulting file
doesn't exist.
Args:
executable_name: name of the test binary that the test script runs.
Returns:
The absolute path of the test binary.
"""
return gtest_test_utils.GetTestExecutablePath(executable_name)
def GetExitStatus(exit_code):
"""Returns the argument to exit(), or -1 if exit() wasn't called.
Args:
exit_code: the result value of os.system(command).
"""
if os.name == 'nt':
# On Windows, os.WEXITSTATUS() doesn't work and os.system() returns
# the argument to exit() directly.
return exit_code
else:
# On Unix, os.WEXITSTATUS() must be used to extract the exit status
# from the result of os.system().
if os.WIFEXITED(exit_code):
return os.WEXITSTATUS(exit_code)
else:
return -1
# Suppresses the "Invalid const name" lint complaint
# pylint: disable-msg=C6409
# Exposes utilities from gtest_test_utils.
Subprocess = gtest_test_utils.Subprocess
TestCase = gtest_test_utils.TestCase
environ = gtest_test_utils.environ
SetEnvVar = gtest_test_utils.SetEnvVar
PREMATURE_EXIT_FILE_ENV_VAR = gtest_test_utils.PREMATURE_EXIT_FILE_ENV_VAR
# pylint: enable-msg=C6409
def Main():
"""Runs the unit test."""
gtest_test_utils.Main()
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment