Should I test Django Models? So far I've been writing tests for the views only. What else could and should be tested?
Asked
Active
Viewed 136 times
-2
-
Answers to your question will be opinionated. My opinion would be you should have "enough" tests to suit your needs – Sayse Aug 19 '15 at 06:47
-
Although I agree with @Sayse that writing test cases is opinionated. You can or you can not write test cases its totally upto your level of managing code and designing it. – Arpit Goyal Aug 19 '15 at 07:13
2 Answers
3
Django models
are testable. For instance you can write test cases for a property you write for the model.
class Candidate(models.Model):
first_name = StringField()
last_name = StringField()
@property
def name(self):
return self.first_name + ' ' + self.last_name
Now you can write the test case like this for this model. First create a model instance
class TestCandidateModel(SimpleTestCase):
def setUp(self):
self.candidate = Candidate.objects.create(first_name = 'ABC', second_name = 'XYZ')
def test_returns_candidate_name(self):
self.assertEqual(self.candidate.name, 'ABC XYZ')

Arpit Goyal
- 2,212
- 11
- 31
1
What should be tested? If you want a short answer, "EVERYTHING excluding external libraries". Your tests needs to be as granular as possible. If there is some method that is defined on models, then instead of indirectly testing it in views, you should test it in models, and just make sure that method is being called in views. So for a typical django application, you should test - models, managers, forms, views, serializers, handlers, even middlewares (as I said everything)

hspandher
- 15,934
- 2
- 32
- 45