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

后端 未结 3 1200
名媛妹妹
名媛妹妹 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:33

    Here is a simple way to do it using mock

    import mock
    
    
    def new_loaddata(cls, *args, **kwargs):
        # Your custom testing override
        return 1
    
    
    def test_SomeProductionProcess():
        with mock.patch.object(SomeProductionProcess, 'loaddata', new=new_loaddata):
            obj = SomeProductionProcess()
            obj.loaddata()  # This will call your mock method
    

    I'd recommend using pytest instead of the unittest module if you're able. It makes your test code a lot cleaner and reduces a lot of the boilerplate you get with unittest.TestCase-style tests.

提交回复
热议问题