Django 似乎没有模拟模型方法

Django doesn't seem to mock model methods

我正在尝试为以下方法编写一些测试用例作为名为 Project 的模型的一部分:

    def get_mouse_model_designs(self):
        return {details.design.to_mouse_model()
                for details in self.strategies.all()}

问题似乎出在 details.design.to_mouse_model() 上,我似乎无法准确模拟此功能。这是我的测试(self.details2 是此测试用例中唯一链接到项目的模型,因此它将是 self.strategies.all() 返回的唯一记录):

    def test_mouse_model_designs_one_design(self):
        mm_design = MagicMock()
        self.details2.design.to_mouse_model = MagicMock(return_value=mm_design)
        self.assertEqual(self.project2.get_mouse_model_designs(), {mm_design})

这是我收到的错误消息:

AssertionError: Items in the first set but not the second:
<MouseModel.LabWork.DesignTask.DesignTask object at 0x0A4B0910>
Items in the second set but not the first:
<MagicMock id='172651760'>

MouseModel.LabWork.DesignTask.DesignTask 对象是 to_mouse_model() 方法返回的对象。但我嘲笑了这一点。所以从错误消息中我可以看出它实际上并没有模拟 to_mouse_model() 方法。我试图断言该方法已被调用,但也失败了。

但是,如果我删除函数定义中的 to_mouse_model() 并相应地更新测试,它就会通过。

如有任何帮助,我们将不胜感激!

我找到了解决办法。通过模拟 class 方法而不是对象方法:

@patch("LabWork.models.Design.to_mouse_model")
def test_mouse_model_designs_one_design(self, mock_design_mm):
    mm_design = MagicMock()
    mock_design_mm.return_value = mm_design
    self.assertEqual(self.project2.get_mouse_model_designs(), {mm_design})