title: How do I mock part of a python constructor just for testing?
body: <p>I am new to Python, so I apologize if this is a duplicate or overly simple question. I have written a coordinator class that calls two other classes that use the kafka-python library to send/read data from Kafka. I want to write a unit test for my coordinator class but I'm having trouble figuring out how to best to go about this. I was hoping that I could make an alternate constructor that I could pass my mocked objects into, but this doesn't seem to be working as I get an error that test_mycoordinator cannot be resolved. Am I going about testing this class the wrong way? Is there a pythonic way I should be testing it?</p>
  
  <p>Here is what my test class looks like so far:</p>
  
  <pre><code>import unittest
  from mock import Mock
  from mypackage import mycoordinator
  
  class MyTest(unittest.TestCase):
  
      def setUpModule(self):
          # Create a mock producer
          producer_attributes = ['__init__', 'run', 'stop']
          mock_producer = Mock(name='Producer', spec=producer_attributes)
  
          # Create a mock consumer
          consumer_attributes = ['__init__', 'run', 'stop']
          data_out = [{u'dataObjectID': u'test1'},
                      {u'dataObjectID': u'test2'},
                      {u'dataObjectID': u'test3'}]
          mock_consumer = Mock(
              name='Consumer', spec=consumer_attributes, return_value=data_out)
  
          self.coor = mycoordinator.test_mycoordinator(mock_producer, mock_consumer)
  
      def test_send_data(self):
          # Create some data and send it to the producer
          count = 0
          while count &lt; 3:
              count += 1
              testName = 'test' + str(count)
              self.coor.sendData(testName , None)
  </code></pre>
  
  <p>And here is the class I am trying to test:</p>
  
  <pre><code>class MyCoordinator():
      def __init__(self):
          # Process Command Line Arguments using argparse  
          ...
  
          # Initialize the producer and the consumer
          self.myproducer = producer.Producer(self.servers,
                                              self.producer_topic_name)
  
          self.myconsumer = consumer.Consumer(self.servers,
                                              self.consumer_topic_name)
  
      # Constructor used for testing -- DOES NOT WORK
      @classmethod
      def test_mycoordinator(cls, mock_producer, mock_consumer):
          cls.myproducer = mock_producer
          cls.myconsumer = mock_consumer
  
      # Send the data to the producer
      def sendData(self, data, key):
          self.myproducer.run(data, key)
  
      # Receive data from the consumer
      def getData(self):
          data = self.myconsumer.run()
          return data
  </code></pre>