英文:
Django Unit Test- How to avoid rollback for each unit test case
问题
我是新手Django框架。我正在编写Django单元测试案例。每个测试案例的数据库事务都会被回滚。是否有可能避免回滚,因为我希望在其他测试案例中使用该数据库数据?
英文:
I am new to Django framework. I am writing Django unit test cases. The DB transactions are getting roll-backed for each test case. Is it possible to avoid the rollback since I want to use that DB data for other test cases?
答案1
得分: 2
你可以在测试类中使用 setUp(self)
和 tearDown(self)
方法,它们分别在类范围的初始化之前和之后运行。
也就是说,如果你在测试类的 setUp(self)
方法中创建一个对象,那个对象将对该类中的所有测试可用。
如果你希望在测试类之间共享资源,那么你应该重新评估你试图解决的问题。
这值得一读:
在 Django 中进行测试
英文:
You can use setUp(self)
and tearDown(self)
methods within a test class, which are run before and after (respectively) for class-wide initialization.
I.e. if you create an object in a test class's setUp(self)
method, that object will be available to all tests within that class.
If you want to share a resource between test classes, then you should probably re-evaluate the problem you are trying to solve.
This is worth a read:
Testing in Django
答案2
得分: 0
方法 setUpClass
和 setUpTestData
是为此而设计的,它们不会在方法之间回滚。
如果您希望在测试用例类之间保留您设置的状态更长时间,那么 fixtures 可能会有所帮助。 https://docs.djangoproject.com/en/4.2/topics/db/fixtures/
(当说“测试用例”时,您可能指的是测试方法或一个测试用例类 - 人们有时会含糊不清地使用这个术语,所以要小心)
英文:
Methods setUpClass
, and setUpTestData
, are designed for that, they would not rollback between methods.
If you want keep the state you set up around even longer, between TestCase classes, then fixtures may help. https://docs.djangoproject.com/en/4.2/topics/db/fixtures/
(By saying "test case", you may have meant a test method or a TestCase class - people sometimes use the term vaguely, so take care)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论