How to stub Python methods without Mock

前端 未结 2 2014
广开言路
广开言路 2021-02-04 09:38

I\'m a C# dev moving into some Python stuff, so I don\'t know what I\'m doing just yet. I\'ve read that you don\'t really need Dependency Injection with Python. I\'ve been told

2条回答
  •  遇见更好的自我
    2021-02-04 10:23

    Python functions are first-class objects, so you can assign any function to the identifier:

    class Person:
      def greetings(self):
        return "Hi!"
    
    def happy_greetings(self):
      return "Hi! You're awesome!"
    
    mike = Person()
    mike.greetings()  # "Hi!"
    
    Person.greetings = happy_greetings
    mike.greetings()  # "Hi! You're awesome!"
    

    Think of method identifier as a reference to some function. By changing the reference, Python interpreter will find and execute whatever it refers to. However, instead of doing this by hand, I suggest you using some mature module, like unittest.mock, since there are plenty of pitfalls like managing stub scope, etc.

提交回复
热议问题