[BangPypers] issues using constructor in unittest

Senthil Kumaran orsenthil at gmail.com
Mon Mar 14 10:46:45 CET 2011


On Mon, Mar 14, 2011 at 03:00:01PM +0530, Nitin Kumar wrote:
> Hi Navin,
> I can't use setUp as this will be called every time for each test cases, I
> thought of using setUpClass decorator but there i can define self.
> 
> import unittest2
> class XMLSupport(unittest2.TestCase):
>         def __init__(self):
>                 super(XMLSupport,self).__init__(*args, **kwargs)
>                 self.x = 3
> 

You don't have constructor for unittest class. Because of the way
unittest framework works, (namely creates testobjects for its
purposes), creating an object is not recommended. I have not seen any
code doing it. For what you are trying to do, you could do something
like this:

(Follow along and modify as per your requirement)

import unittest

x = 100

class XMLSupport(unittest.TestCase):

    def setUp(self):
        print 'In setup'
        self.x = 3
    
    def test_3(self):
        print(self.x)
        self.x += 1
        global x
        x += 1

    def test_4(self):
        print(self.x)
        print(x)

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



More information about the BangPypers mailing list