-1

I am currently exploring adding unit tests to my Django REST Framework project. I totally understand adding unit tests for other components of the app like models. However, I'm stuck at testing views. I understand using Client is for adding integration testing while using APIRequestFactory is for adding unit tests.

I'm curious whether I should add unit tests or integration tests to my views, and in which situations would either of them be useful.

1
  • I haven't developed django apps before, so I am not familiar with the architecture. Can you give more information about what Client and APIRequestFactory is? Do views generate HTML, or data in JSON? Mar 12 at 21:03

1 Answer 1

0

Unit tests focus on a single part of a whole application in total isolation, usually, a single class or function.

Integration testing is to test how parts of the application work together as a whole.

While a unit test may be used to ensure that the homepage produces an HTTP status code of 200, an integration test may be used to simulate a user’s whole registration process.

I generally use unit tests to check status codes:

def test_whatever_list_view(self):
    w = self.create_whatever()
    url = reverse("whatever.views.whatever")
    resp = self.client.get(url)

    self.assertEqual(resp.status_code, 200)
    self.assertIn(w.title, resp.content)

I fetch the URL from the client, store the results in the variable resp and then test the assertions. First, test whether the response code is 200, and then test the actual response.

I can also use Selenium to make sure something fails which would be an example of integration testing.

Install selenium:

pip install selenium

If a user needs to be logged in to create a new object, the test would succeed if it actually fails to create the object.

from selenium import webdriver

class TestSignup(TestCase):

    def setUp(self):
        self.driver = webdriver.Firefox()

    def test_signup_fire(self):
        self.driver.get("http://localhost:8000/add/")
        self.driver.find_element_by_id('id_title').send_keys("test title")
        self.driver.find_element_by_id('id_body').send_keys("test body")
        self.driver.find_element_by_id('submit').click()
        self.assertIn("http://localhost:8000/", self.driver.current_url)

    def tearDown(self):
        self.driver.quit

if __name__ == '__main__':
    unittest.main()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.