2017-10-15 97 views
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') 

回答

0

所以,圍繞着搜索在github上查找一些代碼,我發現我需要從view中嘲笑,即使該功能屬於use_cases模塊。

所以我的代碼現在是:

tests.py

from unittest.mock import patch, Mock 

@patch('core.views.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) 

我知道這工作,但現在我需要搜索,爲什麼它的工作原理。我會在解釋它時解釋它。

+1

其原因在[documentation](https://docs.python.org/3/library/unittest.mock.html#unittest.mock.patch)中有相當詳細的解釋, – solarissmoke