[Qt-interest] Force emitting a signal in a test?

Andre Somers andre at familiesomers.nl
Tue Nov 17 09:53:36 CET 2009


Oliver.Knoll at comit.ch wrote:
> Hong Jiang wrote on Sunday, November 15, 2009 8:02 AM:
>
>   
>> I'm writing some tests for my application. In the tests, I need to
>> programmatically force emit some signals. For example, I'd like to
>> trigger QListWidget::itemActivated from outside the widget.
>>     
>
> Normally one can't emit signals from *outside* a given QObject, unless that QObject based class provides some (public/protected) methods, as in:
>
> class MyObject : public QObject {
>   Q_OBJECT
> public:
>   ...
>   void emitFoo() { emit foo(); }
> signals:
>   void foo();
>   ...
> };
>
> Off course you don't want to expose such methods just for "sake of testing", so you could either make it at least private in your class, and then in your test class do the VERY NASTY AND EVIL EVIL DIRTY TRICK
>
>   #define private public // muahahahhahaaa!!!
>   #include "ClassToTest.h"
>
> before including the SUT's (System Under Test) header.
>
> If you also want to avoid implementing a method like emitFoo(), have a look at to what the emit macro expands and call this code instead (also with the dirrty nasty "private to public" magic voodoo).
>
>
> Cheers, Oliver
>   
Another, perhaps a bit less nasty trick, is to use 
QMetaObject::invokeMethod on the signal. That works, and is documented 
qt behaviour. No voodoo needed at all :-)

André




More information about the Qt-interest-old mailing list