您可以模拟函数定义吗?

时间:2020-10-12 20:55:17

标签: python unit-testing mocking python-unittest

说我有一堂课:

class AutoShopComponent: 
 
   def onArrival(self, Car):
       carClassifier = CarClassifier(car)
       
       if carClassifier.engine_life < 10:
          # send it to place X
       else
          # send it to place Y

   class CarClassifier: 
      def __init__(self, car): 
          self.model = car.model
          self.mileage = car.mileage
          self.engine_life = -1

      def determineEngineLife(self):
          if self.mileage > 100000:
              self.engine_life = 10
          # more code

我想测试汽车是否真的被送到了正确的地方。 结果,我想“覆盖”确定EngineLife,如果它小于10 它被发送到位置X,否则它被发送到位置Y。 可以用ock.patch完成吗?什么是测试的最佳实践 这个吗?

Test A:

with mock.patch('AutoShopComponent.CarClassifier.determineEngineLife') as mock_determine_engine_life:
     # override determineEngineLife to set self.engine_life = 9

# test onMessage and see if it gets sent to place X

Test B:

with mock.patch('AutoShopComponent.CarClassifier.determineEngineLife') as mock_determine_engine_life:
     # override determineEngineLife to set self.engine_life = 11

# test onMessage and see if it gets sent to place Y

0 个答案:

没有答案