2017-06-16 102 views
0

我有一個類的方法,我實例化一個配置類,然後調用這個類的一個方法:嘲諷初始化步驟和添加方法調用嘲笑

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

的可能的複製[模擬父類\ _ \ _ init \ _ \ _方法](https://stackoverflow.com/questions/32349855/mock-parent-class-init-method) – grundic

+1

初始[可能不會返回非無值](https: //docs.python.org/3/reference/datamodel.html#object.__init__),否則會引發TypeError - 就像您觀察到的那樣。如果你想模擬'ConfigB.createvalue',你不應該'@ mock.patch('ConfigB.ConfigB.createvalue')'? –

+0

@IljaEverilä工作。我已經添加了我更新的測試方法。謝謝。 – EliSquared

回答

0

按照唐柯比,我已經把我的解決方案作爲一個問題的答案:

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)