AutoTest.h 1.49 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
/**
* @author Rob Caldecott
* @note This was obtained from http://qtcreator.blogspot.com/2010/04/sample-multiple-unit-test-project.html
*
*/

#ifndef AUTOTEST_H
#define AUTOTEST_H

#include <QTest>
#include <QList>
#include <QString>
#include <QSharedPointer>

namespace AutoTest
{
    typedef QList<QObject*> TestList;
18
    
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
    inline TestList& testList()
    {
	static TestList list;
	return list;
    }

    inline bool findObject(QObject* object)
    {
	TestList& list = testList();
	if (list.contains(object))
	{
	    return true;
	}
	foreach (QObject* test, list)
	{
	    if (test->objectName() == object->objectName())
	    {
		return true;
	    }
	}
	return false;
    }

    inline void addTest(QObject* object)
    {
	TestList& list = testList();
	if (!findObject(object))
	{
	    list.append(object);
	}
    }

    inline int run(int argc, char *argv[])
52
    { 
53
	int ret = 0;
54
	QCoreApplication t(argc, argv);
55
	foreach (QObject* test, testList())
56 57
	{  
            ret += QTest::qExec(test, argc, argv);
58
	}
59
	
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
	return ret;
    }
}

template <class T>
class Test
{
public:
    QSharedPointer<T> child;

    Test(const QString& name) : child(new T)
    {
	child->setObjectName(name);
	AutoTest::addTest(child.data());
    }
};

#define DECLARE_TEST(className) static Test<className> t(#className);

#define TEST_MAIN \
    int main(int argc, char *argv[]) \
    { \
      return AutoTest::run(argc, argv); \
  }

#endif // AUTOTEST_H