A couple releases back Salesforce provided a new annotation @testSetup for your fun loving Apex Test classes. Over the past months I’ve used this more and more for my unit testing, and now its my go to on initial test class creation. Along the way I had questions and thoughts about this new functionality that I want to share:
Should this replace a test data utility/factory?
In my opinion no, I still use a “TestDataUtility” that has methods to quickly give me 10 accounts, 250 leads, etc. What I actually do is call that utility inside my @testsetup method, make any additional modifications, and then perform DML
What are the benefits of @testSetup?
So one thing you would assume is the data is automatically available throughout the test class, but that’s not the case. If you insert records in a @testSetup method, you can’t reference them throughout the class in other unit test methods, you have to query for them. So you may ask….what’s the point? I can think of a couple:
- You still consolidate your test data in one method for the entire class. It gives you a great baseline for your unit tests.
- From my brief performance review, it actually ran quicker to query for the data each time than to keep performing DML in each unit test method. In some cases it was 20-35% faster on runtime. Granted there could be environment factors, but still a performance increase.
- Edits and modifications are quicker. If my baseline is off because of changed or new requirements and the edits don’t belong in the test data utility, I still only edit in once place, the @testSetup method.
How difficult is it to use this new annotation?
I started on the fence about using this, but quickly found my rhythm with using @tesSetup. It became really handy with my test classes that blossomed into 4-5 unit test methods. Now by default its the first thing I do in a test class.