I have a class method that I am trying to test that requires two patched methods, ConfigB.__init__
and listdir
:
from os import listdir
from config.ConfigB import ConfigB
class FileRunner(object):
def runProcess(self, cfgA)
cfgB = ConfigB(cfgA)
print(listdir())
I have the following test set up:
import unittest
import unittest.mock imort MagicMock
import mock
from FileRunner import FileRunner
class TestFileRunner(unittest.TestCase):
@mock.patch('ConfigB.ConfigB.__init__')
@mock.patch('os.listdir')
def test_methodscalled(self, osListDir, cfgB):
cfgA = MagicMock()
fileRunner = FileRunner()
cfgB.return_value = None
osListDir.return_value = None
fileRunner.runProcess(cfgA)
Now the patched mock and return value works for ConfigB.ConfigB
, but it does not work for os.listdir
. When the print(listdir())
method runs I get a list of file in the current directory, not a value of None
as I specified in the patched return value. Any idea what is going wrong?
You need to patch your relative path to your code. patch('os.listdir')
doesn't works because you need to patch this:
@mock.patch("path.to.your.pythonfile.listdir")
Try with that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With