2012-06-14 106 views
5

我已經寫了一些單元測試來測試我的Django應用程序。特別是一個測試套件在其setUp()函數中有很多代碼。所述代碼的目的是爲數據庫創建測試數據。 (是的,我知道夾具,並選擇不使用它們在這種情況下)。當我運行單元測試套件時,運行的第一個測試通過,但套件中的其餘測試失敗。所有失敗的消息都是相同的:它提到錯誤的位置是「self.database_object.save()」,原因是「IntegrityError:列名稱不唯一」。所以,我最好的猜測是Django在每次測試後都沒有正確地拆除數據庫。Django單元測試數據庫沒有被拆除?

今天早些時候它正在工作,但我想一些重構我搞砸了。關於爲什麼Django在每次測試後都沒有正確拆除數據庫的想法?

回答

8

您是否對您的基類使用TestCase或TransactionTestCase?有時候,這種行爲與Django爲TestCase優化TransactionTestCase所做的優化有關。這裏的區別是:

https://docs.djangoproject.com/en/dev/topics/testing/?from=olddocs#django.test.TransactionTestCase

class TransactionTestCase

Django TestCase classes make use of database transaction facilities, if available, to speed up the process of resetting the database to a known state at the beginning of each test. A consequence of this, however, is that the effects of transaction commit and rollback cannot be tested by a Django TestCase class. If your test requires testing of such transactional behavior, you should use a Django TransactionTestCase.

TransactionTestCase and TestCase are identical except for the manner in which the database is reset to a known state and the ability for test code to test the effects of commit and rollback. A TransactionTestCase resets the database before the test runs by truncating all tables and reloading initial data. A TransactionTestCase may call commit and rollback and observe the effects of these calls on the database.

A TestCase, on the other hand, does not truncate tables and reload initial data at the beginning of a test. Instead, it encloses the test code in a database transaction that is rolled back at the end of the test. It also prevents the code under test from issuing any commit or rollback operations on the database, to ensure that the rollback at the end of the test restores the database to its initial state. In order to guarantee that all TestCase code starts with a clean database, the Django test runner runs all TestCase tests first, before any other tests (e.g. doctests) that may alter the database without restoring it to its original state.

+0

這是現貨上。非常感謝你Tisho! –