Search code examples
c++unit-testinggoogletestgooglemock

Why is original method mocked by GoogleMock still getting called?


I have been attempting to use GoogleMock to override a few specific methods in a underlying class, however I seem to be getting the base constructor, rather than the mocked object. Is there something obvious I am missing here?

I have been following the following example: http://blog.divebomb.org/2011/07/my-first-c-cmake-googletest-and-googlemock/

However, in my test, I am still getting my 'printf' called. Any thoughts?

Here are the classes/header files:

A.h:

#pragma once
class A
{
public:
    virtual void methodToOverride();
    void someConcreteMethod();

    int mMemberVariable;
};

A.cpp:

#include "A.h"

void A::methodToOverride()
{
    std::printf("Hello World");
}

void A::someConcreteMethod()
{
}

B.h:

#include "A.h"

class B
{
public:
    B(A &injectedClass);
    ~B();
    void MethodToTest();

private:
    A mA;
};

B.cpp:

#include "B.h"

B::B(A & injectedClass):mA(injectedClass)
{
    mA.someConcreteMethod();
}

B::~B(){}

void B::MethodToTest()
{
    mA.methodToOverride();
}

MockA.h:

#include "A.h"
#include "gmock\gmock.h"

class MockA : public A
{
public:
    MOCK_METHOD0(methodToOverride, void());

};

BTest.cpp:

#include "gtest/gtest.h"
#include "MockA.h"
#include "B.h"

using ::testing::AtLeast;
using ::testing::_;

TEST(BTest, mockObject)
{
    // Arrange
    MockA injectedMock;
    EXPECT_CALL(injectedMock, methodToOverride())
        .Times(AtLeast(1));

    B classUnderTest(injectedMock);

    // Act
    classUnderTest.MethodToTest();
}

Solution

  • One major problem is that B::mA is an instance of the A class. It doesn't know anything about child-classes and objects.

    The member B::mA either needs to be a reference or a pointer for polymorphism to work.