Created
August 1, 2019 12:04
-
-
Save nettle/5db56ab3cf34815ea4dc1850b5b2800a to your computer and use it in GitHub Desktop.
Minimal C++ TestSuite
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <string> | |
#include <vector> | |
// Test suite controls test execution | |
class TestSuite { | |
public: | |
// Abstract test case | |
class TestCase { | |
public: | |
TestCase() {}; | |
TestCase(const char* n, const char* d) | |
: name(n), description(d) { | |
TestSuite::add(this); | |
}; | |
virtual bool test() = 0; | |
std::string name; | |
std::string description; | |
}; | |
static TestSuite& get() { | |
static TestSuite testSuite; | |
return testSuite; | |
} | |
static void add(TestCase* test) { | |
get().tests.push_back(test); | |
} | |
static bool run() { | |
bool allResults = true; | |
for (auto t : get().tests) { | |
bool result = t->test(); | |
std::cout << "[TestSuite::run] " << t->description << " : " << (result ? "PASS" : "FAIL") << std::endl; | |
allResults = allResults && result; | |
} | |
return allResults; | |
} | |
private: | |
std::vector<TestCase*> tests; | |
}; | |
// TEST macro to use when defining tests | |
#define TEST(name, description) \ | |
class TEST_##name##_Test : public TestSuite::TestCase { \ | |
public: \ | |
TEST_##name##_Test(const char* n, const char* d) \ | |
: TestSuite::TestCase(n, d) {} \ | |
bool test(); \ | |
} TEST_##name##_Test_instance(#name, description); \ | |
bool TEST_##name##_Test::test() | |
// Example: | |
TEST(TEST1, "Test aaa") { | |
std::cout << "[TEST1] Zzzz..." << std::endl; | |
return true; | |
} | |
TEST(TEST2, "Test bbb") { | |
std::cout << "[TEST2] Hmmm..." << std::endl; | |
return true; | |
} | |
// Cusomized test case | |
class TEST3 : public TestSuite::TestCase { | |
public: | |
TEST3(const char* n, const char* d) | |
: TestSuite::TestCase(n, d) { | |
std::cout << "[TEST3] Custom constructor" << std::endl; | |
} | |
~TEST3() { | |
std::cout << "[TEST3] Custom destructor" << std::endl; | |
} | |
bool test() { | |
std::cout << "[TEST3] No macro" << std::endl; | |
return true; | |
}; | |
} TEST3_instance("TEST3", "Test ccc"); | |
int main(void) { | |
bool result = TestSuite::run(); | |
std::cout << "[main] Result: " << (result ? "PASS" : "FAIL") << std::endl; | |
return (result ? 0 : 1); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment