模拟对象进入Django单元测试

时间:2013-04-24 18:00:49

标签: python django unit-testing mocking django-testing

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

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

这个问题围绕着模拟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个实例进行单元测试,将它们从数据库中取出,并在调用get时尝试将其中一个实例移回return_value

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以模拟数据库中的整个视图?

0 个答案:

没有答案
相关问题