【问题标题】:How to let DjangoModelFactory create a model without saving it to the DB?如何让 DjangoModelFactory 创建模型而不将其保存到数据库?
【发布时间】:2020-02-29 23:22:42
【问题描述】:

我正在一个 Django 项目中编写单元测试。我有一个使用.create() 方法创建对象的工厂。所以在我的单元测试中我使用这个:

device = DeviceFactory.create()

不过,这总是会在数据库中创建一条记录。有没有一种方法可以让工厂创建一个对象而不将其保存到数据库中?

我查看了文档,但找不到。我错过了什么吗?

【问题讨论】:

    标签: python django unit-testing factory factory-boy


    【解决方案1】:

    this bit of the documentation,用.build()代替.create()

    # Returns a User instance that's not saved
    user = UserFactory.build()
    
    # Returns a saved User instance.
    # UserFactory must subclass an ORM base class, such as DjangoModelFactory.
    user = UserFactory.create()
    
    # Returns a stub object (just a bunch of attributes)
    obj = UserFactory.stub()
    
    # You can use the Factory class as a shortcut for the default build strategy:
    # Same as UserFactory.create()
    user = UserFactory()
    

    【讨论】:

    • 哈哈,发生在我们最好的人身上。 :)
    猜你喜欢
    • 2021-02-18
    • 2019-09-29
    • 1970-01-01
    • 2017-02-22
    • 2016-10-30
    • 2020-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多