简体   繁体   English

unittest mock 如何模拟被调用的方法

[英]unittest mock how to mock a method being called

I want to test that method a calls method b .我想测试该方法a调用方法b These methods are in separate files, and are not a part of class object.这些方法位于单独的文件中,不是类对象的一部分。

# file_a.py
from file_b import b

def a():
    b()
# file_b.py
def b():
    test
import unittest
from unittest import mock

from file_a import a

class MyTestCase(unittest.TestCase):
    @mock.patch('file_b.b')
    def test_b_called(self, mock):
        a()
        mock.assert_called()

if __name__ == "__main__":
    unittest.main()

This fails with AssertionError: Expected 'b' to have been called.这失败了AssertionError: Expected 'b' to have been called.

Is there a right way to do this?有没有正确的方法来做到这一点?

When you import a function into the current namespace, like in your example, the function will need to be patched in that namespace.当您将函数导入当前命名空间时,就像在您的示例中一样,需要在该命名空间中修补该函数。 In your case, you need:在您的情况下,您需要:

@mock.patch('file_a.b')

You would patch file_b.b if you had done the import and use like this:如果您已经完成导入和使用,您将修补file_b.b

import file_b
def a():
    file_b.b()

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

相关问题 如何对用unittest.mock调用的Django模型方法进行单元测试? - How to unittest that a django model method called with unittest.mock? 如何使用 unittest.mock 调试补丁方法 - How to debug patched method with unittest.mock Unittest Mock - 断言一个模拟对象没有被调用 - Unittest Mock - Assert a mock object is not called Python 模拟:如何模拟从正在测试的 class 方法调用的 class - Python mock: How to mock a class being called from the class method being tested 使用Python单元测试库(unittest,mock),如何断言是否在类A的方法内调用了类B的方法? - Using Python unittesting libraries (unittest, mock), how to assert if a method of class B was called within a method of class A? Python unittest模拟方法在另一个模块中调用时出错 - Python unittest mock method which called in another module work error Python unittest.mock:调用了已修补的类方法,但断言失败 - Python unittest.mock: patched class method called but assertion fails 使用 unittest.mock.patch 全局模拟方法 - Mock method globally with unittest.mock.patch 在unittest`setUp`中部分模拟一个方法 - Partially mock a method in unittest `setUp` 如何使用 Python unittest 在另一个方法中模拟一个方法? - How to mock a method inside another method with Python unittest?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM