[英]Mock parent class __init__ method
I am trying to write some unittests on a class which is derived from another, but I have some difficulties to mock the parent class init method, which afaik you cannot, so I am looking for suggestion. 我试图在一个派生自另一个类的类上编写一些单元测试,但是我有一些困难来模拟父类init方法,但是你不能这样做,所以我正在寻找建议。
Here an example of how are my classes 这是我的课程如何的一个例子
Imported.py Imported.py
class Imported():
def __init__(self, a="I am Imported"):
print("a:{}".format(a))
Parent.py Parent.py
from Imported import Imported
class Parent(object):
parent_list = ["PARENT"]
def __init__(self, a="I am Parent"):
imported = Imported(a)
Derived.py Derived.py
from Parent import Parent
class Derived(Parent):
Parent.parent_list.append("DERIVED")
In my unittests I want to verify that Parent.parent_list == ["PARENT", "DERIVED"] when I instantiate an object from the Derived class, Derived(). 在我的单元测试中,当我从Derived类Derived()实例化一个对象时,我想验证Parent.parent_list == [“PARENT”,“DERIVED”]。
Both of this solution doesn't work 这两种解决方案都不起作用
test_Derived.py 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 fails with test_init_001失败了
TypeError: __init__() should return None, not 'MagicMock'
test_init_002 fails with test_init_002失败了
ImportError: No module named Parent.Imported
Any suggestion? 有什么建议吗?
For the first solution, change the return value of the __init__
method to None
. 对于第一个解决方案,将
__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"])
For the second solution, patch Parent.Imported
: 对于第二个解决方案,补丁
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"])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.