首页 > 解决方案 > 在 TestCase 中改变函数的行为

问题描述

我有在 post_save 信号中调用的 sendmail 函数。我希望这个函数只是为所有测试用例返回 None 。如何做到这一点?在 setUp 中使用来自 mock.patch 的补丁?如何?

标签: djangotestingdjango-rest-framework

解决方案


是的,您可能想模拟您在post_save信号中使用的任何功能。

一个更好的主意是模拟信号内部的功能。

def do_something():
    ...

@receiver(...)
def signal_handler_post_save(sender, *args, **kwargs):
   do_something()

然后在你的测试中:

from unittest.mock import patch

...
    @patch('path_to_your_signal_module.do_something')
    def test_my_test_case(self, do_something):
        self.assertEqual(do_something.call_count, 1)
...

推荐阅读