3

编辑:这最初不起作用,因为导入使用不同的导入到视图和模拟中。我project.app.views.Model在测试模拟中使用过,而在导入中views.py实际上是app.views.Model.

因此这个问题实际上得到了解决,但这个问题可能对其他人有用,因为它强调了在模拟中导入一致性的必要性。(Michael Foord(模拟创作者)在他的演讲中提到的东西)。

这个问题围绕着模拟 Django 模型管理器返回 factory_boy 对象的方法,从而避开数据库。我有一个“目的地”模型:

class Destination(models.Model):
    name = models.CharField(max_length=50)
    country = models.CharField(max_length=50)

和一个基于 DestinationView 类的视图。在其中,我尝试使用 url 提供的名称来检索数据库对象:

from app.models import Destination

class DestinationView(View):

    def get(self, request, **kwargs):

        [snip - gets the name from the URL request]

        try:
            destination = Destination.objects.get(name=name)
        except:
            return HttpResponse('No such destination', status=400)

我现在想模拟上面的单元测试。我为我的单元测试使用factory_boy实例将它们从数据库中取出,并试图在调用时将其中一个作为return_valueget交还:

def test_mocked_destination(self):
    with patch('app.views.Destination') as mock_destination:
        rf = RequestFactory()
        mock_destination.objects.get.return_value = DestinationFactory.build()
        request = rf.get('/destination/', {'destination': 'London'})
        response = DestinationView.as_view()(request)

然而,这并没有按计划工作,因为假模拟似乎永远不会被调用。如何正确覆盖Destination对象的get()return_value 以便从数据库中模拟出整个视图?

4

0 回答 0