为什么我不能用unittest.mock.patch?

2024-04-20 02:54:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试为函数编写UT,同时模拟其他函数。两者位于同一模块中。似乎unittest.mock.补丁()调用传递没有错误,但没有模拟任何东西,因此示例代码中出现异常。所以,我的问题是:如何用unittest.mock.补丁?你知道吗

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()

Tags: 模块函数代码import示例foodef错误
1条回答
网友
1楼 · 发布于 2024-04-20 02:54:29

下面是一种使用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

相关问题 更多 >