【发布时间】:2014-07-01 14:18:02
【问题描述】:
我尝试模拟这样的类的构造函数https://stackoverflow.com/a/17950141/633961
class MockedHttpResponse(django.http.response.HttpResponseBase):
def check(self, *args, **kwargs):
status=kwargs.get('status')
if status is None and self.status_code==200:
return # default
if not status==self.status_code:
raise self.AssertionErrorStatusCode('%s!=%s' % (self.status_code, status))
def __init__(self, *args, **kwargs):
self.check(*args, **kwargs)
django.http.response.HttpResponseBase.__init__(self, *args, **kwargs)
class AssertionErrorStatusCode(AssertionError):
pass
在测试中的使用:
def test_assert_http_response_status__with_self_mocking(self):
from django.http import HttpResponse
with mock.patch('django.http.response.HttpResponse', testutils.MockedHttpResponse):
HttpResponse(status=200)
但我得到了这个例外:
Traceback (most recent call last):
File "/home/foo_eins_di514/src/djangotools/djangotools/tests/unit/utils/test_testutils.py", line 129, in test_assert_http_response_status__with_self_mocking
HttpResponse(status=200)
File "/home/foo_eins_di514/lib/python2.7/site-packages/django/http/response.py", line 258, in __init__
super(HttpResponse, self).__init__(*args, **kwargs)
TypeError: super(type, obj): obj must be an instance or subtype of type
如何模拟一个类并修改其__init__() 方法?
【问题讨论】:
-
你使用的是哪个版本的 Django?
-
@SilasRay 我们使用 Django 1.5.8
标签: python django unit-testing mocking