我想在 Django 项目中测试类方法时模拟在类方法中调用的函数。考虑以下结构:
应用程序/utils.py
def func():
...
return resp # outcome is a HTTPResponse object
应用程序/模型.py
from app.utils import func
class MyModel(models.Model):
# fields
def call_func(self):
...
func()
...
应用程序/测试/test_my_model.py
from django.test import TestCase
import mock
from app.models import MyModel
class MyModelTestCase(TestCase):
fixtures = ['my_model_fixtures.json']
def setUp(self):
my_model = MyModel.objects.get(id=1)
@mock.patch('app.utils.func')
def fake_func(self):
return mock.MagicMock(headers={'content-type': 'text/html'},
status_code=2000,
content="Fake 200 Response"))
def test_my_model(self):
my_model.call_func()
... # and asserting the parameters returned by func
当我运行测试模拟函数时fake_func()
被避免了,而真正的func()
被调用。我猜范围在mock.patch
装饰器可能是错的,但我找不到让它工作的方法。我应该怎么办?
您的代码存在三个问题:
1)正如 Daniel Roseman 提到的,您需要修补调用该函数的模块,不在定义的地方.
2)此外,您需要装饰实际执行调用模拟函数的代码的测试方法。
3)最后,您还需要将模拟版本作为参数传递给您的测试方法,可能是这样的:
fake_response = mock.MagicMock(headers={'content-type': 'text/html'},
status_code=2000,
content="Fake 200 Response"))
class MyModelTestCase(TestCase):
fixtures = ['my_model_fixtures.json']
def setUp(self):
my_model = MyModel.objects.get(id=1)
@mock.patch('app.models.func', return_value=fake_response)
def test_my_model(self, fake_response): # the mock goes in as a param or else you get number of arguments error!
my_model.call_func()
self.assertTrue(fake_response.called)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)