Mocking out methods on any instance of a python class

前端 未结 5 538
悲&欢浪女
悲&欢浪女 2020-12-08 18:57

I want to mock out methods on any instance of some class in the production code in order to facilitate testing. Is there any library in Python which could facilitate this?

5条回答
  •  难免孤独
    2020-12-08 19:37

    Mock is the way to do it, alright. It can be a bit tricky to make sure you're patching the instance method on any instances created from the class.

    # a.py
    class A(object):
        def foo(self):
            return "A's foo"
    
    # b.py
    from a import A
    
    class B(object):
        def bar(self):
            x = A()
            return x.foo()
    
    # test.py
    from a import A
    from b import B
    import mock
    
    mocked_a_class = mock.Mock()
    mocked_a_instance = mocked_a_class.return_value
    mocked_a_instance.foo.return_value = 'New foo'
    
    with mock.patch('b.A', mocked_a_class):  # Note b.A not a.A
        y = B()
        if y.bar() == "New foo":
            print "Success!"
    

    Referenced in the docs, at the para starting "To configure return values on methods of instances on the patched class..."

提交回复
热议问题