django - 工厂男孩 : how to teardown?

标签 django unit-testing factory-boy

我不明白 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/

相关文章:

Django Factory Boy 创建 vs create_batch

python - 如何使用 FactoryBoy 指定列表大小

python - Django:使用 L10N 将 DateTimeField 转换为字符串

jquery - 如何延迟重定向到页面,直到数据加载到 django 或 jquery 中?

django - 我可以使用 prefetch_related 来缓存过滤的查询集吗?

asp.net-mvc - 如何在ASP.NET MVC中模拟模型?

django - 使用带有静音信号的factory_boy时如何测试信号

django - 如何再次将 templatetag 的返回值插入到 {% if - 中

javascript - Reactjs 功能组件中的 Jest SpyOn

javascript - Jest 对调用返回 Promise 的函数的函数进行单元测试