Salesforce has finally introduced a way to create test data for an entire test class; this will be a huge time savings for developers.
The rollback of records created during execution happens at the end of the test class’ execution. By only inserting records once, we should see tests run faster and require less system resources.
Lately, I have been updating all of my test classes to use this new @testSetup annotation. One thing to keep in mind, is that it will not set static variables and has a bug for package developers.
Here’s some sample code:
@isTest private class join_Controller_Test { @TestSetup static void CreateTestData() { Util_TestSetup.createSettings(); Account acc = Util_TestSetup.createAccount(); Util_TestSetup.createContact(acc.Id); Util_TestSetup.createOpportunity(acc); } static testMethod void Test_Load() { Account acc = [select Id from Account]; PageReference p = new PageReference('apex/internal_join'); p.getParameters().put('acc', acc.Id); Test.setCurrentPage(p); test.startTest(); internalJoin_Controller controller = new internalJoin_Controller(); system.assertEquals(null, controller.OnLoad() ); system.assertNotEquals(null, controller.acc ); test.stopTest(); } }
I hope that the addition of @testSetup will finally result in better tests on Salesforce. As most programmers with test experience know, testing in Salesforce isn’t usually true unit testing.
Most are usually coded to be integration tests instead. Unit tests are tests that written to verify small sections (“units”) of code; integration testing is testing how the different units work together.
Another common, and disturbing trend, is that most programmers are simply coding unit tests to just get the 75% coverage and not using asserts. By using asserts, the tests can help significantly reduce bugs before code leaves development.