I know how test data setup method and test data factory works.

But I was wondering, if we can create test data in data setup method then why do we need the test data factory class?

Is the data factory class only used because of quick data creation in test classes or there is other technical reasons like governor limits?

2 Answers 2


By far one of the biggest reasons you should consider a test data factory "must have" is that it centralizes data creation, so you can have one single file to fix if you add validations that break tests.

As an example, let's say you for some reason add a Validation Rule that Account.Name must start with 'foo'. If you have dozens of test classes which each locally create Account records to work with, you are going to have to modify all those files. If in the same example, you used a data factory, you would just need to update a required fields cache somewhere.


A Test Data Factory is used to create all your records you need for your tests in one place. This makes it easy to fix your unit tests when a validation rule or new required field is added. It also arguably reduces the complexity of your code, since you're now effectively using a factory pattern to create all of your data, which reduces the amount of code you're repeating (the DRY principle).

A @testSetup method, in contrast, sets up a miniature mock database for all unit tests in the same class to use. This can significantly reduce test runtime by setting up common data for all tests to use. In addition, if done correctly, it can reduce governor limits usage in all of your unit tests, meaning you can get more done with fewer tests.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .