简体   繁体   中英

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?

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 = ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM