模拟Python对象实例化

时间:2018-10-25 18:17:44

标签: python python-3.x namespaces mocking python-unittest

我想模拟对象的实例,以便返回的对象是MagicMock对象。我的文件结构如下:

home_folder
|
|-namespace
|  |-Class1.py
|  |-Class2.py
|
|-tests
   |-unit_tests
      |-test_Class2.py

Class1.py的内容是:

class Class1:
    ... class members ...

Class2.py的内容是:

from Class1 import Class1

class Class2(Class1):

    classMethod(self):
        objInst = Class1()

        ... some logic ...

        return objInst

test_class2.py的内容是:

from unittest import TestCase
from Class1 import Class1
from Class2 import Class2
from unittest.mock import patch, MagicMock

class TestClass2(TestCase):

    @patch("namespace.Class2.Class1")
    def test_classMethod(self, mock_class1):
        cl2Obj = Class2()

        cl1Obj = MagicMock(Class1())

        mock_class1.return_value = cl1Obj

        r = cl2Obj.classMethod()

        self.assertEqual(cl1Obj, r)

运行此测试可以给我:

<Class1.Class1 object at 0xnum> != <MagicMock name='Class1()' spec='Class1' id=num>

我尝试使用

@patch("namespace.Class1.Class1")

但是没有帮助。尝试

mock_class1.__init__.return_value = cl1Obj

抛出错误

Attribute Error: 'method' object has no attribute 'return_value'

如何模拟objInst = Class1(),以便objInst最终持有MagicMock对象?

1 个答案:

答案 0 :(得分:0)

您正在使它变得比所需的复杂。 Scanner sc1 = new Scanner(file).useDelimiter("a:1,"); (mapping code) Scanner sc2 = new Scanner(sc1.next()).useDelimiter("b:2,"); (mapping code) Scanner sc3 = new Scanner(sc2.next()).useDelimiter("c:3,"); (mapping code)....... Scanner sc3 = new Scanner(sc2.next()).useDelimiter("a:1,"); 已经是一个可调用的对象,并且将返回另一个模拟-无论在何处调用该模拟。这样就可以正常工作:

mock_class1