MagicMock
到
PropertyMock
这就是访问它的方式(Django model列)。但是测试失败了
_mock_self = <PropertyMock name='get().my_prop' id='4524632776'>
# view
def get(self request):
# stuff...
obj = MyModel.objects.get(id=2)
# more stuff...
print(obj.my_prop)
some_val = MyOtherModel(my_prop=obj.my_prop)
# tests
def test_my_test(mocker):
other_obj = mocker.patch("app.views.MyOtherModel")
obj_get = mocker.patch("app.views.MyModel.objects.get")
obj_prop = mocker.PropertyMock(return_value=1)
# This should translate to an instance of MyModel i.e. MyModel().my_prop
obj_get.return_value.my_prop = obj_prop
# run view
obj_prop.assert_called_once() # Says never invoked
# Failed as my_prop was a PropertyMock instead of actual value
other_obj.assert_called_once_with(my_prop=obj_prop)
print语句显示
<PropertyMock name='get().my_prop' id='4524632776'>
我也尝试过直接修补模型上的属性,但这似乎不起作用
Mocks
都不一样。
def test_my_test(mocker):
other_obj = mocker.patch("app.views.MyOtherModel")
obj_prop = mocker.patch("app.views.MyModel.my_prop", new_callable=mocker.PropertyMock)
obj_get = mocker.patch("app.views.MyModel.objects.get")
obj_get.return_value.my_prop = obj_prop
# run view
obj_prop.assert_called_once()
# Failed as my_prop was a PropertyMock instead of actual value
other_obj.assert_called_once_with(my_prop=obj_prop)
失败的原因是。。。
_mock_self = <PropertyMock name='my_prop' id='4543022192'>
<MagicMock name='get().my_prop' id='4543752232'>
编辑
添加了其他更准确地描述实现的补丁