Test Django views that require login using RequestFactory

When using RequestFactory, you are testing view with exactly known inputs.

That allows isolating tests from the impact of the additional processing performed by various installed middleware components and thus more precisely testing.

You can setup request with any additional data that view function expect, ie:

    request.user = AnonymousUser()
    request.session = {}

My personal recommendation is to use TestClient to do integration testing (ie: entire user checkout process in shop which includes many steps) and RequestFactory to test independent view functions behavior and their output (ie. adding product to cart).

Leave a Comment