I’m trying to test a class that uses a QIODevice. In actuality, the object will probably use a QFile, but for my unit test I’d prefer to use a QBuffer for speed. Dependency injection and polymorphism combine to get me what I want.
I have a problem, however. My class constructor looks like this:
Object::Object(QIODevice& source)
{
if(!source.open(QIODevice::ReadOnly))
{
qDebug("Object: Could not open source.");
}
}
Then in my test I check for the message:
void TestObject::printsErrorOnOpenFailure()
{
QTest::ignoreMessage(QtDebugMsg, "Object: Could not open source.");
QBuffer buffer;
Object obj(buffer);
}
Unfortunately, open still seems to succeed even without a QByteArray to operate on. What’s the best way to give my object a QIODevice that I know it can’t open?
You can’t make
QBuffer::open()to return false (*). So you can’t useQBufferin your scenario.But what about sub-classing and just overwriting
open()to always return false?(*) At least not using the flags
WriteOnlyand/orReadOnly. Passing invalid flags is the only possibility to make it return false. Quoting Qt 4.8.0 sources:corelib/io/qbuffer.cpp:
corelib/io/qiodevice.cpp: