chevron-thin-right chevron-thin-left brand cancel-circle search youtube-icon google-plus-icon linkedin-icon facebook-icon twitter-icon toolbox download check linkedin phone twitter-old google-plus facebook profile-male chat calendar profile-male
Welcome to Typemock Answers. Here you can ask and receive answers from other community members. And if you liked or disliked an answer or thread: react with an up- or downvote Enjoy!
+2 votes
Hello,

I am working on a C++ unit test. I have a  production code like below.

I am having trouble for redirecting a method call with a derived class which inherits from a base class as protected.

I want to call MockMethodA on anotherObj. (anotherObj is an instance of a concrete class in my unit test project) when methodA is called inside methodB.

But It does not work. It calls methodA of BaseClass. I tried both WHEN_CALLED and PRIVATE_WHEN_CALLED macros.

WHEN_CALLED(d->methodA()).DoMemberFunctionInstead(&anotherObj, MockMethodA);

PRIVATE_WHEN_CALLED(d, methodA).DoMemberFunctionInstead(&anotherObj, MockMethodA);

d->methodB();

//production code. It cannot be changed.

class BaseClass

{

public:

BaseClass(){};

virtual ~BaseClass(){};

virtual void methodA()

{

cout << \"methodA\" << endl;

}

};

class DerivedClass :protected BaseClass

{

public:

DerivedClass(){};

~DerivedClass(){};

void methodB()

{

cout << \"methodB\" << endl;

BaseClass::methodA();

}

};
asked by (620 points)

Hi Levent, we\'re exploring it.

1 Answer

0 votes

It works fine when I use the PRIVATE_WHEN_CALLED(d, methodA).DoMemberFunctionInstead(&anotherObj, MockMethodA); due to MethodA being inaccessible from the DerivedClass directly.

std::string str = \\\"\\\";

std::string str2 = \\\"\\\";

class BaseClass {

public:

    BaseClass() {};

    virtual ~BaseClass() {};

    virtual void methodA()

    {

        str = \\\"MethodA\\\";

    }

};

class DerivedClass :protected BaseClass

{

public:

    DerivedClass() {};

    ~DerivedClass() {};

    void methodB()

    {

        str = \\\"MethodB\\\";

        BaseClass::methodA();

    }

};

class AnotherClass

{

public:

    void MockMethodA() { str2 = \\\"MethodRedirected\\\"; }

};

class ReproductionTests : public ::testing::Test

{

    void SetUp() override

    {

        auto dummy = new AnotherClass();

        dummy->MockMethodA();

        delete dummy;

    }

    virtual void TearDown()

    {

        ISOLATOR_CLEANUP();

    }

};

TEST_F(ReproductionTests, QALevent)

{

    auto d = new DerivedClass();

    auto anotherObj = new AnotherClass();

    //WHEN_CALLED(d->methodA()).DoMemberFunctionInstead(&anotherObj, MockMethodA);

    PRIVATE_WHEN_CALLED(d, methodA).DoMemberFunctionInstead(&anotherObj, MockMethodA);

    d->methodB();

    ASSERT_EQ(str2, \\\"MethodRedirected\\\");

    ASSERT_EQ(str, \\\"MethodB\\\");

    

    delete d;

    delete anotherObj;

}

answered by (3.9k points)
...