How do I directly mock a superclass with python mock?

前端 未结 2 1585
孤独总比滥情好
孤独总比滥情好 2020-12-30 02:23

I am using the python mock framework for testing (http://www.voidspace.org.uk/python/mock/) and I want to mock out a superclass and focus on testing the subclasses\' added b

2条回答
  •  醉酒成梦
    2020-12-30 03:03

    is there a way for me to interject here and to somehow get it to utilize a mock.Mock() on the fly?

    There may be better approaches, but you can always write your own super() and inject it into the module that contains the class you're mocking. Have it return whatever it should based on what's calling it.

    You can either just define super() in the current namespace (in which case the redefinition only applies to the current module after the definition), or you can import __builtin__ and apply the redefinition to __builtin__.super, in which case it will apply globally in the Python session.

    You can capture the original super function (if you need to call it from your implementation) using a default argument:

    def super(type, obj=None, super=super):  
        # inside the function, super refers to the built-in
    

提交回复
热议问题