
Django Testing
TestCase, test fixtures, factories, test client, coverage, TDD, mocking, CI/CD integration
1Which base class should be used to write unit tests in Django?
Which base class should be used to write unit tests in Django?
回答
django.test.TestCase is the recommended base class for Django unit tests. It inherits from unittest.TestCase and adds Django-specific features like automatic wrapping of tests in a database transaction that gets rolled back after each test, ensuring test isolation.
2What is the main difference between TestCase and TransactionTestCase in Django?
What is the main difference between TestCase and TransactionTestCase in Django?
回答
TestCase wraps tests in an atomic transaction that is rolled back at the end, which is faster but prevents testing real transactional behaviors. TransactionTestCase recreates the database between each test, allowing testing of explicit commits and rollbacks, but is slower.
3How to use the Django test client to simulate a GET request to a view?
How to use the Django test client to simulate a GET request to a view?
回答
The Django test client, accessible via self.client in a TestCase, allows simulating HTTP requests. The method self.client.get('/url/') simulates a GET request and returns a Response object containing the status_code, content and template context used for rendering.
How to load predefined test data in Django using JSON fixtures?
What is the main advantage of using Factory Boy over JSON fixtures?
+19 面接問題