How to pass variable to test class

Peter Otten __peter__ at web.de
Mon Apr 17 03:21:54 EDT 2006


Podi wrote:

> Newbie question about unittest. I am having trouble passing a variable
> to a test class object.
> 
> MyCase class will potentially have many test functions.

By default a unittest.TestCase has only one test function called "runTest".
Therefore you have to add multiple instances of your TestCase subclass to
the suite and to pass the test function's name to the initializer
explicitly:

import unittest

class MyTestCase(unittest.TestCase):
    def __init__(self, testname, value):
        super(MyTestCase, self).__init__(testname)
        self.value = value
    def test1(self):
        pass
    def test2(self):
        pass

if __name__ == "__main__":
    value = 42

    suite = unittest.TestSuite()
    suite.addTest(MyTestCase("test1", value))
    suite.addTest(MyTestCase("test2", value))

    unittest.TextTestRunner(verbosity=2).run(suite)

However, the standard place for common setup is in the setUp() method.

Peter




More information about the Python-list mailing list