1
votes

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()
1
I'm not sure, what's wrong with the first test? That's exactly how other code would use the class, so that part should work and be tested as such.Martijn Pieters
You can use the TestCase.assertRaises() method to test for exceptions, if your code should raise one.Martijn Pieters
@MartijnPieters there's nothing necessarily wrong with it, I was just trying to decouple it.TJ1S
You don't need to decouple it; it is part of the unit under test; you are testing the myClass unit here.Martijn Pieters

1 Answers

1
votes

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