Inheritance and signals
Unsolved
General and Desktop
-
Hi.
I am currently trying to write a unittest for a class that uses my api class.
Because the server is not running while testing, i inherited from my api class and overwrote the functions used by the class to be tested. However I end up with a nasty exception.
To test what's wrong I coded a minimal example which demonstrates what I'm trying to accomplish:Base class:
#ifndef TESTBASE_H #define TESTBASE_H #include <QObject> class Api: public QObject { Q_OBJECT; signals: void signalResponse(int i); public: void foo() { //the network manager would be called here and its result would be handled //in a private slot, afterwards the signal below would be emitted to the //object using the api emit signalResponse(111); } }; #endif // TESTBASE_H
Dummy class used in test:
#ifndef TESTCHILD_H #define TESTCHILD_H #include <QObject> #include "TestBase.h" class MockApi: public Api { Q_OBJECT; public: void foo() { // to prevent exception due to failed network requests // this "mock" class just emits dummy data to the object using the api emit signalResponse(222); } }; #endif // TESTCHILD_H
Test:
#ifndef TEST_H #define TEST_H #include <QObject> #include "TestBase.h" #include "TestChild.h" #include <QDebug> // not an actual unittest, just poc class Test: public QObject { Q_OBJECT; private: Api*test = new MockApi(); public: Test() { //using new object connect syntax does not work either connect(test, SIGNAL(signalResponse(int)), this, SLOT(slotTest(int))); } void foo() { test->foo(); } public slots: void slotTest(int i) { qDebug() << i; //prints 111 instead of expected 222 } }; #endif // TEST_H
Is what I am trying to do impossible?
And if so, why?Thank ya'll in advance.
-
@VS-IK said in Inheritance and signals:
//prints 111 instead of expected 222
That's because Api::foo() is not
virtual
. You can't override it.