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:

  1. 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.
  2. 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.
  3. 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.
  4. 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”.