首页 > 解决方案 > 似乎无法在另一个文件中修补类和方法

问题描述

我一直在用这样的小模型把头撞在墙上:

这是树:

src
├── __init__.py
├── file_a.py
├── file_b.py


test
├── test_a.py

在 file_a 中:

class qaz(object):
    def __init__(self):
        print("\n\nin qaz")

    def exec_bar(self):
        bar_inst = bar()
        bar_inst.execute("a", "b")

在 file_b 中:

class bar(object):
    def __init__(self, a, b):
        print("\n\nin bar")

    def execute(self, c, d):
        print("\n\nin bar -> execute")

所以,我想模拟bar,以便我可以a毫无问题地进行测试。

在 test_a 中:

from unittest.mock import patch, MagicMock
from src.file_a import qaz
from src.file_b import bar

class BarTester(unittest.TestCase):

    @patch('src.file_b.bar')
    def test_bar(self, mock_bar):
        bar_inst = MagicMock()
        bar_inst.execute.return_value = None
        mock_bar.return_value = bar_inst

        q = qaz()
        q.exec_bar()

每次都会失败,如下所示:

TypeError: __init__() missing 2 required positional arguments: 'a' and 'b'

这意味着模拟不起作用。我似乎无法弄清楚我做错了什么。

标签: pythonpython-3.xmockingpython-unittestmagicmock

解决方案


在 file_b 中,您期望在“ init ”中传递 2 个参数
def __init__(self, a, b):

但是在为类栏创建对象时,在 file_a 中,您没有传递任何参数
bar_inst = bar()

这就是您看到错误的原因
TypeError: __init__() missing 2 required positional arguments: 'a' and 'b'

你做两件事:

  1. 删除参数 a 和 bdef __init__(self, a, b):
  2. 传递参数时

新解决方案:

from mock import patch
import unittest
from src.file_a import qaz
from src.file_b import bar

class BarTester(unittest.TestCase):

    @patch.object(bar, '__init__', return_value=None)
    def test_bar(self, *mock_stdout):
        q = qaz()
        q.exec_bar()



推荐阅读