4

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

Ambroise
  • 41
  • 3

1 Answers1

1

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; }
};
Peter
  • 5,608
  • 1
  • 24
  • 43
  • First yes I'm working with legacy code and I can't refactor all. And second your solution is nice, I like it – Ambroise Feb 25 '14 at 12:39
  • I think the above pattern, and a couple of others are described in this book: http://www.amazon.com/Working-Effectively-Legacy-Michael-Feathers/dp/0131177052 – Peter Feb 25 '14 at 13:37
  • I'm reading the books you send to me. It is very interesting. Thanks a lot – Ambroise Feb 28 '14 at 06:32
  • 1
    HippoMocks can do this in case of a non-virtual member function calling a virtual one - you can only mock virtual ones. In this case though, as you're relying on implementation details of your mock I'd use @Peter's solution still, if only to make it explicit. – dascandy Mar 06 '14 at 22:43