Writing test cases for django models

This was an article I found helpful: A Guide to Testing in Django (archived link). Here is a good summary of what to test:

Another common setback for developers/designers new to testing is the
question of ‘what should (or shouldn’t) I test?’ While there are no
hard & fast rules here that neatly apply everywhere, there are some
general guidelines I can offer on making the decision:

  • If the code in question is a built-in Python function/library, don’t test it. Examples like the datetime library.

  • If the code in question is built into Django, don’t test it. Examples like the fields on a Model or testing how the built-in
    template.Node renders included tags.

  • If your model has custom methods, you should test that, usually with unit tests.

  • Same goes for custom views, forms, template tags, context processors, middleware, management commands, etc. If you implemented
    the business logic, you should test your aspects of the code.

So, for your example, there wouldn’t really be anything to test until you write some custom functions.
In my opinion, testing ForeignKey and ManyToManyField links would fall under the second category (code built into Django), so I wouldn’t test these, as you are really testing whether or not Django is functioning properly. If you have a method which creates an instance of your product, including foreign relationships and M2Ms, you could verify the data has been created, that would be testing your custom method, not Django functionality.

Using the TDD paradigm, the tests are built to verify business logic, and design requirements.

Leave a Comment