我想测试这个方法,但我需要模拟变量dirContent
def imageFilePaths(paths):
imagesWithPath = []
for _path in paths:
try:
dirContent = os.listdir(_path)
except OSError:
raise OSError("Provided path '%s' doesn't exists." % _path)
for each in dirContent:
selFile = os.path.join(_path, each)
if os.path.isfile(selFile) and isExtensionSupported(selFile):
imagesWithPath.append(selFile)
return list(set(imagesWithPath))
如何使用mox模拟变量?这就是我试图模仿os.listdir
的方式
def setUp(self):
self._filePaths = ["/test/file/path"]
self.mox = mox.Mox()
def test_imageFilePaths(self):
filePaths = self._filePaths[0]
self.mox.StubOutWithMock(os,'listdir')
dirContent = os.listdir(filePaths).AndReturn(['file1.jpg','file2.PNG','file3.png'])
self.mox.ReplayAll()
utils.imageFilePaths(filePaths)
self.mox.VerifyAll()
也尝试过这种方式
def test_imageFilePaths(self):
filePaths = self._filePaths
os = self.mox.CreateMock('os')
os.listdir = self.mox.CreateMock(os)
dirContent = os.listdir(filePaths).AndReturn(['file1.jpg','file2.PNG','file3.png'])
self.mox.ReplayAll()
lst = utils.imageFilePaths(filePaths)
# self.assertEquals('/test/file/path/file1.jpg', lst[0])
self.mox.VerifyAll()
但对正在测试的方法的调用无法识别模拟的discontent
通常不会模拟变量,而是模拟用于设置变量值的函数调用。例如,在您的示例中,您将模拟os.listdir
,并让它返回一个模拟值。
# Your test file
import os
class YourTest(...):
def setUp(self):
self.mox = mox.Mox()
def tearDown(self):
self.mox.UnsetStubs()
# Your test
def testFoo(self):
self.mox.StubOutWithMock(os, 'listdir')
# the calls you expect to listdir, and what they should return
os.listdir("some path").AndReturn([...])
self.mox.ReplayAll()
# ... the rest of your test