我有一个视图,其中有一个名为 can_upload_file 的方法可以进行外部调用。这个方法是从视图的 post (create) 方法中调用的。所以,在我的单元测试中,我试图测试 post 方法,同时模拟 can_upload_file 方法,如下所示:
DatasetViewSet._can_upload_file = MagicMock()
DatasetViewSet._can_upload_file = "valid"
response = self.client.post(self.url, self.dataset, format="multipart")
但是我看到视图中实际的 can_upload_file 方法仍在执行。
我该如何解决这个问题?
您可以像这样指定模拟方法的返回值:
DatasetViewSet._can_upload_file = MagicMock(return_value="valid")