【问题标题】:How to mock objects with constructors in Python3?如何在 Python3 中使用构造函数模拟对象?
【发布时间】:2011-08-15 00:59:19
【问题描述】:

我是 Python 新手(我来自 Java),在 Python3.2 中使用模拟时遇到了问题。

代码如下:

import gzip    

class MyClass:

    _content = None

    _gzipfile = gzip.GzipFile

    def __init__(self, content):
        self._content = content

    def my_method(self):
        # Code ...
        gzipper = self._gzipfile(fileobj=data)
        return gzipper.read()


import unittest
from mockito import *

class MyClassTest(unittest.TestCase):

    def my_method_test(self):
        gzipfile = mock
        myclass = MyClass()
        myclass._gzipfile = mock
        myclass.my_method

我想对我的方法进行单元测试(我正在使用 mockito 库进行模拟)。但是当我执行测试时,我收到了这个:

TypeError: __init__() got an unexpected keyword argument 'fileobj'

在这种情况下,我不得不使用命名参数调用 GzipFile 对象。

有没有很好的方法来模拟这个 GzipFile 对象(和类似的对象)?

【问题讨论】:

  • '__init' 是错字还是实际错误?
  • 不是错字,双下划线变成斜体,不知道怎么转义……所以我作弊了
  • 啊,好吧,在这种情况下,我建议添加一个需要“fileobj”参数的初始化程序。
  • 下划线不会触发代码块中的斜体。 (如果不确定,您可以在编辑时查看预览。)我删除了格式设置技巧,因此 init 用于应有的位置。让问题更清晰。
  • 你使用mockito而不是mock有什么原因吗?

标签: python unit-testing testing python-3.x mocking


【解决方案1】:

您看到的TypeError 是因为您将myclass._gzipfile 分配给mockito.mock 类对象。所以当my_method用关键字参数fileobj=data调用_gzipfile时,它实际上是在调用mockito.mock类,从而调用了它的__init__方法,它不理解这个参数。

这样的事情应该可以工作。它仍然不是一个理想的单元测试,因为它依赖于 gzip.GzipFile,但它应该可以帮助您入门。

import gzip

class MyClass(object):
    def __init__(self, content, file):
        self._content = content
        self._gzipper = gzip.GzipFile(filename=file)
    def my_method(self):
        # Code ...
        return self._gzipper.read()

import unittest
from mockito import *

class TestMyClass(unittest.TestCase):
    def setUp(self):
        self.my_class = MyClass('some content', 'file')

    def test_my_method(self):
    self.my_class._gzipper = mock()
        when(self.my_class._gzipper).read().thenReturn('gzipper read return')
        data = self.my_class.my_method()
        self.assertEqual(data, 'gzipper read return')

if __name__ == '__main__':
    unittest.main()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-19
    • 2015-07-21
    • 1970-01-01
    • 1970-01-01
    • 2019-05-25
    相关资源
    最近更新 更多