'Django testing rest-framework: APIRequestFactory vs APIClient

Being new to testing i'm looking to test my API in Django (Django-rest-framework).

I'm setting up tests for my views, that is my API endpoints. Now looking over the documentation i can use an APIRequestFactory or a APIClient. Both seem to do the same thing.

What is the difference between those two, and why/when should i use one or the other??



Solution 1:[1]

If you look at the tools and helpers for testing "standard" views in Django you will find something very analogue, the TestClient and a RequestFactory.

The RequestFactory shares the same API as the test client. However, instead of behaving like a browser, the RequestFactory provides a way to generate a request instance that can be used as the first argument to any view. This means you can test a view function the same way as you would test any other function – as a black box, with exactly known inputs, testing for specific outputs.

The TestClient lets you interact with your site from the perspective of a user browsing your site (... though testing Javascript is yet another story). Many things come into play when testing your site like this (Sessions, Middlewares, URL-Routing, etc.). So these are typically more integrational tests that mimic real world interaction with your site or API.

A RequestFactory allows you to test you views in a very isolated manner. You can build a request and test your view without the need to setup your urls or care about things happening in middlewares etc. So this is closer to a typical unit test.

That said, both types of tests are useful. To get a general feeling if your API works as expected I would probably start using the APIClient and use RequestFactories when it comes to more complex views. But the right mix depends a lot on your concrete application.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1