我有一个模型:
class Evaluation(models.Model):
def abc(self):
#some logic here
return something
说,我有另一个使用此功能:
def filter_graded(evaluations):
return filter(lambda x: x.is_completely_graded(), evaluations)
现在,当我为filter_graded
方法编写测试时,我模拟is_completely_graded
在某些情况下返回true/false。测试不尊重模拟,而是调用实际is_completely_graded
。我该如何解决?
我的测试看起来像:
def test_filter_graded(self):
eval1 = G(Evaluation)
eval2 = G(Evaluation)
eval1.is_completely_graded = mock.MagicMock(return_value=True)
eval2.is_completely_graded = mock.MagicMock(return_value=False)
filter_graded(Evaluation.objects.all())
self.assertEqual(len(result), 1)
您没有传递模拟对象。您正在传递真实数据:
filter_graded(Evaluation.objects.all())
您没有嘲笑Evaluation
或Evaluation.objects
或Evaluation.objects.all()
。
如果您的所有代码都使用is_completely_graded
方法寻找对象,则只需将模拟作为序列传递,而无需任何ORM查询:
def test_filter_graded(self):
eval1 = mock.MagicMock()
eval2 = mock.MagicMock
eval1.is_completely_graded.return_value = True
eval2.is_completely_graded.return_value = False
filter_graded([eval1, eval2])
self.assertEqual(len(result), 1)