Tôi đang cố gắng viết một số unittests trên một class có nguồn gốc từ cái khác, nhưng tôi có một số khó khăn để thử kiểu cha mẹ init. .Phương thức __init__ Mock parent class
Dưới đây là một ví dụ về cách các lớp học của tôi
Imported.py
class Imported():
def __init__(self, a="I am Imported"):
print("a:{}".format(a))
Parent.py
from Imported import Imported
class Parent(object):
parent_list = ["PARENT"]
def __init__(self, a="I am Parent"):
imported = Imported(a)
Derived.py
from Parent import Parent
class Derived(Parent):
Parent.parent_list.append("DERIVED")
Trong unittests tôi muốn xác minh rằng Parent.parent_list == ["PARENT", "DERIVED"] khi tôi khởi tạo một đối tượng từ lớp Derived, Derived().
Cả hai giải pháp này không làm việc
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 không thành công với
TypeError: __init__() should return None, not 'MagicMock'
test_init_002 không thành công với
ImportError: No module named Parent.Imported
Bất kỳ s uggestion?
Tại sao chính xác không 'Chánh .__ init__' cần phải được chế giễu? Tại sao không chỉ mô phỏng 'Đã nhập '? –
Thử nghiệm thứ hai của bạn cần giả lập 'Parent.Imported'. –
Cuối cùng nhưng không kém phần quan trọng, bạn đã sửa đổi 'Parent.parent_list' * tại chỗ *, vì vậy cả hai' Parent.parent_list' và 'Derived.parent_list' đều tham chiếu đến cùng một đối tượng. Vì vậy, 'Parent.parent_list' bây giờ chứa' "DERIVED" '. Bạn có thể muốn tạo một bản sao cho 'Derived' thay vào đó:' parent_list = Parent.parent_list + ["DERIVED"] '. Các xét nghiệm của bạn có thể muốn kiểm tra điều này. –