Django when to use teardown method

前端 未结 3 2048
-上瘾入骨i
-上瘾入骨i 2021-02-18 13:09

According to the docs:

A TestCase, on the other hand, does not truncate tables and reload initial data at the beginning of a test. Instead, it encloses

3条回答
  •  遥遥无期
    2021-02-18 13:18

    If you are using an alternative database like MongoDB or Redis and you need to load in a set of initial data (a "collection"), you will need to override the tearDown method too.

    See http://www.belchak.com/2011/02/07/unit-testing-django-with-a-nosql-backend/

    In general, django.test.TestCase does a full database flush at the start of each new test. This means that we do not need to manually delete objects in our tearDown as Chris Pratt has mentioned above. The next test setUp will make sure the database is clean.

    However, if we are using doctests and unittest.TestCase, there will be no database flush before tests are run again. At the start of a test, the database will be in whatever state the previous test left. This means that any stray data left by a previous run would cause conflict. So if we are using doctests or unittest.TestCase for our django tests, a cleanup might be good practice.

    Finally, in more complicated scenarios, it might also make sense to deliberately persist the test database to hunt down specific unit test bugs.

提交回复
热议问题