How to supply a mock class method for python unit test?

后端 未结 3 1201
名媛妹妹
名媛妹妹 2021-02-03 20:43

Let\'s say I have a class like this.

   class SomeProductionProcess(CustomCachedSingleTon):

       def loaddata():
           \"\"\"
           Uses an iterator         


        
3条回答
  •  温柔的废话
    2021-02-03 21:45

    To easily mock out a class method with a structured return_value, can use unittest.mock.Mock.

    from unittest.mock import Mock
    
    mockObject = SomeProductionProcess
    mockObject.loaddata = Mock(return_value=True)
    

    EDIT:

    Since you want to mock out the method with a custom implementation, you could just create a custom mock method object and swap out the original method at testing runtime.

    def custom_method(*args, **kwargs):
        # do custom implementation
    
    SomeProductionProcess.loaddata = custom_method
    

提交回复
热议问题