Ambroise
Ambroise

Reputation: 41

HippoMock : mocking just a part of class

I would like to know if with HippoMock it is possible to mock just a parts of a class.

Example

class aClass
{
public:
    virtual void method1() = 0;

    void method2(){ 
        do
            doSomething;      // not a functon 
            method1();
        while(condition);
    };
};

I would like to mock just method1 in order to test the method 2

Clearly I use HippoMock and I have a bug in method2 so I made a unit test in order to correct it and be sure it will not come back. But i don't find the way to do it.

I try this

TEST(testMethod2)
{
    MockRepository mock;
    aClass *obj = mock.Mock<aClass>();
    mock.ExpectCall(obj , CPXDetector::method1);
    obj->method2();
}

Is there some solution in native cpp ? With an other mock framework ?

Thanks a lot

Ambroise Petitgenêt

Upvotes: 4

Views: 1259

Answers (1)

Peter
Peter

Reputation: 5728

There are 2 parts to this answer. First is, yes it's easy to do this. Second is, if you need to structure a test this way you often have an unfortunate class design - this commonly happens when you need to put legacy software under test, where the class design can't reasonably be fixed.

How to test this? As far as I remember you can use Hippomocks for this, but because I haven't used it in a while, I don't remember off the top of my head how to do it. Because you asked for any solution, even those using a different framework, I suggest using the direct approach instead of using hippomocks:

class bClass : public aClass
{
    int _counter;
public:
    bClass() : aClass(), _counter(0){}
    void method1() { _counter++; }
    int NumCallsToMethod1() const { return _counter; }
};

TEST(testMethod2)
{
    bClass testThis;
    testThis.method2();
    TEST_EQUALS(1,testThis.NumCallsToMethod1());
}

or, if method1 is const:

class bClass : public aClass
{
    mutable int _counter;
public:
    bClass() : aClass(), _counter(0){}
    void method1() const { _counter++; }
    int NumCallsToMethod1() const { return _counter; }
};

Upvotes: 1

Related Questions