How to mock python's datetime.now() in a class method for unit testing?

前端 未结 7 1238
南旧
南旧 2020-12-14 05:38

I\'m trying to write tests for a class that has methods like:

import datetime
import pytz

class MyClass:
    def get_now(self, timezone):
        return dat         


        
7条回答
  •  无人及你
    2020-12-14 06:12

    If you don't want to install anything this is the simplest way. Simply use, Mock class -

    class NewDt(datetime.date):
        @classmethod
         def now(cls):
               return datetime.datetime.strptime('2020-07-10 05:20:20', '%Y-%m-%d %H:%M:%S')
    

    And use this patch before mock function

     @mock.patch('module path', NewDt)
    

提交回复
热议问题