简体   繁体   English

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

[英]Why I cannot effectively mock function with unittest.mock.patch?

I'm trying to write UT for function with other function mocked.我正在尝试为其他函数编写 UT 函数。 Both lies in the same module.两者都在同一个模块中。 It appears that unittest.mock.patch() call passes without error but doesn't mock anything so I'm getting exception in the example code.看起来unittest.mock.patch()调用通过而没有错误,但没有模拟任何东西,所以我在示例代码中遇到了异常。 So, my question is: How to mock foo with 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()

Here is a way to use unittest.mock.patch and patch the foo returns.这是一种使用unittest.mock.patch并修补foo返回值的方法。 See the comments in the example:请参阅示例中的注释:

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

Output:输出:

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

OK

For more informations, please visit the official documentation更多信息请访问官方文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM