// Example function to be tested int Add(int a, int b) { return a + b; } // Test case using CppUnit class Test_Add : public CppUnit::TestFixture { public: void Test() { CPPUNIT_ASSERT(Add(2, 2) == 4); } }; // Create a test suite and run it int main(int argc, char* argv[]) { CppUnit::TextUi::TestRunner runner; runner.addTest(new CppUnit::TestCaller("test_add", &Test_Add::Test)); runner.run(); return 0; }
// Example class to be tested class Calculator { public: int Add(int a, int b) { return a + b; } int Subtract(int a, int b) { return a - b; } }; // Test cases using CppUnit class Test_Calculator : public CppUnit::TestFixture { private: Calculator calculator; public: void TestAdd() { CPPUNIT_ASSERT(calculator.Add(2, 2) == 4); } void TestSubtract() { CPPUNIT_ASSERT(calculator.Subtract(5, 2) == 3); } }; // Create a test suite and run it int main(int argc, char* argv[]) { CppUnit::TextUi::TestRunner runner; runner.addTest(new CppUnit::TestCallerIn this example, we define a class `Calculator` that has two methods `Add()` and `Subtract()` for addition and subtraction of two numbers respectively. We then create a CppUnit test case `Test_Calculator` that verifies that both `Add()` and `Subtract()` methods behave as expected. We create two test cases `TestAdd()` and `TestSubtract()` that use the `CPPUNIT_ASSERT()` assertion macro to test the results of these functions. Finally, we create a test suite that includes both test cases and run it using the `CppUnit::TextUi::TestRunner`.("test_add", &Test_Calculator::TestAdd)); runner.addTest(new CppUnit::TestCaller ("test_subtract", &Test_Calculator::TestSubtract)); runner.run(); return 0; }