2017-02-24 69 views
0

我的班級在__init__()中通過HTTP進行通信時創建了一些對象。例如:如何測試在應該被模擬的__init__中創建對象的python類?

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

    def methods_to_test(self): 
     # test this stuff 

如何單元測試StreamController與模仿對象替換listenerstream變量?我將不得不實例化這個東西來測試它,但是當它被創建時,它將嘗試與服務器進行通信。我如何防止並仍在測試?

回答

1

一個常見的成語是使用工廠來創建對象:

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 

如果你需要創建嘲笑或存根,你只是在測試之前,覆蓋工廠:

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

的偉大工程。謝謝。沒有意識到這個成語。 – uclatommy

+0

@uclatommy事實上,它在Java語言中很常見... –

相關問題