python - 模拟父类 __init__ 方法

标签 python python-2.7 unit-testing mocking

我正在尝试在派生自另一个类的类上编写一些单元测试,但我在模拟父类 init 方法时遇到一些困难,而 afaik 你做不到,所以我正在寻找建议.

这是我的类(class)的例子

导入.py

class Imported():
    def __init__(self, a="I am Imported"):
        print("a:{}".format(a))

父类.py

from Imported import Imported

class Parent(object):

    parent_list = ["PARENT"]

    def __init__(self, a="I am Parent"):
        imported = Imported(a)

派生.py

from Parent import Parent

class Derived(Parent):

    Parent.parent_list.append("DERIVED")

在我的单元测试中,当我从派生类 Derived() 实例化一个对象时,我想验证 Parent.parent_list == ["PARENT", "DERIVED"]。

这两种解决方案都行不通

test_Derived.py

import unittest
from mock import patch

from Derived import Derived


class test_Derived(unittest.TestCase):

    @patch("Derived.Parent.__init__")
    def test_init_001(self, mock_parent_init):
        a = Derived("I am Derived")
        mock_parent_init.assert_called_with("I am Derived")
        self.assertEquals(a.parent_list, ["PARENT", "DERIVED"])

    @patch("Derived.Imported.Imported")
    def test_init_002(self, mock_parent_init):
        a = Derived("I am Derived")
        mock_parent_init.assert_called_with("I am Derived")
        self.assertEquals(a.parent_list, ["PARENT", "DERIVED"])

test_init_001 失败

TypeError: __init__() should return None, not 'MagicMock'

test_init_002 失败

ImportError: No module named Parent.Imported

有什么建议吗?

最佳答案

对于第一种方案,将__init__方法的返回值改为None

@patch("Derived.Parent.__init__")
def test_init_001(self, mock_parent_init):
    mock_parent_init.return_value = None  # <---
    a = Derived("I am Derived")
    mock_parent_init.assert_called_with("I am Derived")
    self.assertEquals(a.parent_list, ["PARENT", "DERIVED"])

对于第二种解决方案,修补Parent.Imported:

@patch("Parent.Imported")  # <---
def test_init_002(self, mock_parent_init):
    a = Derived("I am Derived")
    mock_parent_init.assert_called_with("I am Derived")
    self.assertEquals(a.parent_list, ["PARENT", "DERIVED"])

关于python - 模拟父类 __init__ 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32349855/

相关文章:

Python 多处理导入错误

python - pymunk + tkinter : How to get ball to move to left or right with pymunk?

python - 在 Mac OS 上使用 virtualenvwrapper 在 python 版本之间切换

python - python 中的线程-

c# - 从同一方法模拟两个不同的结果

c# - TryUpdateModel 仅在更新子对象的单元测试中失败

python - PyTorch:运行时错误:输入、输出和索引必须在当前设备上

python - Python中的包数据结构?

python - 每次我运行 "jupyter notebook"时,为什么我总是在 mac os 上得到这个?

python - 测试工具 ConcurrentStreamTestSuite 的一个简单的工作示例