I had to do something similar. I created simple TestCase subclasses that took a value in their __init__, like this:

class KnownGood(unittest.TestCase):
    def __init__(self, input, output):
        super(KnownGood, self).__init__()
        self.input = input
        self.output = output
    def runTest(self):
        self.assertEqual(function_to_test(self.input), self.output)

I then made a test suite with these values:

def suite():
    suite = unittest.TestSuite()
    suite.addTests(KnownGood(input, output) for input, output in known_values)
    return suite

You can then run it from your main method:

if __name__ == '__main__':
    unittest.TextTestRunner().run(suite())

The advantages of this are:

  • As you add more values, the number of reported tests increases, which makes you feel like you are doing more.
  • Each individual test case can fail individually
  • It's conceptually simple, since each input/output value is converted into one TestCase
Answer from Amandasaurus on Stack Overflow
Top answer
1 of 6
57

I had to do something similar. I created simple TestCase subclasses that took a value in their __init__, like this:

class KnownGood(unittest.TestCase):
    def __init__(self, input, output):
        super(KnownGood, self).__init__()
        self.input = input
        self.output = output
    def runTest(self):
        self.assertEqual(function_to_test(self.input), self.output)

I then made a test suite with these values:

def suite():
    suite = unittest.TestSuite()
    suite.addTests(KnownGood(input, output) for input, output in known_values)
    return suite

You can then run it from your main method:

if __name__ == '__main__':
    unittest.TextTestRunner().run(suite())

The advantages of this are:

  • As you add more values, the number of reported tests increases, which makes you feel like you are doing more.
  • Each individual test case can fail individually
  • It's conceptually simple, since each input/output value is converted into one TestCase
2 of 6
41

Not tested:

class TestPreReqs(unittest.TestCase):
    ...

def create_test (pair):
    def do_test_expected(self):
        self.assertEqual(under_test(pair[0]), pair[1])
    return do_test_expected

for k, pair in enumerate ([(23, 55), (4, 32)]):
    test_method = create_test (pair)
    test_method.__name__ = 'test_expected_%d' % k
    setattr (TestPreReqs, test_method.__name__, test_method)

If you use this often, you could prettify this by using utility functions and/or decorators, I guess. Note that pairs are not an attribute of TestPreReqs object in this example (and so setUp is gone). Rather, they are "hardwired" in a sense to the TestPreReqs class.

🌐
Reddit
reddit.com › r/python › how to use unittest to test multiple cases with assertequal in python?
r/Python on Reddit: How to use unittest to test multiple cases with assertEqual in python?
January 16, 2017 -

I've read the docs here on unittest but I am confused on how should I test multiple test where I have to use only use assertEquals. import unittest

class TestStringMethods(unittest.TestCase):
    def test_upper(self):
        self.assertEqual('foo'.upper(), 'FOO')
        self.assertEqual('too'.upper(), 'TOO')
        self.assertEqual('poo'.upper(), 'POO')
if __name__ == '__main__':
    unittest.main()

So, If I run this it shows only one test run, I understand why it shows that but how should I organize the test so that I get to know which assertions passed and which failed because it will show the failed ones and i will not have much control over them.

For example my test cases will look something like this,

[{ inputString: 'i like to sleep', 
  outputDict: {sleepHours: 7, likes: 'sleeping' } 
},{...},{...},{...}]
Discussions

