Skip to content

Instantly share code, notes, and snippets.

@melihovv
Last active December 31, 2015 19:33
Show Gist options
  • Save melihovv/1525db238b7823596421 to your computer and use it in GitHub Desktop.
Save melihovv/1525db238b7823596421 to your computer and use it in GitHub Desktop.
Qt Tests Stub
#include "testsrunner.h"
int main(int argc, char* argv[])
{
return RUN_ALL_TESTS(argc, argv);
}
#include "testsomething.h"
void TestSomething::testSomething_data()
{
QTest::addColumn<int>("a");
QTest::addColumn<int>("b");
QTest::addColumn<int>("expectation");
QTest::newRow("a + b")
<< 1
<< 2
<< 3;
}
void TestSomething::testSomething()
{
QFETCH(int, a);
QFETCH(int, b);
QFETCH(int, expectation);
int real = a + b;
QString message = QString("\nExpected:\n\"%1\"\n\nReal:\n\"%2\"\n")
.arg(expectation)
.arg(real);
QVERIFY2(expectation == real, message.toStdString().c_str());
}
#ifndef TESTSOMETHING_H
#define TESTSOMETHING_H
#include <QObject>
#include <QTest>
#include "testsrunner.h"
class TestSomething : public QObject
{
Q_OBJECT
private slots:
void testSomething_data();
void testSomething();
};
DECLARE_TEST(TestSomething);
#endif // TESTSOMETHING_H
#ifndef TESTRUNNER_H
#define TESTRUNNER_H
#include <QTest>
#include <QSharedPointer>
#include <algorithm>
#include <list>
#include <iostream>
// Use this macro after your test declaration.
#define DECLARE_TEST(className) \
static char test_##className = TestRunner::Instance().RegisterTest<className>(#className);
// Use this macro to execute all tests.
#define RUN_ALL_TESTS(argc, argv) \
TestRunner::Instance().RunAll(argc, argv);
class TestRunner
{
public:
static TestRunner& Instance()
{
static TestRunner instance;
return instance;
}
template <typename T>
char RegisterTest(char *name)
{
if (std::find_if(begin(tests), end(tests), [&name](QSharedPointer<QObject> &elem) {
return elem->objectName() == name;
}) == end(tests))
{
QSharedPointer<QObject> test(new T());
test->setObjectName(name);
tests.push_back(test);
}
return char(1);
}
int RunAll(int argc, char *argv[])
{
int errorCode = 0;
std::for_each(begin(tests), end(tests), [&](QSharedPointer<QObject>& test)
{
errorCode |= QTest::qExec(test.data(), argc, argv);
std::cout << std::endl;
});
return errorCode;
}
private:
std::list<QSharedPointer<QObject>> tests;
};
#endif // TESTRUNNER_H
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment