gpt4 book ai didi

python - 如何在 Python3 中使用构造函数模拟对象?

转载 作者:行者123 更新时间:2023-11-28 20:57:52 25 4
gpt4 key购买 nike

我是 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 对象(和类似对象)的好方法?

最佳答案

您看到的 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()

关于python - 如何在 Python3 中使用构造函数模拟对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7060836/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com