The best way to mock querysets

59 views
Skip to first unread message

Edgar Gabaldi

unread,
Apr 30, 2015, 3:26:15 PM4/30/15
to django...@googlegroups.com
Who practices TDD (XP like) says that the tests need to run quickly. For this, we have to mock all external resources of the method that i want to test.

In the case of queryset, i think so strange. Eg: https://gist.github.com/edgabaldi/ffdffa60f2add650f052

Am i doing it wrong? Do i have better way to do that?

Avraham Serour

unread,
May 1, 2015, 6:18:52 AM5/1/15
to django...@googlegroups.com
It seems correct, but the question is if you should do it.

In my opinion you shouldn't, you should set the test data and make a real query then compare results, you shouldn't care how the function got the data, but that it got it correctly.

let's say tomorrow you add a prefetch_related to your query, you're still getting the same data, but now your tests are failing because you are doing it differently

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAGjPPHkvcPGusgTzddJ3SVtfeGhgQCZb4L9tOq8vWgY9OoP8zQ%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.

Javier Guerra Giraldez

unread,
May 1, 2015, 9:41:00 AM5/1/15
to django...@googlegroups.com
On Fri, May 1, 2015 at 5:17 AM, Avraham Serour <tov...@gmail.com> wrote:
> In my opinion you shouldn't, you should set the test data and make a real
> query then compare results, you shouldn't care how the function got the
> data, but that it got it correctly.


that's part of a much bigger religious war, with "unit tests" at one
extreme and "integration tests" at the other.

even without aiming for unittest purity, the "test only the code
you're testing" idea would clearly advise for mocking the database.
of course, that means many more tests for the database layer itself,
which in turn make the OP's wish for quick tests all much more
important.

but when doing TDD, the favored tests aren't necessarily of the
unittest variety; they lean somewhat more towards functional tests,
almost integration tests. IOW: if it's a requirement for the code to
work decoupled from the database, then test it in isolation. if not,
then the minimal test (and minimal code to pass it) is to assume the
database layer is already well tested by the framework (and it is!),
and you're free to assume it in the tests.

cheers,

--
Javier
Reply all
Reply to author
Forward
0 new messages