如何在测试中添加存根

How add stub in the test?

本文关键字:添加 存根 测试      更新时间:2023-10-16

有一种需要测试的方法:

void DATA::setData(QString path)
{
...........................
    QDir dir(path);
    if (dir.exists()) {
        ...................
    }
}

是否有可能以某种方式在dir.exists()上放置一个固执,以便在测试中调用setData方法的返回true不管更改路径如何?

P.S。我使用Google模拟和Google测试。

qdir类没有任何虚拟方法,因此很难模拟它。您可以在此处提到的技巧,但是它迫使您使用模板。其他方法(我会这样这样做)是为QDIR定义其他接口:

class MyAbstractQDirInterface {
public:
    MyAbstractQDirInterface() = default;
    virtual ~MyAbstractQDirInterface() = default;
    virtual bool exists() = 0;
};
class MyConcreteQDirInterface: public MyAbstractQDirInterface {
public:
    MyConcreteQDirInterface() = default;
    ~MyConcreteQDirInterface() override = default;
    bool exists() override {
        // here call the real QDir::exists
    }
};
class MyQDirInterfaceMock: public MyAbstractQDirInterface {
public:
    MOCK_METHOD0(exists, bool());
};

并稍微更改setData签名以接受指针(或参考,如果您愿意的话)到MyAbstractQDirInterface类:

void DATA::setData(MyAbstractQDirInterface* qdirInterface)
{
    // ...
    if (qdirInterface->exists()) {
        // ...
    }
}

然后,在生产中,您可以使用MyConcreteQDirInterface调用此方法,在测试env中您可以使用MyQDirInterfaceMock调用。