Question

I'm currently writing tests for a wsgi server I made. The server class at __init__ constructor inits 2 instances of other classes as members. Lets say

def __init__(self):
  self.a = A()
  self.b = B()

During tests, how can I mock self.a and and self.b as mock classes I made for them instead of using A and B ?

#I use this if I want to mock the entire server class
@mock.patch('myproject.server.MyServerClass',autospec=True)
Was it helpful?

Solution

The more python I write the more curious I am about situations like this. My inclination is usually to introduce dependency injection and pass in the created A and B classes on the constructor. This makes it easy to both see the external dependencies and change them up when i need. But sometimes that is overkill. Could you not just:

server = Server()
server.a = MockA()
server.b = MockB()
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top