Recent End to End Testing Preferences with Django
When testing in Django there’s two basic ways to make an End-to-End test for your view: use the test client to send a request to the server or create a fake request object and manually call your view function.
One isn’t “better” than the other, but I’ve come to prefer using the mock client over the fake request for the following reasons:
- Client tests hit the entire stack of code before executing your view allowing you to catch any conflicts with a middleware or settings and your view.
- Url Path tests come for free. When testing with fake request objects you can put any path you’d like in there and it will execute missing that bad merge where your url config change removing an endpoint.
- It’s (slightly) easier to reason about. If I’m writing a test to confirm X happens when Y is posted I make Y and post it rather than making an object that pretends Y was posted.
- It removes the friction to refactor your views. As long as the url stays the same, you can rename and move your view however you’d like without changing any of the tests. This makes it easier to create a more consistent codebase e.g. some views use the verb “save” while others use “register”.