python - 运行 python mox 测试时从未调用的预期方法

标签 python mox

我正在尝试编写一个 mox 测试来读取电子表格(4 列)、获取提要并将特定列(2 列)写入 CSV 文件。我试图通过获取列表提要的第一步,我的代码如下:

class SpreadsheetReader(mox.MoxTestBase):

  def setUp(self):
    mox.MoxTestBase.setUp(self)
    self.mock_gclient = self.mox.CreateMock(
                                            gdata.spreadsheet.service.SpreadsheetsService)
    self.mock_spreadsheet_key = 'fake_spreadsheet_key'
    self.mock_worksheet_id = 'default'
    self.test_data = [{'str_col':'col1', 'str_col':'col2', 'str_col':'col13'}]


  def testGetFeed(self):

    self.mock_gclient.GetListFeed(self.mock_spreadsheet_key,
                                  self.mock_worksheet_id).AndReturn(self.test_data)

    self.mox.ReplayAll()
    self.mox.Verify()


  def tearDown(self):
    mox.MoxTestBase.tearDown(self)

当我运行它时,出现以下错误:

ExpectedMethodCallsError: Verify: Expected methods never called:
  0.  SpreadsheetsService.GetListFeed('fake_spreadsheet_key', 'default') -> [{'str_col': 'col13'}]

知道如何解决这个错误吗?

最佳答案

您需要实际触发调用 GetListFeed 的函数。在调用 self.mox.ReplayAll() 之前,您只是在“记录”mox 进入重放模式后应该看到的内容。将 mox 置于重播模式后,您需要实际调用任何将调用 GetListFeed 的函数。在您的情况下,这似乎是 testGetFeed 或其父函数是什么。

此外,因为您在类定义中子类化了 mox.MoxTestBase(),所以您不需要在最后调用 self.mox.Verify() —根据 docs ,

you can make your test case be a subclass of mox.MoxTestBase; this will automatically create a mock object factory in self.mox, and will automatically verify all mock objects and unset stubs at the end of each test.

关于python - 运行 python mox 测试时从未调用的预期方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11953448/

相关文章:

testing - 如何用 Mox 模拟 HTTPoison?

Python SQLAlchemy - 模拟模型属性的 "desc"方法

python - PyCharm 自动导入和自动完成

Python ImportError 没有名为 crypto.PublicKey.RSA 的模块

python - 将黑白图像转换为数字数组?

python - 将数据框中字符串列的唯一值转换为值为 0 或 1 的新多 header

python - 使用 Mox 和 Python 测试模拟对象的调用顺序

elixir - 使用 Mox 测试函数链中的多个 API 调用

python - 如何使用 Python Mox 检查是否使用字符串的等效项调用方法?

python - 在 venv 上安装 pip 之后出现 ModuleNotFoundError