In unit test should i create new model object or use model object from production database?

Hello there,
In the unit test, I am testing a patch method.
In the patch method, I need to provide a model object.

1) Use production database
I can have a model object from the production database as follow.

  1. Fetch a record from database: place=Place.objects.filter()[:1]
  2. Create fixture
    with open('praticeapp/fixtures/test_data.json', 'w') as f: serializers.serialize('json', place, indent=4, stream=f)
  3. Load fixture in test database
    management.call_command(loaddata.Command(), 'praticeapp/fixtures/test_data', verbosity=0)

2) Create model object
In the second option, I can create place object directly.
place=Place.objects.create(name="The ajay",address="Surat")

I am considering first option becaues in real model i have many models with many fields.
If any of the field will be change in future, testing will stop working. I have also found first option from django official documentation but in first option i have to write more code compare to second one.
I am not able to decide which option is better.
Thank you in advance.

Unless your testing requires using specific data from your production database, I would caution against it. When doing unit tests, I find that it is most effective to be able to quickly create synthetic test data that accurately approximates production data.

One fantastic tool for doing this is factory_boy. factory_boy is a toolkit for creating test data that you can use in unit tests. The documentation is pretty good and shows how you could create this data. https://factoryboy.readthedocs.io/en/latest/index.html

I like factory_boy a lot because it allows me to compose together all the database records that I require. It has tools for creating related records that you would likely need when dealing with ForeignKey relationships, for instance.

The package is one of the most used tools that I have in my testing toolbox.

2 Likes