[solved] Mocking the database example
-
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
-
Hi! Thank you for your post.
I saw you made a conference with this subject. Is it possible to have access to the video or the demo?Thanks!
-
AFAIK, the video will be released after the San Francisco Qt DevDay.
The code itself I must clean a bit
-
Ok, thanks.
But in the meanwhile, can someone give me an example how I would "fake" and test a QSerialPort read() and write() methods?This is really the first Unit test I'm implementing, so excuse me my ignorance.
Thank.
-
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.
-
I understand that, I just don't know how to (and what to) test, for example, the read and write methods.
-
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
-
Yes, it helped. And, to finish... can you post an example of an actual test? With how would you use this MockupDevice?
Many thanks!
-
@
#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"
@ -
Thank you very much for the help! I think I can go alone from here ;-)
-
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 :)