0
我試圖嘲笑一個功能。當我嘗試模擬功能core.use_cases.add_owner_to_place
模擬不起作用。它不斷打印「哎唷」。模擬不斷調用實際功能
我試過測試mocked_add_owner_to_place.called
,它返回False。
有誰知道爲什麼即使我嘲笑它仍然使用真正的功能?
views.py:
from core.use_cases import add_owner_to_place
class CreatePlace(LoginRequiredMixin, FormView):
template_name = 'place/create_place.html'
form_class = PlaceForm
success_url = reverse_lazy('place_list')
def form_valid(self, form):
place = form.save()
add_owner_to_place(place, self.request.user)
return super(CreatePlace, self).form_valid(form)
tests.py:
from unittest.mock import patch, Mock
@patch('core.use_cases.add_owner_to_place')
@patch('core.forms.PlaceForm.is_valid')
@patch('core.forms.PlaceForm.save')
def test_save_should_be_called(self, mocked_save, mocked_is_valid, mocked_add_owner_to_place):
self.client.post(reverse('place_create'), data={})
self.assertTrue(mocked_save.called)
uses_cases.py:
def add_owner_to_place(place, user):
print('Ouch')
其原因在[documentation](https://docs.python.org/3/library/unittest.mock.html#unittest.mock.patch)中有相當詳細的解釋, – solarissmoke