Skip to content
Advertisement

Using unittest.mock to mock a DRF response

My example is pretty basic:

JavaScript
JavaScript
JavaScript
JavaScript

What I’m trying to do is mock the request to the /core/ URI so it returns a mocked response and not the response from the database. For example, considering unit testing in a CI pipeline when the database isn’t available.

The below is what I have, but print(response.data) returns the actual response and not the mocked one:

JavaScript

Not finding the documentation very intuitive in figuring this out, so asking how I should be implementing this. Suggestions?

Advertisement

Answer

JavaScript

The above patch just mocks the file, which won’t have any effect. What you can use is:

JavaScript

This will mock the list method of the viewset, which you can then give a response object as the return_value.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement