6
import unittest

class A(unittest.TestCase):
    def setUp(self):
        print "Hi it's you",self._testMethodName

    def test_one(self):
        self.assertEqual(5,5)

    def tearDown(self):
        print "Bye it's you", self._testMethodName

class B(A,unittest.TestCase): 

    def setUp(self):
        print "Hi it's me", self._testMethodName

    def test_two(self):
        self.assertNotEqual(5,5)


unittest.main()

Output :

Hi it's you test_one
Bye it's you test_one
.Hi it's me test_one
Bye it's you test_one
.Hi it's me test_two
FBye it's you test_two

======================================================================
FAIL: test_two (__main__.B)
----------------------------------------------------------------------

Traceback (most recent call last):
  File "try_test_generators.py", line 19, in test_two
    self.assertNotEqual(5,5)
AssertionError: 5 == 5

----------------------------------------------------------------------
Ran 3 tests in 0.005s

FAILED (failures=1)

In the above code, the test case test_one is using the setUp() of class A. However in the derived class test_one is using the setUp() of class B. Is there a way by which I can use the setUp() of A for every test case derived from it??.

wonder
  • 885
  • 1
  • 18
  • 32

2 Answers2

9

Just make sure to call super, in every child class where you've overridden it.

class B(A, unittest.TestCase):

    def setUp(self):
        print "Hi it's me", self._testMethodName
        super(B, self).setUp()
hspandher
  • 15,934
  • 2
  • 32
  • 45
  • I tried your approach. It's calling the `setUp()` of A as well as `setUp()` of B. I want to use only `setUp()` of A. – wonder May 03 '17 at 10:00
  • 1
    Don't override setUp in B then. – hspandher May 03 '17 at 10:01
  • I think this answer can still be improved. By using this solution, we still end up with 3 tests. test_one running in A an B, then test_two in B. Is there a way to use only setUp from another class so we only have the two tests ran? – DanBC Dec 15 '21 at 13:40
1

You can try this code:

import unittest

class A(unittest.TestCase):
    def setUp(self):
        print("Hi it's you", self._testMethodName)

    def test_one(self):
        self.assertEqual(5, 5)

    def tearDown(self):
        print("Bye it's you", self._testMethodName)

class B(A, unittest.TestCase):

    def setUp(self):
        test = A()
        super(B, B).setUp(test)

    def test_two(self):
        self.assertNotEqual(5, 5)

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

Here is where I got some inspiration about problems like this:

  1. TypeError: attack() missing 1 required positional argument: 'self'

  2. super() and @staticmethod interaction

ndrwnaguib
  • 5,623
  • 3
  • 28
  • 51
stefan.stt
  • 2,357
  • 5
  • 24
  • 47