How to mock Python static methods and class methods

前端 未结 2 891
鱼传尺愫
鱼传尺愫 2021-02-07 17:14

How do I mock a class that has unbound methods? For example, this class has a @classmethod and a @staticmethod:

class Calculator(objec         


        
2条回答
  •  深忆病人
    2021-02-07 18:10

    You were patching the wrong object. You must patch the Calculator from the Machine class, not the general Calculator class. Read about it here.

    from mock import patch
    import unittest
    
    from calculator import Calculator
    from machine import Machine
    
    
    class TestMachine(unittest.TestCase):
        def my_mocked_mult(self, multiplier):
            return 2 * multiplier * 3
        def test_bound(self):
            '''The bound methods of Calculator are replaced with MockCalculator'''
            machine = Machine(Calculator(3))
            with patch.object(machine, "mult") as mocked_mult:
                mocked_mult.side_effect = self.my_mocked_mult
                self.assertEqual(machine.mult(3), 18)
                self.assertEqual(machine.incr_bound(3), 5)
                self.assertEqual(machine.decr_bound(3), 1)
    
        def test_unbound(self):
            '''Machine.incr_unbound() and Machine.decr_unbound() are still using
            Calculator.increment() and Calculator.decrement(n), which is wrong.
            '''
            machine = Machine(Calculator(3))
            self.assertEqual(machine.incr_unbound(3), 4)    # I wish this was 5
            self.assertEqual(machine.decr_unbound(3), 2)    # I wish this was 1
    

提交回复
热议问题