CppUnit
Unit testing framework module
CppUnit is a unit testing framework module for the C++ programming language. It allows unit-testing of C sources as well as C++ with minimal source modification. It was started around 2000 by Michael Feathers as a C++ port of JUnit for Windows and ported to Unix by Jerome Lacoste. The library is released under the GNU Lesser General Public License. However, unlike JUnit, CppUnit does not rely on annotations (as annotations were not added to C++ until C++26), and rather creates tests with preprocessor macros.
The framework runs tests in suites. Test result output is sent to a filter, the most basic being a simple pass or fail count printed out, or more advanced filters allowing XML output compatible with continuous integration reporting systems.The project has been forked several times. The freedesktop.org version at GitHub, maintained by Markus Mohrhard of the LibreOffice project (which uses CppUnit heavily), was actively maintained until 2020, and is used in Linux distributions such as Debian, Ubuntu, Gentoo and Arch. Some libraries, such as POCO C++ Libraries, provide their own APIs to consume the CppUnit library.
01Example
Consider the following class Integer:
module; export module wikipedia.examples.Integer; export namespace wikipedia::examples { class Integer { private: int x = 0; public: Integer(int x): x{x} {} [[nodiscard]] int add(int y) noexcept { x += y; return x; } [[nodiscard]] int subtract(int y) noexcept { x -= y; return x; } } }It can be tested like so:
module; export module wikipedia.examples.tests.IntegerTest; import <cppunit/extensions/HelperMacros.h>; import wikipedia.examples.Integer; using CppUnit::TestFixture; using wikipedia::examples::Integer; export namespace wikipedia::examples::tests { class IntegerTest: public TestFixture { private: CPPUNIT_TEST_SUITE(IntegerTest); CPPUNIT_TEST(testAdd); CPPUNIT_TEST(testSubtract); CPPUNIT_TEST_SUITE_END(); Integer* i; protected: void testAdd() { CPPUNIT_ASSERT_EQUAL(8, i->add(8)); // 5 + 3 = 8 } void testSubtract() { CPPUNIT_ASSERT_EQUAL(3, i->subtract(2)); // 5 - 2 = 3 } public: void setUp() override { i = new Integer(5); } void tearDown() override { delete i; } }Then, it can be tested in main():
import <cppunit/ui/text/TestRunner.h> import wikipedia.examples.tests.IntegerTest; using CppUnit::TextUi::TestRunner; using wikipedia::examples::tests::IntegerTest; int main(int argc, char* argv[]) { TestRunner testRunner; runner.addTest(IntegerTest::suite()); runner.run(); }Sources and credits
This article is adapted from the Wikipedia article “CppUnit”, written by its contributors and licensed under CC BY-SA 4.0. Fathomly has changed the layout, removed citation markers, navigation and maintenance notices, and adjusted punctuation. This adapted version is shared under the same license. For references, see the original article.
Fathomly is not affiliated with or endorsed by the Wikimedia Foundation. Spotted a problem? Tell us.