我想模拟一个在类方法中调用的函数,同时在Django项目中测试类方法.考虑以下结构:
def func():
...
return resp # outcome is a HTTPResponse object
Run Code Online (Sandbox Code Playgroud)
from app.utils import func
class MyModel(models.Model):
# fields
def call_func(self):
...
func()
...
Run Code Online (Sandbox Code Playgroud)
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_mock(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
Run Code Online (Sandbox Code Playgroud)
当我运行测试时,fake_func避免使用mock函数,func而是调用real .我想mock.patch …