为什么我不能使用unittest.mock.patch有效地模拟函数?

时间:2018-12-26 22:08:06

标签: python python-3.x

我正在尝试为函数编写UT,并嘲笑其他函数。两者都位于同一模块中。看来 unittest.mock.patch()调用通过时没有错误,但是没有模拟任何东西,因此示例代码中出现了异常。因此,我的问题是:如何使用 unittest.mock.patch 模拟 foo

import unittest
import unittest.mock

def foo():
        raise Exception("not implemented")

def bar():
        foo()

class UT(unittest.TestCase):

        def testBar(self):
                with unittest.mock.patch('mock_test.foo',spec=True) as mock_foo:
                        bar()    # <- original foo is called here

unittest.main()

1 个答案:

答案 0 :(得分:1)

这是使用unittest.mock.patch并修补foo返回值的一种方法。请参见示例中的注释:

import unittest
from unittest.mock import patch


def foo():
        raise Exception("Not implemented")


def bar():
        return foo()


class UT(unittest.TestCase):

        def testBar(self):
            # foo is mocked to raise a ValueError and catch it during the test
            with patch('__main__.foo', side_effect=ValueError):
                with self.assertRaises(ValueError):
                    bar()

            # foo is mocked to raise and exception and catch it during the test
            with patch('__main__.foo', side_effect=Exception):
                with self.assertRaises(Exception):
                    bar()

            # foo is mocked to return 1
            with patch('__main__.foo', return_value=1):
                self.assertEqual(bar(), 1, "Should be equal to 1")

            # foo is mocked to return an object
            with patch('__main__.foo', return_value={}):
                self.assertIsInstance(bar(), dict, "Should be an instance of dict")


unittest.main()

输出:

.
----------------------------------------------------------------------
Ran 1 test in 0.001s

OK

有关更多信息,请访问official documentation