When testing, how/when will
@TestSetup
annotation be preferable to a “DataFactory”?I understand how both works, but I don’t see any case where I’d rather use the
@testSetup
annotation.I use this datafactory and it works very well.
Answer
A major reason to use @TestSetup
is the situation where you have many tests that require the same baseline of data. The @TestSetup
method runs once and all its data is available to all the test methods in the class. Any changes made by a test method are rolled back but the @TestSetup
data isn’t. The benefit is faster test running because the baseline data inserts are only done once per test class not once per test method.
A downside is that the only way to get references to the data created in @TestSetup
is to query for it. But those queries are much cheaper than the inserts.
(The @TestSetup
method also gets its own set of governor limits, so if you have a lot of data setup logic that consumes a big proportion of those, moving it to @TestSetup
will help.)
I use @TestSetup
sometimes, and other times, when I want to refer to the test data in the following asserts, use builder classes invoked from each test method so I have references to the test objects without having to do queries.
You can choose to use whatever technique you like to create the SObjects and use that method inside the @TestStup
method or outside of it.
Some more information on @TestSetup: What are the advantage of the @testSetUp annotation.
Attribution
Source : Link , Question Author : Alexis MASSON , Answer Author : Keith C