How Important Is Writing Unit Tests For Django Applications?

I understand the importance of unit testing. However, if we are going to write integration tests (testing the views), this test will step through all of the modules that we would otherwise unit test.

So, I’m wondering, it it really necessary to write unit test for other Django components, like the models and forms, when we will still test the views? And while testing the views, when does it makes sense to use Client and the RequestFactory.

Regarding your first question, here’s what we do:

When a view does something non-trivial, that functionality is usually extracted away into some modularized form of code, while the view just handles taking the input out of the request and giving the template renderer the result of that extracted functionality. Now the unit tests for that functionality don’t have to bother with the whole Request-Response-Cycle and can just test it directly with various input cases.

We also perform tests on the view itself (I suppose those would be integration tests), however what is tested there is the authorisation restrictions on the view, a general “good path” test case and maybe a few different input cases, if the input takes a non-trivial form. This does leave an untested gap of possible behaviour, where the view function unpacks the input wrong or otherwise fails to call the modularized functionality correctly. However it’s rarely useful to cover this gap, unless this is a very important view that can lead to loss of data or other Bad Things.

Hope this helps.

1 Like