我试图用下面的虚拟方法模拟一个链接的Django模型对象,
# utils.py
def foo_something_exist():
if Foo.objects.get(a='something').exist():
return 'exist'
# test.py
import unittest.mock import patch
import utils
.
.
.
@patch('utils.Foo')
def test_foo_something_exist_returns_none(self, mock_foo):
mock_foo.objects.get.exists.return_value = False
self.assertIsNone(utils.foo_something_exist())
.
.
.
test_foo_something_exist()
次测试失败.我在utils中发现了Foo.objects.get(a='something').exist()
.py是MagicMock对象(<MagicMock name='Member.objects.get().exists()' id='xxxxxx'>
)而不是False
,这导致了该测试功能的失败.是的,我也试过mock_foo.objects.return_value.get.return_value.exists.return_value = False
,这是在一篇帖子中提到的.正确模拟模型对象(及其链接方法)的指针/提示非常有用.
提前谢谢你.