0

我想测试这个方法,但是我需要模拟变量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

4

1 回答 1

0

通常,您不会模拟变量,而是模拟用于设置该变量值的函数调用。例如,在您的示例中,您将模拟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
于 2013-11-23T03:16:23.867 回答