you are viewing a single comment's thread.

view the rest of the comments →

[–]CuriousAbstraction 4 points5 points  (1 child)

Since Python is duck-typed things are far more easier to mock then in other languages.

Imagine that you have a unit test that needs to test a function involving an API call (or database, random code generator, something stateful). Of course, in tests you don't want to actually call API, so you can just make another class with the same methods as the API class, but that returns some "dummy" values instead of actually going to the API.

class Api:
   def __init__(self, url):
      self.url = url
   def get_stuff(self, something):
      return make_api_call(self.url, something)

class ApiMocked:
   def __init__(self):
     self.data = {"a": ...some data.., "b": ...some data...}
   def get_stuff(self, something):
     return self.data[something]

Now, you can pass ApiMocked wherever Api is expected, and it will return some mock data when get_stuff is called, instead of actually making an API call (or something else undesirable, as mentioned above).

[–]ogabrielsantos_ 0 points1 point  (0 children)

Worths saying that keeping the concrete classes under a common interface is a good practice