Python Mock Multiple Calls with Different Results

前端 未结 3 1532
小鲜肉
小鲜肉 2021-02-03 19:06

I want to be able to have multiple calls to a particular attribute function return a different result for each successive call.

In the below example, I would like increm

3条回答
  •  伪装坚强ぢ
    2021-02-03 19:55

    I think the popping values off of a list method will be more straightforward. The below example works for the test you wanted to perform.

    Also, I've had a difficult time with the mock library before and have found that the mock.patch.object() method was typically easier to use.

    import unittest
    import mock
    
    
    class A:
        def __init__(self):
            self.size = 0
    
        def increment(self, amount):
            self.size += amount
            return amount
    
    incr_return_values = [5, 10]
    
    
    def square_func(*args):
        return incr_return_values.pop(0)
    
    
    class TestMock(unittest.TestCase):
    
        @mock.patch.object(A, 'increment')
        def test_mock(self, A):
            A.increment.side_effect = square_func
    
            self.assertEqual(A.increment(1), 5)
            self.assertEqual(A.increment(-20), 10)
    

提交回复
热议问题