python - Creating a test suite from multiple test cases - Stack Overflow
I've looked at nosetests, and it ... from multiple cases in a suite without depending on an external library. ... Did you try to create a TestSuite from a list of suites created with TestLoader? This is an example adapted from Python documentation: suite1 = unittest.TestLoade... More on stackoverflow.com
🌐 stackoverflow.com
unit testing - Multiple tests per method, new workplace - Python - Software Engineering Stack Exchange
I am learning unit testing on the job, at a new job. The testing team is small, (1 other), and all of the tests are written in the following fashion. class TestClass(unittest.TestCase): def More on softwareengineering.stackexchange.com
🌐 softwareengineering.stackexchange.com
May 17, 2017
How do I run multiple Python test cases in a loop? - Stack Overflow
I am new to Python and trying to do something I do often in Ruby. Namely, iterating over a set of indices, using them as argument to function and comparing its results with an array of fixture outp... More on stackoverflow.com
🌐 stackoverflow.com
June 28, 2016
How do I run multiple Classes in a single test suite in Python using unit testing? - Stack Overflow
How do I run multiple Classes in a single test suite in Python using unit testing? ... Did you mean this? stackoverflow.com/questions/1732438/… It runs multiple python test classes in a directory More on stackoverflow.com
🌐 stackoverflow.com
🌐
Python
docs.python.org › 3 › library › unittest.html
unittest — Unit testing framework
The testing code of a TestCase instance should be entirely self contained, such that it can be run either in isolation or in arbitrary combination with any number of other test cases. The simplest TestCase subclass will simply implement a test method (i.e. a method whose name starts with test) in order to perform specific testing code: import unittest class DefaultWidgetSizeTestCase(unittest.TestCase): def test_default_widget_size(self): widget = Widget('The widget') self.assertEqual(widget.size(), (50, 50))
🌐
techno milk
technomilk.wordpress.com › 2012 › 02 › 12 › multiplying-python-unit-test-cases-with-different-sets-of-data
Multiplying Python Unit Test Cases with Different Sets of Data | techno milk
February 29, 2012 - Unhappy with the situation of not ... or Data-Decorated Tests). It allows developers to create multiple test cases from a single test method, feeding it different data using a decorator....
🌐
DigitalOcean
digitalocean.com › community › tutorials › how-to-use-unittest-to-write-a-test-case-for-a-function-in-python
How To Use unittest to Write a Test Case for a Function in Python | DigitalOcean
September 30, 2020 - Tests written using the unittest module can help you find bugs in your programs, and prevent regressions from occurring as you change your code over time. Te…
Find elsewhere
🌐
Dataquest
dataquest.io › home › blog › a beginner's guide to unit tests in python
A Beginner's Guide to Unit Tests in Python
April 8, 2025 - Among the numerous tools provided by unittest that allow us to test code, this class is one of the most important ones. It's used as a base class to create our own test cases that enable us to run multiple tests at once.
🌐
Medium
raphaeldelio.medium.com › getting-started-with-unit-tests-in-python-part-2-unittest-module-66fbf967b1d4
Getting Started With Unit Tests In Python — Part 2: unittest module | Medium
February 27, 2024 - TestSuite class: This allows you to organize and run multiple test cases together. Thus, you can spend more time thinking about designing your test cases instead of designing your testing modules. import unittest class SeatFinderTest(unittest.TestCase): def test_prefer_near_the_front(self): finder = SeatFinder(available_seats={"A1", "B4", "H2"}) seats = finder.find_seats_in_front(1) self.assertEqual(["A1"], seats) if __name__ == '__main__': unittest.main()
Top answer
1 of 5
51

If you want to run all of the tests from a specific list of test classes, rather than all of the tests from all of the test classes in a module, you can use a TestLoader's loadTestsFromTestCase method to get a TestSuite of tests for each class, and then create a single combined TestSuite from a list containing all of those suites that you can use with run:

import unittest

# Some tests

class TestClassA(unittest.TestCase):
    def testOne(self):
        # test code
        pass

class TestClassB(unittest.TestCase):
    def testOne(self):
        # test code
        pass

class TestClassC(unittest.TestCase):
    def testOne(self):
        # test code
        pass

def run_some_tests():
    # Run only the tests in the specified classes

    test_classes_to_run = [TestClassA, TestClassC]

    loader = unittest.TestLoader()

    suites_list = []
    for test_class in test_classes_to_run:
        suite = loader.loadTestsFromTestCase(test_class)
        suites_list.append(suite)
        
    big_suite = unittest.TestSuite(suites_list)

    runner = unittest.TextTestRunner()
    results = runner.run(big_suite)

    # ...

if __name__ == '__main__':
    run_some_tests()
2 of 5
26

I'm a bit unsure at what you're asking here, but if you want to know how to test multiple classes in the same suite, usually you just create multiple testclasses in the same python file and run them together:

import unittest

class TestSomeClass(unittest.TestCase):
    def testStuff(self):
            # your testcode here
            pass

class TestSomeOtherClass(unittest.TestCase):
    def testOtherStuff(self):
            # testcode of second class here
            pass

