【发布时间】:2020-04-01 17:05:05
【问题描述】:
我的函数在数据库中查找Actor 对象并使用传递的参数调用其do_something() 方法。
from my_app.models import Actor
def my_function(id, stuff):
actor = Actor.objects.get(id=id)
return actor.do_something(stuff)
我希望我的单元测试检查两件事:
1.my_function找到我想要的Actor。
2、my_function按预期调用了actor的do_something方法。
from unittest import mock
from django.test import TestCase
from my_app.models import Actor
from my_app.views import my_function
class ViewsTestCase(TestCase):
@classmethod
def setUpTestData(cls):
self.actor = Actor.objects.create(id=42, name='John')
def test_my_function(self):
with mock.patch.object(Actor, 'do_something') as mock_do:
my_function(id=42, stuff='a-short-string')
mock_do.assert_called_once_with('a-short-string')
这可以确保 my_function 像我想要的那样调用 do_something,但我不知道如何确保它找到了我让他找到的 Actor。即使my_function 找到了错误的演员,这个测试也会通过。有什么办法可以检查吗?
【问题讨论】:
标签: python django mocking python-unittest django-unittest