小编use*_*566的帖子

模拟父类__init__方法

我试图在一个派生自另一个类的类上编写一些单元测试,但是我有一些困难来模拟父类init方法,但是你不能这样做,所以我正在寻找建议.

这是我的课程如何的一个例子

Imported.py

class Imported():
    def __init__(self, a="I am Imported"):
        print("a:{}".format(a))
Run Code Online (Sandbox Code Playgroud)

Parent.py

from Imported import Imported

class Parent(object):

    parent_list = ["PARENT"]

    def __init__(self, a="I am Parent"):
        imported = Imported(a)
Run Code Online (Sandbox Code Playgroud)

Derived.py

from Parent import Parent

class Derived(Parent):

    Parent.parent_list.append("DERIVED")
Run Code Online (Sandbox Code Playgroud)

在我的单元测试中,当我从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") …
Run Code Online (Sandbox Code Playgroud)

python unit-testing mocking python-2.7

13
推荐指数
1
解决办法
1万
查看次数

标签 统计

mocking ×1

python ×1

python-2.7 ×1

unit-testing ×1