Mocking Functions Using Python Mock

后端 未结 5 1967
清酒与你
清酒与你 2020-12-01 06:08

I am trying to Mock a function (that returns some external content) using the python mock module.

I\'m having some trouble mocking functions that are im

5条回答
  •  無奈伤痛
    2020-12-01 06:41

    Let's assume you're creating your mock inside module foobar:

    import util, mock
    util.get_content = mock.Mock(return_value="mocked stuff")
    

    If you import mymodule and call util.get_content without first importing foobar, your mock will not be installed:

    import util
    def func()
        print util.get_content()
    func()
    "stuff"
    

    Instead:

    import util
    import foobar   # substitutes the mock
    def func():
        print util.get_content()
    func()
    "mocked stuff"
    

    Note that foobar can be imported from anywhere (module A imports B which imports foobar) as long as foobar is evaluated before util.get_content is called.

提交回复
热议问题