我正在尝试测试一个使用QIODevice的类。实际上,对象可能会使用QFile,但对于我的单元测试,我更喜欢使用QBuffer来提高速度。依赖注入和多态性的结合让我得到了我想要的东西。
然而,我有一个问题。我的类构造函数如下所示:
Object::Object(QIODevice& source)
{
if(!source.open(QIODevice::ReadOnly))
{
qDebug("Object: Could not open source.");
}
}然后在我的测试中,我检查消息:
void TestObject::printsErrorOnOpenFailure()
{
QTest::ignoreMessage(QtDebugMsg, "Object: Could not open source.");
QBuffer buffer;
Object obj(buffer);
}不幸的是,即使没有QByteArray可以操作,open似乎仍然是成功的。给我的对象一个我知道它打不开的QIODevice的最好方法是什么?
发布于 2012-06-29 06:07:27
不能让QBuffer::open()返回false (*)。所以你不能在你的场景中使用QBuffer。
但是,如果子类化和重写open()总是返回false呢?
class UnopenableDevice : public QBuffer {
public:
bool open(QIODevice::OpenMode m) { return false; }
};(*)至少不使用标志WriteOnly和/或ReadOnly。传递无效标志是使其返回false的唯一可能。引用Qt 4.8.0来源:
corelib/io/qbuffer.cpp:
332 bool QBuffer::open(OpenMode flags)
333 {
334 Q_D(QBuffer);
335
336 if ((flags & (Append | Truncate)) != 0)
337 flags |= WriteOnly;
338 if ((flags & (ReadOnly | WriteOnly)) == 0) {
339 qWarning("QBuffer::open: Buffer access not specified");
340 return false; // <----- only possibility to return false!
341 }
342
343 if ((flags & Truncate) == Truncate)
344 d->buf->resize(0);
345 d->ioIndex = (flags & Append) == Append ? d->buf->size() : 0;
346
347 return QIODevice::open(flags);
348 }corelib/io/qiodevice.cpp:
540 bool QIODevice::open(OpenMode mode)
541 {
542 Q_D(QIODevice);
543 d->openMode = mode;
544 d->pos = (mode & Append) ? size() : qint64(0);
545 d->buffer.clear();
546 d->accessMode = QIODevicePrivate::Unset;
547 d->firstRead = true;
548 #if defined QIODEVICE_DEBUG
549 printf("%p QIODevice::open(0x%x)\n", this, quint32(mode));
550 #endif
551 return true;
552 }https://stackoverflow.com/questions/11253299
复制相似问题