我正在Django项目中编写单元测试。我有一家工厂使用.create()
方法创建对象。所以在我的单元测试中,我使用的是这个:
device = DeviceFactory.create()
这总是在数据库中创建一条记录。有没有一种方法可以使工厂在不将其保存到数据库的情况下创建对象?
我查看了文档,但找不到。我想念什么吗?
答案 0 :(得分:3)
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()