如何在测试中添加存根
How add stub in the test?
有一种需要测试的方法:
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
调用。
相关文章:
- 将成员变量添加到共享库中的类中,不会破坏二进制兼容性吗
- 如何在C++中从两个单独的for循环中添加两个数组
- POCO::PostgreSQL:如何将std::vector支持添加到`Binder::bind`
- 如何仅为一个函数添加延迟
- 如何防止 c++ 在从浮点型转换为双精度型(不适用于 IO)时添加额外的小数?
- 使用std::transform将一个范围的元素添加到另一个范围中
- 如何将更多文件夹添加到c++include路径
- 如何将元素添加到数组的线程安全函数?
- QT通过C++添加映射QML项目
- 如何将点击的信号和插槽添加到qt中的自定义按钮中
- 如何使用重载的相等(==)运算符向测试用例添加描述
- 为什么Mat类的两个对象可以在不重载运算符+的情况下添加
- 如何防止clang格式在流运算符调用之间添加换行符<<
- 只能向C++添加一定数量的字符
- Qt和C++:将QLineEdit添加到QTabWidget中
- 将QIcon添加到QTableView单元格
- 为什么我必须在C++中添加一个赋值符号来声明一个数组
- 为什么除非添加括号,否则构造函数上的模板替换会失败?
- 将图像添加到资源文件夹UWP C++
- 如何在测试中添加存根