TJ1S
TJ1S

Reputation: 528

Testing function called in object's __init__

I have a class that looks like this:

class myClass(object):
     def __init__(self, arg1):
         self.arg1 = arg1
         self.build_connection()

     def build_connection(self):
         if self.arg1 != 'foo':
             raise Exception('ohno')
         <more code that could potentially raise an exception>

I would like to test the build_connection function within the class, but I'm not sure what the best way / most Pythonic way of doing that would be. I realize that I could create the object and mock out the various functions called in build_connection, but I was wondering if there was a way to test build_connection independently of the object being created, ie I don't want to necessarily do something like this:

 try:
     class = myClass('foo')
 except Exception:
     self.fail('should have initialized correctly')

I'd rather do something more like this:

 myclass = myClass('bar')
 # mock various properties in build_connection
 myclass.build_connection()

Upvotes: 1

Views: 667

Answers (1)

chepner
chepner

Reputation: 531035

If you really want to test build_connection without otherwise instantiating the class, mock the object itself.

mock_instance = mock.Mock()
# set up necessary attributes here
myClass.build_connection(mock_instance)
# examine mock_instance

Upvotes: 1

Related Questions