8

Is there a way to pass arguments to the setUp() method from a given test, or some other way to simulate this? e.g.,

import unittest

class MyTests(unittest.TestCase):
    def setUp(self, my_arg):
        # use the value of my_arg in some way

    def test_1(self):
        # somehow have setUp use my_arg='foo'
        # do the test

    def test_2(self):
        # somehow have setUp use my_arg='bar'
        # do the test
Rob Bednark
  • 25,981
  • 23
  • 80
  • 125
  • @Jan_Vlcinsky, note that my question is about passing arguments from the test, whereas the question you mentioned is about passing arguments from the command line. – Rob Bednark May 08 '14 at 23:43
  • 1
    Oh, I see. As SetUp is always called before any `test_*`, I thought, you want to run the set of test with different context. Your answer is clear solution for your needs. – Jan Vlcinsky May 08 '14 at 23:47

1 Answers1

10

setUp() is a convenience method and doesn't have to be used. Instead of (or in addition to) using the setUp() method, you can use your own setup method and call it directly from each test, e.g.,

class MyTests(unittest.TestCase):
    def _setup(self, my_arg):
        # do something with my_arg

    def test_1(self):
        self._setup(my_arg='foo')
        # do the test

    def test_2(self):
        self._setup(my_arg='bar')
        # do the test
Rob Bednark
  • 25,981
  • 23
  • 80
  • 125