2012-06-28 61 views
2

我想測試一個使用QIODevice的類。實際上,該對象可能使用QFile,但對於我的單元測試,我傾向於使用QBuffer來提高速度。依賴注入和多態性結合起來讓我得到我想要的。如何使一個無法打開的QIODevice

但是,我有一個問題。我的類的構造函數是這樣的:

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成功進行操作。給我的對象一個QIODevice,我知道它不能打開的最佳方法是什麼?

+0

爲什麼你需要一個指針到你的'QIODevice'? – leemes

+0

因爲我簡化了示例的設置代碼,所以我沒有仔細考慮。我會刪除它,因爲這是不必要的。 – cgmb

+0

好的。我只是想知道......;) – leemes

回答

1

您不能讓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 } 
+0

那不能被實例化。 QIODevice :: readData和QIODevice :: writeData是純虛擬的。我用QBuffer的繼承替換了QIODevice的繼承,並刪除了不必要的構造函數。 – cgmb

+0

噢,是的,謝謝你。我糾正了我的答案。 – leemes

+1

另一種可能性是使用'QFile(「」)';這也不應該是可以打開的。 – leemes