Testing views with mock

In this recipe, we will take a look at how to write unit tests. Unit tests are those that check whether the functions or methods return correct results. We again take the likes app and write tests checking whether posting to the json_set_like() view returns {"success"; false} in the response for unauthenticated users and returns {"action": "added", "count": 1, "obj": "Haus der Kulturen der Welt", "success": true} for authenticated users. We will use the Mock objects to simulate the HttpRequest and AnonymousUser objects.

Getting ready

Let's start with the locations and likes apps from the Implementing the Like widget recipe in Chapter 4, Templates and JavaScript.

Install the mock module in your virtual environment, as follows: ...

Get Django: Web Development with Python now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.