首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用mox模拟变量

使用mox模拟变量
EN

Stack Overflow用户
提问于 2013-11-23 03:13:09
回答 1查看 1.3K关注 0票数 0

我想测试这个方法,但是我需要模拟变量dirContent

代码语言:javascript
复制
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的方式。

代码语言:javascript
复制
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()

也尝试过这种方法

代码语言:javascript
复制
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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-11-23 03:16:23

通常,您不会模拟变量,而是模拟用于设置变量值的函数调用。例如,在您的示例中,您可以模拟出os.listdir并让它返回一个模拟值。

代码语言:javascript
复制
# 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
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/20158063

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档