我不明白 FactoryBoy + Django 中的teardown
是如何工作的。
我有一个这样的测试用例:
class TestOptOutCountTestCase(TestCase):
multi_db = True
def setUp(self):
TestCase.setUp(self)
self.date = datetime.datetime.strptime('05Nov2014', '%d%b%Y')
OptoutFactory.create(p_id=1, cdate=self.date, email='inv1@test.de', optin=1)
def test_optouts2(self):
report = ReportOptOutsView()
result = report.get_optouts()
self.assertEqual(len(result), 1)
self.assertEqual(result[0][5], -1)
setUp
为所有测试运行一次是否正确?现在,如果我进行第二次测试并且在运行之前需要一个干净的状态,我该如何实现这一点?谢谢
最佳答案
如果我理解正确的话,在这种情况下您不需要 tearDown
,因为在每次测试之间重置数据库是 default behaviour对于测试用例
。
参见:
At the start of each test case, before setUp() is run, Django will flush the database, returning the database to the state it was in directly after migrate was called.
...
This flush/load procedure is repeated for each test in the test case, so you can be certain that the outcome of a test will not be affected by another test, or by the order of test execution.
或者您的意思是将通过 OutputFactory
创建实例限制为某些测试?
那么你可能不应该将实例的创建放入setUp
中。
或者您创建 TestCase 的两种变体,一种用于所有依赖工厂的测试,另一种用于不依赖工厂的测试。
<小时/>关于tearDown
的使用,请检查这个答案:Django when to use teardown method
关于django - 工厂男孩 : how to teardown?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26937219/