django unit tests without a db

前端 未结 11 1499
醉梦人生
醉梦人生 2020-11-29 16:11

Is there a possibility to write django unittests without setting up a db? I want to test business logic which doesn\'t require the db to set up. And while it is fast to setu

11条回答
  •  隐瞒了意图╮
    2020-11-29 17:01

    Generally tests in an application can be classified in to two categories

    1. Unit tests, these test the individual snippets of code in insolation and do not require to go to the database
    2. Integration test cases which actually go to the database and test the fully integrated logic.

    Django supports both unit and integration tests.

    Unit tests, do not require to setup and tear down database and these we should inherit from SimpleTestCase.

    from django.test import SimpleTestCase
    
    
    class ExampleUnitTest(SimpleTestCase):
        def test_something_works(self):
            self.assertTrue(True)
    

    For integration test cases inherit from TestCase in turn inherits from TransactionTestCase and it will setup and tear down the database before running each test.

    from django.test import TestCase
    
    
    class ExampleIntegrationTest(TestCase):
        def test_something_works(self):
            #do something with database
            self.assertTrue(True)
    

    This strategy will ensure that database in created and destroyed only for the test cases that access the database and therefore tests will be more efficient

提交回复
热议问题