if __name__ == '__main__':
    unittest.main()

And run with for example:

python mytestsuite.py

Better examples can be found in the official documention.

If on the other hand you want to run multiple test files, as detailed in "How to organize python test in a way that I can run all tests in a single command?", then the other answer is probably better.

🌐
Real Python
realpython.com › python-testing
Getting Started With Testing in Python – Real Python
June 10, 2026 - Within your test case, you can ... tests against that test data. Remember you can have multiple test cases in a single Python file, and the unittest discovery will execute both....
Top answer
1 of 3
6

You can put the asserts in a loop:

def test_fact(self):
    tests = [(1,1), (2,2), (3,6), (4,24), (5,120)]
    for n,f in tests:
        self.assertEqual(fact(n), f)
2 of 3
5

I'd say your ways of doing it is generally fine (but read on).

You could, as interjay suggested, do a loop (and, incidentally, it only counts as one test because the unittest module counts the number of functions, not the number of asserts). But I assume you won't exhaustively try to test every number, or even all numbers within a very large interval. So looping won't save you much, and, especially in testing, you should aim at being explicit.

Having said that, you should test for a small number of subsequent numbers (say, 1 through 5), and then try to get a feel for where possible corner cases and failures points are. Say, test for 10, 100, 1000 (that is, change order of magnitude), negative numbers, zero etc.

BTW, watch out for your two last tests. The first of them doesn't mean much. fact(5) is different than a LOT of numbers (infinite numbers, actually). Test for the correct case, testing for the incorrect ones isn't productive.

def test_fact_5(self):
    self.assertFalse(1==fact(5))

The second one is badly named: "test_fact_6" makes me think you're testing fact(6). You should name it as something like "test_fact_minus_one", or at least "test_fact_negative_number".

def test_fact_6(self):
    self.assertRaises(RuntimeError, fact, -1)

Test naming is very important, both when you're debugging errors and when you refer back to the tests as documentation.

🌐
Real Python
realpython.com › python-unittest
Python's unittest: Writing Unit Tests for Your Code – Real Python
April 29, 2024 - It can read the test cases from your project’s documentation and your code’s docstrings. This framework is shipped with the Python interpreter as part of the batteries-included philosophy. Note: To dive deeper into doctest, check out the Python’s doctest: Document and Test Your Code at Once tutorial. The unittest package is also a testing framework.
🌐
Python
docs.python.org › 3.4 › library › unittest.html
26.3. unittest — Unit testing framework — Python 3.4.10 documentation
The testing code of a TestCase instance should be entirely self contained, such that it can be run either in isolation or in arbitrary combination with any number of other test cases. The simplest TestCase subclass will simply implement a test method (i.e. a method whose name starts with test) in order to perform specific testing code: import unittest class DefaultWidgetSizeTestCase(unittest.TestCase): def test_default_widget_size(self): widget = Widget('The widget') self.assertEqual(widget.size(), (50, 50))
🌐
Wellsr
wellsr.com › python › unittest-examples-for-testing-python-code
Python unittest Examples for Testing Python Code - wellsr.com
December 29, 2020 - That means when the unittest module passed 5 to your take_square function, it successfully calculated a result of 25. Your function behaved as expected. You can also unit test multiple Python functions with the unittest module.
🌐
OneUptime
oneuptime.com › home › blog › how to use unittest module in python
How to Use unittest Module in Python
January 28, 2026 - # test_subtests.py # Using subtests for parameterized testing import unittest def is_palindrome(s): """Check if string is a palindrome.""" s = s.lower().replace(' ', '') return s == s[::-1] class TestPalindrome(unittest.TestCase): """Tests for palindrome function using subtests.""" def test_palindromes(self): """Test multiple palindrome cases.""" test_cases = [ ('radar', True), ('level', True), ('A man a plan a canal Panama', True), ('hello', False), ('world', False), ('', True), ] for text, expected in test_cases: with self.subTest(text=text): result = is_palindrome(text) self.assertEqual(result, expected)
🌐
GitHub
gist.github.com › aychedee › 5244147
Demonstration running a test multiple times using unittest · GitHub
Demonstration running a test multiple times using unittest · Raw · gistfile1.py · This file contains hidden or 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.