本文介绍了模拟父类__init__方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在派生自另一个类的类上编写一些单元测试,但是我在模拟父类 init 方法时遇到了一些困难,因此您无法做到这一点,因此我正在寻找建议

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.

这是我的班级如何的一个例子

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")

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

In my unittests I want to verify that Parent.parent_list == ["PARENT", "DERIVED"] when I instantiate an object from the Derived class, 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失败

test_init_001 fails with

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

test_init_002失败

test_init_002 fails with

ImportError: No module named Parent.Imported

有什么建议吗?

推荐答案

对于第一个解决方案,将__init__方法的返回值更改为None.

For the first solution, change the return value of the __init__ method to 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:

For the second solution, patch 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"])

这篇关于模拟父类__init__方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-09 10:59