Mocking a Django Queryset in order to test a function that takes a queryset

Rory picture Rory · Sep 9, 2011 · Viewed 17.9k times · Source

I have a utility function in my Django project, it takes a queryset, gets some data from it and returns a result. I'd like to write some tests for this function. Is there anyway to 'mock' a QuerySet? I'd like to create an object that doesn't touch the database, and i can provide it with a list of values to use (i.e. some fake rows) and then it'll act just like a queryset, and will allow someone to do field lookups on it/filter/get/all etc.

Does anything like this exist already?

Answer

Ned Batchelder picture Ned Batchelder · Sep 9, 2011

Of course you can mock a QuerySet, you can mock anything.

You can create an object yourself, and give it the interface you need, and have it return any data you like. At heart, mocking is nothing more than providing a "test double" that acts enough like the real thing for your tests' purposes.

The low-tech way to get started is to define an object:

class MockQuerySet(object):
    pass

then create one of these, and hand it to your test. The test will fail, likely on an AttributeError. That will tell you what you need to implement on your MockQuerySet. Repeat until your object is rich enough for your tests.