[solved] Mocking the database example
-
Hi! Does anyone have some examples how to Mock the database with Qt? I've been searching the internet and cannot understand how to do it.
From what I've read we cannot use any 3rd party tools (GoogleMock, Hippo Mocks, etc) and we should use qttestlib and QtSignalSpy, but I cannot figure out how to do it.
I'm new to Unit testing, I have already a project which has connections to the database and to a Serial Port, and would like to add the tests now, mocking the Database and the Serial Port connection. If someone could post an example with something like this it would be great! -
Hi and welcome to devnet,
If you are using QSerialPort then you can create your own QIODevice that should answer like it's a QSerialPort.
As for the database you can generate one in memory using sqlite.
Hope it helps
-
AFAIK, the video will be released after the San Francisco Qt DevDay.
The code itself I must clean a bit
-
In short, use a custom QIODevice in place of your QSerialPort.
So the class that uses QSerialPort should have a setDevice(QIODevice *device) so you can choose which one to use.
-
Quick example:
@
class MockupDevice : public QIODevice
{
Q_OBJECT
public:
explicit MockupDevice(QObject *parent = 0);qint64 bytesAvailable() const Q_DECL_OVERRIDE;
protected:
qint64 readData(char *data, qint64 maxlen) Q_DECL_OVERRIDE;
qint64 writeData(const char *data, qint64 len) Q_DECL_OVERRIDE;private:
QByteArray _outputBuffer;
};
@@
MockupDevice:: MockupDevice(QObject *parent)
: QIODevice(parent)
{
}qint64 MockupDevice::bytesAvailable() const
{
return _outputBuffer.size() + QIODevice::bytesAvailable();
}qint64 MockupDevice::readData(char *data, qint64 maxlen)
{
if (_outputBuffer.size() == 0) {
return 0;
}qint64 len = qMin((qint64)_outputBuffer.size(), maxlen); QByteArray out = _outputBuffer.left(len); _outputBuffer.remove(0, len); memcpy(data, out.data(), len); return len;
}
qint64 MockupDevice::writeData(const char *data, qint64 len)
{
// process the data you wrote in your device
// put the answer in _outputbuffer
if (_outputBuffer.size() > 0) {
emit readyRead();
}return len;
}
@Hope it helps
-
@
#include <QtTest>#include "mockupdevice.h"
#include <QBuffer>
class Tst_usingmockup : public QObject
{
Q_OBJECTprivate Q_SLOTS:
void test();
};void Tst_usingmockup::test() const
{
MyCoolClass mcc;
MockUpdevice *device = new MockupDevice;
mcc.setDevice(device)
// execute mcc functions
// check mcc functions return value if any
// check device content etc.
}QTEST_APPLESS_MAIN(Tst_usingmockup)
#include "tst_usingmockup.moc"
@ -
You're welcome !
Don't forget to also add a unit test for the mockup object to be sure it's acting correctly.
If your question is answered, please update the thread title prepending [solved] so other forum users may know a solution has been found :)