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

HippoMock : mocking just a part of class

本文关键字:课堂 一部分 HippoMock      更新时间:2023-10-16

我想知道使用HippoMock是否可以只模拟类的一部分。

class aClass
{
public:
    virtual void method1() = 0;
    void method2(){ 
        do
            doSomething;      // not a functon 
            method1();
        while(condition);
    };
};

我想只模拟方法 1 以测试方法 2

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

我试试这个

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

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

多谢

Ambroise Petitgenêt

这个答案有两个部分。首先是,是的,这很容易做到。其次,如果你需要以这种方式构建测试,你通常会有一个不幸的类设计 - 这通常发生在你需要对遗留软件进行测试时,其中类设计无法合理地修复。

如何测试?据我所知,你可以使用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());
}

或者,如果method1 const

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