Writing a re-usable (parametrized) unittest.TestCase method

astrofrog picture astrofrog · Nov 4, 2009 · Viewed 15.2k times · Source

Possible Duplicate:
How to generate dynamic (parametrized) unit tests in python?

I'm writing tests using the unittest package, and I want to avoid repeated code. I am going to carry out a number of tests which all require a very similar method, but with only one value different each time. A simplistic and useless example would be:

class ExampleTestCase(unittest.TestCase):

    def test_1(self):
        self.assertEqual(self.somevalue, 1)

    def test_2(self):
        self.assertEqual(self.somevalue, 2)

    def test_3(self):
        self.assertEqual(self.somevalue, 3)

    def test_4(self):
        self.assertEqual(self.somevalue, 4)

Is there a way to write the above example without repeating all the code each time, but instead writing a generic method, e.g.

    def test_n(self, n):
        self.assertEqual(self.somevalue, n)

and telling unittest to try this test with different inputs?

Answer

akaihola picture akaihola · Oct 5, 2012

Some of the tools available for doing parametrized tests in Python are: