Brian Hwang
Brian Hwang

Reputation: 1

How to mock this class

class A
{
public:
    void doFirstJob() 
    {
        // Do first Job.
    }
}

class B : public A
{
public:
    virtual void doSecondJob()
    {
        // Do Second Job.
    }
}

class C
{
public:
    void doSomething() {
        b->doFirstJob();
        b->doSecondJob();
    }
private:
    B* b;
}

Now I should write unit test code for class C, then I'll write a mock for class B, but the problem is how to mock the method doFirstJob().

Bluntly, I want know how to mock the non-virtual method of the parent class???

Can any one help me ??

Upvotes: 0

Views: 87

Answers (1)

JamesR
JamesR

Reputation: 745

Typemock Isolator++ supports mocking non virtual methods of a parent class (same as faking a method of the class under test).

See following example:

class A
{
public:
    int doFirstJob() 
    {
        return 0;
    }
};

class B : public A
{

};

class C
{
public:

    int doSomething() 
    {
        return b->doFirstJob();
    }
    void setB(B* to)
    {
        b = to;
    }
private:
    B* b;
};

In the test You create a fake of B -> change the behavior of doFirstJob to return 3 -> continue with your test as you would normally write it.

TEST_CLASS(NonVirtualMethod)
{
public:

    TEST_METHOD(NonVirtualMethodTestOfBaseClass)
    {
        B* fakeB = FAKE<B>(); 
        WHEN_CALLED(fakeB->doFirstJob()).Return(3);

        C c;
        c.setB(fakeB);
        int first = c.doSomething();

        Assert::AreEqual(3,first);
    }
}

You can find more examples here.

Upvotes: 1

Related Questions