HippoMock:嘲笑只是课堂的一部分

时间:2014-02-24 21:21:44

标签: c++ unit-testing mocking hippomocks

我想知道如果使用HippoMock可以模拟一个类的一部分。

实施例

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

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

我想模拟method1以测试方法2

显然我使用HippoMock并且我在方法2中有一个错误,所以我进行了单元测试以纠正它并确保它不会回来。但我找不到办法。

我试试这个

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

原生cpp中是否有一些解决方案?使用其他模拟框架?

非常感谢

AmbroisePetitgenêt

1 个答案:

答案 0 :(得分:1)

这个答案分为两部分。首先,是的,很容易做到这一点。其次,如果您需要以这种方式构建测试,那么您通常会遇到一个不幸的类设计 - 当您需要将旧版软件置于测试中时,通常会发生这种情况,而无法合理地修复类设计。

如何测试?据我所知,你可以使用Hippomocks,但由于我有一段时间没有使用它,我不记得我的头脑中如何做到这一点。因为您要求任何解决方案,即使使用不同框架的解决方案,我建议使用直接方法而不是使用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());
}

或,如果method1const

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