在unittest中嘲笑post方法不起作用

时间:2019-04-09 13:50:46

标签: django python-3.x unit-testing testing mocking

我为我的网站编写了一些向用户发送验证短信的代码,该代码可以正常工作,但是现在我想对其进行测试,并且需要模拟发送代码,但是测试无法正常工作。

这是我所有的代码: 我有一个视图,向用户发送验证码,如下所示:

view.py
class SendCode(GenericAPIView):
    def post(self, request, *args, **kwargs):
        """some of code that send messages"

我写的测试无效:

@mock.patch('view.SendCode.post', autospec=True)
class MyTest(unittest.TestCase):
    def setUp(self):
        self.client = Client()

    def test_get_data(self, mock_call_external_api):
        data = {'phone': '11111111'}
        self.client.post('/send-code/',json.dumps(data),                                       content_type='application/json')
        self.assertTrue(mock_call_external_api.called)

在这里,我遇到以下错误:

AssertionError: Expected a `Response`, `HttpResponse` or   `HttpStreamingResponse` to be returned from the view, but received a `<class 'unittest.mock.MagicMock'>

我尝试了很多解决方案,例如更改补丁路径,但实际上并没有用。 预先感谢您的帮助

0 个答案:

没有答案