我有一个类方法,我实例化一个配置类,然后在该类上调用一个方法:
from config.ConfigB import ConfigB
class FileRunner(object):
def runProcess(self, cfgA)
cfgB = ConfigB(cfgA)
print(cfgB.createvalue())
我设置了以下测试类来尝试测试该方法,但它不起作用:
import unittest
import unittest.mock imort MagicMock
import mock
from FileRunner import FileRunner
class TestFileRunner(unittest.TestCase):
@mock.patch('ConfigB.ConfigB.__init__')
def test_methodscalled(self, cfgB):
cfgA = MagicMock()
fileRunner = FileRunner()
cfgB.return_value = None
cfgB.return_value.createValue.return_value = 17
fileRunner.runProcess(cfgA)
但是当我测试课程时,我得到错误:
AttributeError: 'NoneType' object has no attribute 'createValue'
我也尝试过像这样编写测试类:
import unittest
import unittest.mock imort MagicMock
import mock
from FileRunner import FileRunner
class TestFileRunner(unittest.TestCase):
@mock.patch('ConfigB.ConfigB.__init__')
def test_methodscalled(self, cfgB):
cfgA = MagicMock()
fileRunner = FileRunner()
cfgBMock = mock.Mock()
cfgBMock.createValue.return_value = 17
cfgB.return_value = cfgBMock
fileRunner.runProcess(cfgA)
但是当我尝试这个时,我得到错误:
TypeError: __init__() should return None, not 'Mock'
我做错了什么?有没有更好的方法来测试我的课程?
*编辑:以下是基于以下评论的解决方案:
import unittest
import unittest.mock imort MagicMock
import mock
from FileRunner import FileRunner
class TestFileRunner(unittest.TestCase):
@mock.patch('ConfigB.ConfigB.__init__')
@mock.patch('ConfigB.ConfigB.createValue')
def test_methodscalled(self, createValue, cfgB):
cfgA = MagicMock()
fileRunner = FileRunner()
createValue.return_value = 17
cfgB.return_value = None
fileRunner.runProcess(cfgA)
答案 0 :(得分:0)
根据Don Kirby的说法,我已将解决方案作为问题的答案:
import unittest
import unittest.mock imort MagicMock
import mock
from FileRunner import FileRunner
class TestFileRunner(unittest.TestCase):
@mock.patch('ConfigB.ConfigB.__init__')
@mock.patch('ConfigB.ConfigB.createValue')
def test_methodscalled(self, createValue, cfgB):
cfgA = MagicMock()
fileRunner = FileRunner()
createValue.return_value = 17
cfgB.return_value = None
fileRunner.runProcess(cfgA)