uclatommy
uclatommy

Reputation: 315

How do I unit test a python class that creates objects in the __init__ that should be mocked?

My class creates a few objects in the __init__() that communicate over HTTP. For example:

class StreamController(object):
    def __init__(self, credentials):
        self.listener = StreamListener()
        self.stream = Stream(credentials, self.listener)

    def methods_to_test(self):
        # test this stuff

How do I unit test the StreamController and replace the listener and stream variables with mock objects? I'm going to have to instance this thing to test it, but when it is created, it's going to try to communicate with the server. How do I prevent that and still test it?

Upvotes: 0

Views: 64

Answers (1)

Serge Ballesta
Serge Ballesta

Reputation: 148890

A common idiom is to use factories to create the objects:

class StreamController(object):
    _streamListenerFactory = (lambda : StreamListener())
    _streamFactory = (lambda credentials, listener: Stream(credentials, listener)
    def __init__(self, credentials):
        self.listener = _streamListenerFactory()
        self.stream = _streamFactory(credentials, self.listener)
    def methods_to_test(self):
        # test this stuff

If you need to create mocks or stubs, you just overwrite the factories before the tests:

StreamController._streamListenerFactory = (lambda : StreamListenerMock())
StreamController._streamFactory = ...

Upvotes: 1

Related Questions