Debug School

rakesh kumar
rakesh kumar

Posted on

How to grouping test and run test cases in unittest

In unittest, you can group tests using test suites and test case classes. Here's a checklist of classes and functions for grouping tests within test cases in unittest, along with examples and output:

Checklist of Classes and Functions for Grouping Tests in unittest

unittest.TestSuite() - A class for creating test suites, which are used to group and run multiple test cases or test methods.

addTest(test) - A method to add a single test case or test method to a test suite.

addTests(tests) - A method to add multiple test cases or test methods to a test suite.

unittest.defaultTestLoader.loadTestsFromTestCase(testCase) - A method to load test cases from a test case class.

unittest.defaultTestLoader.loadTestsFromModule(module) - A method to load tests from a Python module.

Example and Output:

Here's an example that demonstrates how to create test suites and group tests using the above classes and functions:

import unittest

# Test case classes
class TestMathOperations(unittest.TestCase):
    def test_addition(self):
        self.assertEqual(2 + 2, 4)

class TestStringOperations(unittest.TestCase):
    def test_string_concatenation(self):
        result = "Hello, " + "World!"
        self.assertEqual(result, "Hello, World")

# Create test suites
math_tests = unittest.TestLoader().loadTestsFromTestCase(TestMathOperations)
string_tests = unittest.TestLoader().loadTestsFromTestCase(TestStringOperations)

# Create a test suite to group all tests
all_tests = unittest.TestSuite([math_tests, string_tests])

if __name__ == '__main__':
    unittest.TextTestRunner(verbosity=2).run(all_tests)
Enter fullscreen mode Exit fullscreen mode

Expected Output:

When you run the tests, the output will show the results for all the grouped tests:

test_addition (TestMathOperations) ... ok
test_string_concatenation (TestStringOperations) ... ok

----------------------------------------------------------------------
Ran 2 tests in 0.001s

OK
Enter fullscreen mode Exit fullscreen mode

In this example:

  1. Two test case classes, TestMathOperations and TestStringOperations, contain individual test methods.
  2. Test suites (math_tests and string_tests) are created using loadTestsFromTestCase.
  3. A final test suite (all_tests) is created to group all the test cases.
  4. The unittest.TextTestRunner runs all the tests and produces the output, showing the results for both test case classes . This demonstrates how to use test suites to group and run tests from different test case classes. You can also create custom test suites and organize your tests based on your project's needs.

Refrence

Top comments (0)