如何让 DjangoModelFactory 创建模型而不保存到 DB?
How to let DjangoModelFactory create a model without saving it to the DB?
我正在 Django 项目中编写单元测试。我有一个工厂可以使用 .create()
方法创建对象。所以在我的单元测试中我使用这个:
device = DeviceFactory.create()
虽然这总是在数据库中创建一条记录。有没有办法让工厂创建一个对象而不将其保存到数据库?
我查看了文档,但找不到。我错过了什么吗?
Quoth 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()
我正在 Django 项目中编写单元测试。我有一个工厂可以使用 .create()
方法创建对象。所以在我的单元测试中我使用这个:
device = DeviceFactory.create()
虽然这总是在数据库中创建一条记录。有没有办法让工厂创建一个对象而不将其保存到数据库?
我查看了文档,但找不到。我错过了什么吗?
Quoth 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()